text:
Q: How to create single column Filter (Choices) Drop-down (select) Django form? Good day!
I would be very grateful for any help.
I have a model.
There are repeating elements in one column of this model.
I want to inject the result of a query into a view.
The result of a query with a single column filter.
That is, it turns out that I want to take from the model only those rows of the table -->> where the value is equal to the one selected from the drop-down menu (in a simple filter form).
['Gary', 'Henry', 'Shtefan', 'Villi']
For example, select only those rows in the row (empname) whose value is equal to Shtefan.
Without the use of a static, manual entry in the code.
Since it is possible that when the model table is replenished - with new data - there will be additions with other names.
Is it possible somehow to take unique values without duplicates from the corresponding column and automatically use them in the filter?
To be placed in a drop-down menu form (in a simple filter form).
static
class Developer(models.Model):
    JUNIOR = 'JR'
    MIDDLE = 'ML'
    SENIOR = 'SR'

    LEVEL_CHOICES = (
        (JUNIOR, 'Junior'),
        (MIDDLE, 'Middle'),
        (SENIOR, 'Senior'),
    )
    name = models.CharField(max_length=200)
    level = models.CharField(max_length=2, choices=LEVEL_CHOICES, default=JUNIOR)

my Model
class EmployeeModel(models.Model):
    empid = models.IntegerField(primary_key=True)
    empname = models.CharField(max_length=50)
    salary = models.IntegerField()
    joindate = models.DateField()
    class Meta:
        db_table = "employee"

filters
class BookFilter(django_filters.FilterSet):
    class Meta:
        model = EmployeeModel
        fields = ['empname']

views
def showresults(request):
    header = "HYSTORY DATA"
    queryset = EmployeeModel.objects.all()
    form = StockHistorySearchForm(request.POST or None)

    book_filter = BookFilter(request.GET, queryset)

    date_from_model = queryset.values_list()
    df_from_qs = read_frame(date_from_model)
    print(df_from_qs)

    distinct_users = EmployeeModel.objects.all().values_list('empname', flat=True).distinct()
    distinct_users = list(distinct_users)
    print(distinct_users)
    print(type(distinct_users))

    my_tuple = ()

    fig = px.line(
        df_from_qs, x="joindate", y="salary", title='Graph')
    fig.update_layout(title = {
        "font_size": 22,
        "xanchor": "center",
        "x": 0.5
    })
    chart = fig.to_html()

    context = {
        "header":header,
        "queryset":queryset,
        "form":form,
        'form2':book_filter.form,
        'chart': chart,
    }
    if request.method == "POST":
        queryset = EmployeeModel.objects.filter(
            joindate__range=[
                form['start_date'].value(),
                form['end_date'].value()
            ]
        )

        book_filter = BookFilter(request.GET, queryset)
        queryset = book_filter.queryset

        date_from_model = queryset.values_list()
        df_from_qs = read_frame(date_from_model)

        fig = px.line(
            df_from_qs, x="joindate", y="salary", title='Graph')
        fig.update_layout(title={
            "font_size": 22,
            "xanchor": "center",
            "x": 0.5
        })
        chart = fig.to_html()

        context = {
            "header": header,
            "queryset": queryset,
            "form": form,
            "form2":book_filter.form,
            'chart': chart,
        }
    return render(request, "demo/index.html", context)

model
    empid  empname  salary    joindate
7       8     Gary    1800  2020-06-22
8       9     Gary   19000  2020-06-21
9      10    Henry   26000  2020-06-10
10     11    Henry   31000  2020-06-15
11     12    Henry   20000  2020-06-18
12     13    Henry   17000  2020-06-13
13     14    Henry   12000  2020-06-14
14     15    Henry   24000  2020-06-17
15     16  Shtefan   12000  2020-06-11
16     17  Shtefan   13000  2020-06-12
17     18  Shtefan   15000  2020-06-13
18     19  Shtefan   18000  2020-06-15
19     20  Shtefan   19000  2020-06-17
20     21  Shtefan   25000  2020-06-19
21     22  Shtefan   34000  2020-06-21
22     23  Shtefan   38000  2020-06-23
23     24  Shtefan   44000  2020-06-25
24     25  Shtefan   30000  2020-06-27
25     26  Shtefan   25000  2020-06-29
26     27    Villi   70000  2020-06-10
27     28    Villi   60000  2020-06-12
28     29    Villi   50000  2020-06-13
29     30    Villi   55000  2020-06-14
30     31    Villi   46000  2020-06-15
31     32    Villi   42000  2020-06-17


text:
Q: smallest value of hash() function? in python (3), what is the smallest value that hash(x) can return?
i want to use hashes to give a quick 'fingerprint' to database values (basically making it easy to see whether two longish, similar texts are actually equal or not), and want to get rid of negative numbers (for simplicity), so i thought i'd just add the smallest possible value to obtain values of zero and up. the manual is very helpfully stating "Hash values are integers." which is about as much as i knew before.
i was a bit surprised today when i found that my hand-compiled python on a 64bit ubuntu apparently uses 64 bits or so for its hashing function; i have always thought that should be 32bit. does machine architecture have an impact on the hash() function?
also, when i compiled python, i did not set any option to compile for a 64bit architecture (hoping it would "just work"). does python adjust that by itself or do i now have a 32bit python on a 64bit machine? not a silly question i believe as many times you are offered separate packages depending on the processer.
edit: i strongly suspect the answer will be closely related to sys.maxint which has been sadly removed from python 3. my suspicion is that i should def xhash( x ): return hash( x ) - ( -maxint - 1 ) if maxint was available. i know this value 'lost its value' due to the unification of ints and longs, but here might be one area where it could still prove useful. anybody have an idea how to implement an analogue?

A: hash() can return any integer, and as you have seen, the size of the integer can vary with the architecture.  This is one of the reasons dictionary ordering is arbitrary: the same set of operations on two different platforms can give different results because the hashes used along the way can differ.
If all you are doing is showing a hash for a quick fingerprint, then simply keep a subset of the bits.  It's still valid as a hash.  The only requirement of a hash function is that equal values must have equal hashes.  After that, differences among hashes simply affect the efficiency of the algorithms using the hash, because the chances of collision go up or down.
So for example, you could decide you want an 8-digit hash, and get it by using:
hash(x) % 100000000

Or you could get an eight-character alphanumeric hash to display with:
md5(hash(x)).hexdigest()[:8]

A: hash functions usually use the full range of the return value.  The reason is that they usually are constructed with bit operations (shifting, xoring, etc) -- the bits in the return value are all used during the algorithm.
Why are positive values easier or harder than negative ones?

A: The answer to your question should be:
assert(hash(100) == 100 and hash(-100) == -100)
smallest_hash_value= -2**min(range(256), key=lambda i: hash(-2**i))

This depends on the fact that Python uses the integer itself as a hash (with the exception of -1) iff the integer is a valid hash() result. The algorithm normally should remain the same whatever the architecture.

A: so today i was luckier at the google casino, and this is what i found:
(1) system architecture whether a given python is running on a 64 or a 32bit machine can be found by
from platform import architecture
print( architecture() )

from the documentation: "Queries the given executable (defaults to the Python interpreter binary) for various architecture information. Returns a tuple (bits, linkage) which contain information about the bit architecture and the linkage format used for the executable. Both values are returned as strings." on my machine, that's ('64bit', 'ELF'). bingo.
(2) smallest integer there is no sys.maxint in python 3 no more, but there is sys.maxsize. the docs say "An integer giving the maximum value a variable of type Py_ssize_t can take. It's usually 2**31 - 1 on a 32-bit platform and 2**63 - 1 on a 64-bit platform." therefore,
from sys import maxsize
assert maxsize == 2**63 - 1

works on my machine.
(3) to directly answer the original question: "the smallest value of the hash() function should be minus whatever sys.maxsize reports. for this reason, it can be expected that
def xhash( x ): return hash( x ) + sys.maxsize + 1

will only ever report values ≥ 0."

redpajama_set_name: RedPajamaStackExchange


text:
Q: Show that any simple set is the union of a finite number of mutually disjoint canonical intervals Show that any simple set is the union of a finite number of mutually
disjoint canonical intervals.
The set of canonical intervals: $\mathcal{I}=\{[a,b) \quad | \quad a,b \in \mathbb{R} \quad \text{and} \quad a < b \}$
Simple sets: A subset $S$ of $\mathbb{R}$ is said to be simple if it's the union of a finite
number of canonical intervals.
-proof-
Let $s_1$ be a simple set $\implies s_1=\cup_{i=1}^{n} I_i$ where each $I_i=[a_i,b_i)$
Now we do relabelling - we re-label the intervals according to their left-end points in this manner -
Let $a_1$ be the minimum taken overall $A=\{a_i\}_{i=1}^{n}$
define $a_2 = a_1$ if $|A|<n-2$ else define $a_2 = \min\{A-a_1\}$ ..etc
Continuing in this manner we then construct $a_1 \leq a_2 \leq a_3 \leq .. \leq a_n$
First,
 $ a_1 \leq a_2 $
case1: if $b_1> b_2 \implies I_1 \supset I_2$ so re-write $s_1 = [a_1,a_2) \cup [a_2,b_1)=[a_1,b_1)$
case 2: if $b_1=b_2 \implies  s_1=[a_1,b_1) \cup [a_2=b_1, b_2)=[a_1,b_2)$
case3:
if $b_2> b_1$ then $s_1=[a_1,a_2) \cup [a_2,b_1) \cup [b_1,b_2)=[a_1,b_2)$
case4: if $a_2 > b_1$
then $s_1 = [a_1,b_1) \cup [a_2,b_2)$ where $[a_1,b_1) \cap [a_2,b_2) = \emptyset$
case5: if $a_2=b_1$ then $s_1 = [a_1,b_1) \cup [a_2=b_1,b_2)=[a_1,b_2)$
then we consider the case where $a_2 \leq a_3$
we continue this process $(n-1)$ times (where everytime we re-write $s_1$ in a manner where we we don't write an overlapped part more than once  until the final case $a_{n-1} \leq a_n$ we will then see that we have constructed s_1$ which is a finite union of pairwise disjoint canonical intervals

I am not sure if my attempt is correct but if there is an easier way, please share an idea with me

A: An approach like yours can be made to work, but there is a completely different approach that is easier, if perhaps less natural.
Define a relation $\sim$ on $S$ as follows: for any $x,y\in S$,
$$x\sim y\text{ iff }[\min\{x,y\},\max\{x,y\}]\subseteq S\;,$$
i.e., $x\sim y$ if and only if the closed interval between $x$ and $y$ is contained in $S$. It's not hard to show that $\sim$ is an equivalence relation on $S$. Let $\mathscr{C}$ be the set of $\sim$-equivalence classes; the members of $\mathscr{C}$ are certainly pairwise disjoint subsets of $S$ whose union is $S$, so we'll be done if we can show that they are canonical sets and that $\mathscr{C}$ is finite.
Let $C\in\mathscr{C}$. $S$ is a bounded set, so $C$ is bounded, and we can let $a=\inf C$ and $b=\sup C$; now we need only show that $C=[a,b)$. Certainly $C\subseteq[a,b]$; I'll show next that $(a,b)\subseteq C$. Suppose that $x\in(a,b)$; then $a<x$, so there is a $c_0\in C$ such that $a\le c_0<x$. Similarly, $x<b$, so there is a $c_1\in C$ such that $x<c_1\le b$. Then $c_0\sim c_1$, so $[c_0,c_1]\subseteq S$, and since $c_0<x$, it's clear that $[c_0,x]\subseteq S$ as well. But then $x\sim c_0\in C$, so $x\in C$, and since $x\in(a,b)$ was arbitrary, it follows that $(a,b)\subseteq C$. Now we must show that $a\in C$ and $b\notin C$.
Suppose that $b\in C$. Then $b\in S$, so there is an $i\in\{1,\ldots,n\}$ such that $b\in I_i=[a_i,b_i)$. Then $b<b_i$, so choose any $x\in(b,b_i)$; $x\in S$, and $[b,x]\subseteq I_i\subseteq S$, so $b\sim x$, and therefore $x\in C$, contradicting the definition of $b$ as $\sup C$. This shows that $b\notin C$.
Now suppose that $a\notin C$; $a=\inf C$, so there is a strictly decreasing sequence $\langle x_k:k\in\Bbb Z^+\rangle$ in $C$ converging to $a$. Each of the points $x_k$ belongs to one of the sets $I_i$ with $i\in\{1,\ldots,n\}$, and there are only finitely many of these sets $I_i$, so there must be some $i\in\{1,\ldots,n\}$ such that $A=\{k\in\Bbb Z^+:x_k\in I_i\}$ is infinite. Now $\{x_k:k\in A\}\subseteq[a_i,b_i)$, so
$$a_i=\inf[a_i,b_i)\le\inf\{x_k:k\in A\}=a\;.$$
Pick any $k\in A$; then $[a,x_k]\subseteq[a_i,x_k]\subseteq S$, so $a\sim x_k\in C$, and therefore $a\in C$. This completes the proof that $C=[a,b)$ and hence that the partition of $S$ into $\sim$-equivalence classes is a partition of $S$ into canonical intervals.
Finally, it's easy to check that for each $C\in\mathscr{C}$ there is an $i(C)\in\{1,\ldots,n\}$ such that $I_i\subseteq C$ and that the map $\mathscr{C}\to\{1,\ldots,n\}:C\mapsto i(C)$ is injective, so that $|\mathscr{C}|\le n$.

A: I think a variation on your technique might be a bit more rigorous and a bit easier.
The statement to prove is this: given a simple set $S = \bigcup_{i=1}^{n} I_i$, the set $S$ can be rewritten as a disjoint union of canonical intervals.
Here's a proof by induction on $n$.
The basis step is $n=1$, and so $S=I_1$ is a union of just one canonical interval.
Suppose that the statement is true for $n-1$, and so in particular the set $S' = \bigcup_{i=1}^{n-1} I_i$ can be written as a disjoint union of canonical intervals, $S' = \bigcup_{j=1}^m J_j$, for some $m$ and some canonical intervals $J_j = [a_j,b_j)$ such that
$$(*) \,\, - \infty = b_0 \,\,<\,\, a_1 \,\,<\,\, b_1 \,\,\le\,\, a_2 \,\,<\,\, b_2 \,\,\le\,\, a_3 < \cdots  < b_{m-1} \,\, \le \,\,a_m \,\,<\,\, b_m \,\,<\,\, a_{m+1} = +\infty
$$
By convention I'm setting $b_{0}=-\infty$ and $a_{m+1}=+\infty$.
So $S = S' \cup I_n$ can be rewritten
$$(\#) \qquad S = \bigcup_{j=1}^m J_j \cup \underbrace{I_n}_{=[a',b')}
$$
We now look at where $a'$ and $b'$ fit into the sequence $(*)$, and using that information we identify exactly how to alter the terms of the union $(\#)$ in order to get a disjoint union such that the value of that union is still equal to $S$.
Let $j \in \{0,1,...,m,m+1\}$ be the minimal value such that $b_{j-1} \le a'$. It follows that $a_j,a' \in [b_{j-1},b_j)$.
Let $k \in \{0,1,...,m,m+1\}$ be the maximal value such that $b' \le a_k$. It follows that $b_{k-1},b' \in (a_{k-1},a_k]$.
Noting that $b_{j-1} \le a' < b' \le a_k$, it follows that $j \le k$.
Case 1: If $j=k$ then the union $(\#)$ is already disjoint and we are done.
Case 2: If $j<k$ then, the union $(\#)$ becomes disjoint, without changing the value of the union, by removing the terms $[a_j,b_j)$, ... ,$[a_{k-1},b_{k-1})$ and inserting a new term
$$\bigl[\min\{a_j,a'\},\max\{b_{k-1},b'\}\bigr)
$$


text:
Q: How to combine Duplicate data into single Data MySql I was wondering if what is this called or is this even possible in MySql, or what should I do to achieve this. This is what Mysql Table Looks Like:

Desired Output:

A: Your table structures wont allow (anything near as easy).  A better format of your table might be more like
id   customerid   item      qty
1    15           Car       7
2    15           Car       2
3    15           Engine    3
4    15           Engine    2
5    15           Exhaust   5

Then, you could get what you are looking for easily such as
select
      t.customerid,
      t.item,
      sum( t.qty )
   from
      YourTable t
   group by
      t.customerid,
      t.item

This WOULD give your your
customerid  item      qty
15          Car       9
15          Engine    5
15          Exhaust   5

Having a properly formatted table vs trying to have a description requires parsing numeric values vs rest of description is never a good solution such as what you have here.  Too many opportunities for bad answers.

A: you can use a query like this:
SELECT  customerid
 , CONCAT( SUM(CAST(item as INTEGER)), 'pcs,', SUBSTRING_INDEX(item, ',', -1) ) as item
FROM myitems
GROUP BY SUBSTRING_INDEX(item, ',', -1);

Sample
MariaDB [bernd]> SELECT * FROM myitems;
+----+------------+---------------+
| id | customerid | item          |
+----+------------+---------------+
|  1 |         15 | 7pcs, Car     |
|  2 |         15 | 2pcs, Car     |
|  3 |         15 | 3pcs, Engine  |
|  4 |         15 | 2pcs, Engine  |
|  5 |         15 | 5pcs, Exhaust |
+----+------------+---------------+
5 rows in set (0.07 sec)

MariaDB [bernd]> SELECT customerid
    ->      , CONCAT( SUM(CAST(item as INTEGER)), 'pcs,', SUBSTRING_INDEX(item, ',', -1) ) as item
    ->     FROM myitems
    ->     GROUP BY SUBSTRING_INDEX(item, ',', -1);
+------------+---------------+
| customerid | item          |
+------------+---------------+
|         15 | 9pcs, Car     |
|         15 | 5pcs, Engine  |
|         15 | 5pcs, Exhaust |
+------------+---------------+
3 rows in set, 5 warnings (0.02 sec)

MariaDB [bernd]>


text:
Q: How to specify a variable expression list in a Pro*C query? I have a problem with a Pro*C query I'm trying to optimise.
To explain, our application searches for rows in a huge database. These rows exist in several languages and the old code selected a row for each language in an array. Now as these queries are the most time consuming part of our app, I wanted to make only one query which writes directly in an array.
The language codes are 2 letter ISO-639 codes (en for english, fr for french).
Old way (this is only a simplified code to show the intention)
struct ROW arr[MAX_LAN];
struct ROW_IND arr_ind[MAX_LAN];
uint_t LanIdx;
for(LanIdx=0; LanIdx<MAX_LAN; LanIdx++) {
  EXEC SQL SELECT *  /* Don't look at the *, it's for obfuscation only */
      INTO :arr[LanIdx]:arr_ind[LanIdx]
      FROM table WHERE id=:uniqid AND language=:LanCode[LanIdx];
}

I would like to do something like this:
EXEC SQL SELECT *  /* Don't look at the *, it's for obfuscation only */
    INTO :arr:arr_ind
    FROM table WHERE id=:uniqid AND language IN (:LanCodes);

but do not know how I should define LanCodes.
It works with a constant (compile time) list like this
EXEC SQL SELECT *  /* Don't look at the *, it's for obfuscation only */
    INTO :arr:arr_ind
    FROM table WHERE id=:uniqid AND language IN ('en','fr','de');

but this is not useful, as the languages may vary from case to case.
If I write something like
char LanCodes[MAX_LANS*5];
sprintf(LanCodes, "%s", LanCode[LanIdx]);

EXEC SQL SELECT *  /* Don't look at the *, it's for obfuscation only */
    INTO :arr:arr_ind
    FROM table WHERE id=:uniqid AND language IN (:LanCodes);

it works only if there is 1 language code in the string.
So my question is, does anybody know how to make this work? The Oracle documentation is so big, I don't know where to look at. I tried different ways, but none worked.
EDIT
Ok, I found a solution that works. It's not elegant, it's not advanced but it works well. I put a list of OR clauses in my query and it returns what I need in the form that I need.
EXEC SQL SELECT *  /* Don't look at the *, it's for obfuscation only */
    INTO :arr:arr_ind
    FROM table WHERE id=:uniqid AND (
                language=:v1[ 0] OR
                language=:v1[ 1] OR
                language=:v1[ 2] OR
                language=:v1[ 3] OR
                language=:v1[ 4] OR
                language=:v1[ 5] OR
                language=:v1[ 6] OR
                language=:v1[ 7] OR
                language=:v1[ 8] OR
                language=:v1[ 9] OR
                language=:v1[10] OR
                language=:v1[11] OR
                language=:v1[12] OR
                language=:v1[13] OR
                language=:v1[14] OR
                language=:v1[15] OR
                language=:v1[16] OR
                language=:v1[17] OR
                language=:v1[18] OR
                language=:v1[19] OR
                language=:v1[20] OR
                language=:v1[21] OR
                language=:v1[22] OR
                language=:v1[23] OR
                language=:v1[24] OR
                language=:v1[25] OR
                language=:v1[26] OR
                language=:v1[27] OR
                language=:v1[28] OR
                language=:v1[29] OR
                language=:v1[30]);

It's faster when there is more than 2 languages, so I call this variant or the old one depending on number of languages to fetch.

A: You can't do this without Oracle Dynamic SQL. You will have to build your IN clause at runtime and EXECUTE IMMEDIATE. At least you can use Method 1, based on your queries.

A: Probably this AskTom article can help you.

A: I have used a table before composed of an ID and a set of rows where the rows are the permutation of the possible values in the "in" list.  Then I join to the table based on the
ID and it gives me the results I need.
create table permute (
  id number,
  lang char(2)
);
create index permute_p1 on permute ( lang, id );
insert into permute ( id, lang ) values ( 1, 'en' );
insert into permute ( id, lang ) values ( 2, 'en' );
insert into permute ( id, lang ) values ( 2, 'fr' );
...

All you have to do then is pick the correct "ID" value 2, 3, 4 ... and put that into the
join.

A: ...
Main String:= 'Select * FROM table WHERE id=:uniqid AND language IN'; -- can split into two to accomadate :uniqd
...
Select Language_code into v_string
from x_table;
loop
 Copy & Concat v_string to LanCode_String and with ' ', ;
end loop;
..
Concat Lancode to Main String.
..
Prepare and execute the Main String.


text:
Q: An initial- and boundary-value problem for Burgers' equation with no solution Prove that there is no solution to the following Cauchy problem:
$$\begin{align}
u_t+uu_x& =0&\quad x&\in(-1,1), t\gt0 \label{1}\tag{1}\\
u(x,0)&=x&\quad x&\in[-1,1] \label{2}\tag{2}\\
u(-1,t)&=-1& \quad t&\geq0 \label{3}\tag{3}\\
u(1,t)&=1&\quad t&\geq0 \label{4}\tag{4}
\end{align}$$
My attempt: Using the method of characteristics, I found the classical solution
$$
u=\frac{x}{1+t} \quad t\gt{-1}
$$
which satisfies conditions \eqref{1} and \eqref{2}, but not \eqref{3} and \eqref{4}.

But how can I show that there is also no weak solution to this problem?

Thanks in advance.

A: In facts, it is impossible for a classical solution to solve the initial- and boundary-value problem. A plot of the characteristic curves in the $x$-$t$ plane deduced from the initial data is given below*:

The possibility of admissible discontinuities near the boundaries (weak solutions) should be examined. A look at the characteristics in the $x$-$t$ plane shows that such solutions are not admissible in the sense of Lax** (characteristics do not intersect appropriately). For example, at $x\simeq 1$, we have $u_R = 1$ and $u_L = 1/(1+t)<1$, so that $u_L < u_R$. No shock wave is admissible. Alternatively, we could have investigated the boundary $x\simeq -1$, where $u_L = -1$ and $u_R = -1/(1+t) > -1$. Here too, no shock wave is admissible, since $u_L < u_R$.

*The lines drawn outside $]-1,1[$ are the characteristics starting at the boundaries $x=\pm 1$, which have been represented outside the interior domain to keep the figure readable.
**The Lax entropy condition reads $u_L>s>u_R$ where $u_L$ is the value on the left of the discontinuity, $u_R$ is the value on the right of the discontinuity, and $s$ is the speed of shock given by Rankine-Hugoniot.


text:
Q: Pdf support in php 5.2.17 version My php version is 5.2.17. I want to create a pdf using php. i have written this code
$mypdf = PDF_new();
        PDF_open_file($mypdf, "");
        PDF_begin_page($mypdf, 595, 842);
        $myfont = PDF_findfont($mypdf, "Times-Roman", "host", 0);
        PDF_setfont($mypdf, $myfont, 10);
        PDF_show_xy($mypdf, "Sample PDF, constructed by PHP in real-time.", 50, 750);
        PDF_show_xy($mypdf, "Made with the PDF libraries for PHP.", 50, 730);
        PDF_end_page($mypdf);
        PDF_close($mypdf);

        $mybuf = PDF_get_buffer($mypdf);
        $mylen = strlen($mybuf);
        header("Content-type: application/pdf");
        header("Content-Length: $mylen");
        header("Content-Disposition: inline; filename=gen01.pdf");
        print $mybuf;

        PDF_delete($mypdf)

;
this code is working perfectly on my localhost but on my server this is not working . On my server $mypdf is not created. on my server php 5.2.17 version is used. what is the problem ? i thinks pdf library is not working on my srever. Please help me

A: Make sure your server has PDFlib installed.


text:
Q: django categories views(error page not found) my task is to create on main page of my web site two list one list for my post
and second list categories titles which belong my post.
i create that and work fine,and i create post details connect and again work fine.
but i cant to work category details if i want to see list from my post which belong specific category i cant show me error page not found.
my code
my model
class Category(models.Model):
 categorytitle =models.CharField(max_length=1,choices=CAT_CHOICES,unique=True)
 slug= models.SlugField()

class Posts(models.Model):
    Title = models.CharField(max_length=100,blank=True)
    slug= models.SlugField()
    category = models.ManyToManyField(Category)

my view category
def view_category(request, slug):
category = get_object_or_404(Category, slug=slug)
return render_to_response('blog/view_category.html', {
    'category': category,
    'posts': Posts.objects.filter(category=category)
})

my urls category
url(r'^(?P<slug>[^\.]+)/$', views.view_category, name='view_category'),

main template tags
{% for category in categories %}

{{ category.categorytitle }}

{% endfor %}

error message
Page not found (404)
Request Method:
GET
Request URL:
http://127.0.0.1:8000/category1/
Raised by:
blog.views.view_post
No Posts matches the given query.
my view post
def view_post(request, slug):
    return render_to_response('blog/movies_details.html', {
        'post': get_object_or_404(Movies,slug=slug)
    })

my urls view
url(r'^(?P<slug>[^\.]+)/$', views.view_post, name='view_post'),

if i use browser db for sqlite view

A: Change your regex in urls.py to:
url(r'^(?P<slug>[\w-]+)/$', views.view_category, name='view_category'),

\w = alphanumeric signs + underscore
- = hyphen
(These characters are now allowed in the slug)
And change the Post filter to:
Posts.objects.filter(category_id=category.id)

NOTE:

*

*Posts filtering have to placed before rendering, not in it (do it in the same way like "category")

*How do you create slugs in the Category model? In admin? Manually or automatically via prepopulated_fields? Because I don'ŧ like in the categorytitle field the max_length=1

A: If your error message shows: "Raised by: blog.views.view_post" Than obviously django is hitting view_post function in your views and not view_category.
Due to wrong function call view_post can't find the post with slug:"category1" so gives a 404 error ( obviously!! ).
So i will suggest to check out if there is a url mismatch that is causing this first.

A: So I had a similar problem, did all I could by reading various solutions and none was helpful. My solution was real funny(ironic) since I spent an hour to find out what was wrong.
In the urls.py, the order of the url s is pretty important.
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('shop.urls')),
    url(r'^shpcart/', include('shpcart.urls')),
]

The above pattern kept saying 404 shpcart/ not found, but shpcart was already there.
Just as I was about to find myself trying to persuade the pc, I moved the shpcart url 1 line above, everything started to sound. If anyone is stuck like I was, hope this helps
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^shpcart/', include('shpcart.urls')),
    url(r'^', include('shop.urls')),
]


text:
Q: Login Error on Kibana\ElasticSearch console this morning i can't access to my kibana console, that return me a "Oops! Error. Try again." error from the login page.
Yesterday, the only thing i did
was set number_of_replicas setting of the .apm-agent-configuration index to 0 because i had a lot of replicas not assigned.
This is the log i can read from /var/log/kibana/kibana.log on my kibana server:

{"type":"log","@timestamp":"2022-04-21T12:02:59+02:00","tags":["info","plugins","security","routes"],"pid":1136,"message":"Logging in with provider "basic" (basic)"}
{"type":"log","@timestamp":"2022-04-21T12:02:59+02:00","tags":["error","plugins","security","session","index"],"pid":1136,"message":"Failed to create session value: cluster_block_exception"}
{"type":"log","@timestamp":"2022-04-21T12:02:59+02:00","tags":["error","http"],"pid":1136,"message":"ResponseError: cluster_block_exception\n    at onBody (/usr/share/kibana/node_modules/@elastic/elasticsearch/lib/Transport.js:337:23)\n    at IncomingMessage.onEnd (/usr/share/kibana/node_modules/@elastic/elasticsearch/lib/Transport.js:264:11)\n    at IncomingMessage.emit (events.js:387:35)\n    at endReadableNT (internal/streams/readable.js:1317:12)\n    at processTicksAndRejections (internal/process/task_queues.js:82:21) {\n  meta: {\n    body: { error: [Object], status: 429 },\n    statusCode: 429,\n    headers: {\n      'content-type': 'application/json; charset=UTF-8',\n      'content-length': '435'\n    },\n    meta: {\n      context: null,\n      request: [Object],\n      name: 'elasticsearch-js',\n      connection: [Object],\n      attempts: 0,\n      aborted: false\n    }\n  }\n}"}
{"type":"error","@timestamp":"2022-04-21T12:02:59+02:00","tags":[],"pid":1136,"level":"error","error":{"message":"Internal Server Error","name":"Error","stack":"Error: Internal Server Error\n    at HapiResponseAdapter.toInternalError (/usr/share/kibana/src/core/server/http/router/response_adapter.js:61:19)\n    at Router.handle (/usr/share/kibana/src/core/server/http/router/router.js:177:34)\n    at runMicrotasks ()\n    at processTicksAndRejections (internal/process/task_queues.js:95:5)\n    at handler (/usr/share/kibana/src/core/server/http/router/router.js:124:50)\n    at exports.Manager.execute (/usr/share/kibana/node_modules/@hapi/hapi/lib/toolkit.js:60:28)\n    at Object.internals.handler (/usr/share/kibana/node_modules/@hapi/hapi/lib/handler.js:46:20)\n    at exports.execute (/usr/share/kibana/node_modules/@hapi/hapi/lib/handler.js:31:20)\n    at Request._lifecycle (/usr/share/kibana/node_modules/@hapi/hapi/lib/request.js:370:32)\n    at Request._execute (/usr/share/kibana/node_modules/@hapi/hapi/lib/request.js:279:9)"},"url":"https://consoleids.enac.gov.it/internal/security/login","message":"Internal Server Error"}
{"type":"response","@timestamp":"2022-04-21T12:02:59+02:00","tags":[],"pid":1136,"method":"post","statusCode":500,"req":{"url":"/internal/security/login","method":"post","headers":{"host":"consoleids.enac.gov.it","connection":"keep-alive","content-length":"171","sec-ch-ua":"" Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"","content-type":"application/json","sec-ch-ua-mobile":"?0","user-agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36","kbn-version":"7.13.3","sec-ch-ua-platform":""Windows"","accept":"/","origin":"https://consoleids.enac.gov.it","sec-fetch-site":"same-origin","sec-fetch-mode":"cors","sec-fetch-dest":"empty","referer":"https://consoleids.enac.gov.it/login?next=%2F","accept-encoding":"gzip, deflate, br","accept-language":"it-IT,it;q=0.9,en-US;q=0.8,en;q=0.7"},"remoteAddress":"10.144.9.168","userAgent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36","referer":"https://consoleids.enac.gov.it/login?next=%2F"},"res":{"statusCode":500,"responseTime":65,"contentLength":97},"message":"POST /internal/security/login 500 65ms - 97.0B"}

Could u help understand the problem?
Thanks,


text:
Q: generator with conditions in python which is taken from the predefined interval [a=10000, b=99999]
will fill the list (lst) with a random value, taking into account the following principle: on an even index
The sum of the standing digits is equal to the sum of the standing digits on the odd index

A: Here is a hit-or-miss generator that works well for numbers in your range:
import random

def even_odd_places(n):
    evens = []
    odds = []
    for i,d in enumerate(str(n),start = 1):
        if i % 2 == 0:
            evens.append(int(d))
        else:
            odds.append(int(d))
    return evens,odds

def check_condition(n):
    e,o = even_odd_places(n)
    return sum(e) == sum(o)

def rand_nums(a,b,max_tries = 1000):
    tries = 0
    while True:
        tries += 1
        n = random.randint(a,b)
        if check_condition(n):
            tries = 0
            yield n
        else:
            if tries == max_tries:
                return None

For example:
g = rand_nums(10000, 99999)
s = [next(g) for _ in range(10000)]
print(s[:5])
#typical output: [25641, 45980, 38225, 34320, 94380]

Something better than a hit-or-miss approach would require some nontrivial mathematical analysis. There is no easy way to generate all numbers in a given range which satisfy the target condition.


text:
Q: What is the trick in covering GE Lat/Long back to x,y? There are there numerous historical threads talking about converting screen x,y to Lat Long and hypothetically in my excel sheet I can convert x,y and lat longs back and forth all day, but once I export the x,y as lat/longs into a KML file important into Google Earth the link is broken.  If I save the shape I just important, and run that back through my calculation process the x,y cords are so far off I can't relay on them for anything.
My process for making x,y is pretty basic:  Lat or Long = (x or y * delta + base lat/long)
The inverse is not as basic but doable: x or y = (lat or long / delta) - (base lat or lont / delta).
This works all day long in excel without any issues, but once Google Earth gets involved the resulting x,y pairs are so bad its not funny any longer.
What do I need to do to get GE exported lat longs to be more 'accurate' to what I expect the x,y pairs to be (or what they are in excel)?
Thanks.

A: It sounds like you're not accounting for the cos(base_latitude) factor in your delta-x formula.
One degree of latitude is the same distance everywhere, but one degree of longitude, measured at the equator, is a longer distance than one degree of longitude measured at 45 deg north.


text:
Q: Oracle DBMS_APPLICATION_INFO.SET_MODULE equivalent in PostgreSQL I am trying to migrate thr Oracle function DBMS_APPLICATION_INFO.SET_MODULE to PostgreSQL. What would be the equivalent in PostgreSQL?
DBMS_APPLICATION_INFO.SET_MODULE(value1,value2);

A: There is no direct equivalent in PostgreSQL.
The closest would be to set the application_name parameter, for example with the SQL statement SET.
That allows you to distinguish this database session from others on the server side.


text:
Q: Can I run Python 2.7 and Python 3.6 builds on same installation of anaconda? How? I currently have a Python 2.7 build of anaconda. But I'm facing issues following some other Python 3.6 codes. So, I am looking for a solution by which I can keep both versions of anaconda running in the same build.
Thanks for any help!


text:
Q: Set static field value once and use the latest set value in all other threads As working on multi-threaded application, I have once scenario where I need to assign value to static field. I want to use the latest value of static field in all rest of the threads.
Code is seems like below:
Main() Method:
for (var i = 1; i <= 50; i++)
{
  ProcessEmployee processEmployee = new ProcessEmployee();

  Thread thread = new Thread(processEmployee.Process);
  thread.Start(i);
}

public class ProcessEmployee
    {
        public void Process(object s)
        {

            // Sometimes I get value 0 even if the value set to 1 by other thread.
            // Want to resolve this issue.
            if (StaticContainer.LastValue == 0)
            {
                Console.WriteLine("Last value is 0");

            }

            if (Convert.ToInt32(s) == 5)
            {
                StaticContainer.LastValue = 1;
                Console.WriteLine("Last Value is set to 1");
            }

            // Expectation: want to get last value = 1 in all rest of the threads.
            Console.WriteLine(StaticContainer.LastValue);
        }
    }

public static class StaticContainer
    {
        private static int lastValue = 0;

        public static int LastValue
        {
            get
            {
                return lastValue;
            }
            set
            {
                lastValue = value;
            }
        }
    }

Question:
Basically, I want to know that once I set specific value to static field by any thread, I want to get the same value (latest value set by another thread) in rest of the threads always.
Please do give me any idea on this.
Thanks in advance!

A:
Basically, I want to know that once I set specific value to static field by any thread, I want to get the same value (latest value set by another thread) in rest of the threads always.

It sounds like you're basically missing a memory barrier. You could work this out with explicit barriers but no locks - or you could just go for the brute-force lock approach, or you could use Interlocked:
private static int lastValue;

public int LastValue
{
    // This won't actually change the value - basically if the value *was* 0,
    // it gets set to 0 (no change). If the value *wasn't* 0, it doesn't get
    // changed either.
    get { return Interlocked.CompareExchange(ref lastValue, 0, 0); }

    // This will definitely change the value - we ignore the return value, because
    // we don't need it.
    set { Interlocked.Exchange(ref lastValue, value); }
}

You could use volatile as suggested by newStackExchangeInstance in comments - but I'm never actually sure I fully understand exactly what it means, and I strongly suspect it doesn't mean what most people think it means, or indeed what the MSDN documentation states. You may want to read Joe Duffy's blog post on it (and this one too) for a bit more background.

A: If two different threads may access the same field/variable and at least one of them will be writing, you need to use some sort of locking. For primitive types use the Interlocked class.


text:
Q: when I try to run the code, it get the error:PicklingError: Can't pickle : attribute lookup __builtin__.function failed What is wrong with my code? Thank you
import os
import os.path
import time
global item_count
#-*- coding: cp936 -*-
import MySQLdb
import MySQLdb.cursors
import threading
import multiprocessing
from time import sleep,ctime

def qucun():

    #connect to mysql
    conn=MySQLdb.connect(host="localhost",user="root",passwd="caihong")
    cursor=conn.cursor()
    try:
        cursor.execute("""create database if not exists quad""")
    except:
        print 'Quad is exist'

    conn.select_db('quad')
    conn=MySQLdb.connect(host="localhost",user="root",passwd="caihong",db="quad")
    #get cursor
    cursor=conn.cursor()

    try:
        cursor.execute("""create table if not exists record(fn1 varchar(100),
        fn2 varchar(100),fn3 varchar(100),fn4 varchar(100),
        fn5 varchar(100),fn6 varchar(100),fn7 varchar(100),fn8 varchar(100))""")
    except:
        print 'Table record is exist'

    loops=['2013071818_1.txt','2013071818_2.txt','2013071818_3.txt','2013071818_4.txt','2013071818_5.txt']

    def loop(nloop,filename):

        print 'This loop%s start at:'%nloop,ctime()
        #connect to quad
        conn=MySQLdb.connect(host="localhost",user="root",passwd="caihong",db="quad")
        conn.select_db('quad')
        #get cursor
        cursor=conn.cursor()

        newitem=open('C:\\Python27\\caihong\\%s'%filename,'r')
        data=[line.strip() for line in newitem.readlines()]
        print data
        ##put data into value
        values=['%s'%data[0],'%s'%data[1],'%s'%data[2],'%s'%data[3],'%s'%data[4],
                '%s'%data[5],'%s'%data[6],'%s'%data[7]]

        cursor.execute("""insert into record values(%s,%s,%s,%s,%s,%s,%s,%s)""",values);

        conn.commit()
        cursor.close()
        sleep(2)
        print 'This loop done at',ctime()

    if __name__=='__main__':

        print 'starting at:',ctime()
        threads=[]
        nloops=range(len(loops))
        pool=multiprocessing.Pool(processes=2)
        for i in nloops:
            t=pool.apply_async(loop,(i,loops[i]))

        pool.close()
        pool.join()

        if t.successful():
            print 'successful'

        print 'all Done at:',ctime()
        os.system("pause")

qucun()

A: *

*You are attempting to call locally defined function in async.

*You are trying to share an open connection between processes.

First is tricky to implement in 2.7 and second is impossible in any multiprocessing
You have to use separate connection for each process in process pool.
import os
import os.path
import time
global item_count
#-*- coding: cp936 -*-
import MySQLdb
import MySQLdb.cursors
import threading
import multiprocessing
from time import sleep,ctime

CONNECTION = None

def close_connection():
    CONNECTION.close()

def get_connection():
    global CONNECTION

    #If this process pool member launched for a first time - create connection
    if CONNECTION is None:

        conn = MySQLdb.connect( host="localhost",
                                user="root",
                                passwd="caihong")
        cursor = conn.cursor()
        try:
            cursor.execute("""create database if not exists quad""")
        except:
            print 'Quad is exist'

        conn.select_db('quad')

        CONNECTION = MySQLdb.connect(host="localhost",
                                     user="root",
                                     passwd="caihong",
                                     db="quad")

        cursor = CONNECTION.cursor()

        try:
            cursor.execute("""create table if not exists record(fn1 varchar(100),
            fn2 varchar(100),fn3 varchar(100),fn4 varchar(100),
            fn5 varchar(100),fn6 varchar(100),fn7 varchar(100),fn8 varchar(100))""")
        except:
            print 'Table record is exist'

        # we dont need to close connection after each insert.
        # insted - register a finalizer once
        # so it will be called right before Pool.close()
        multiprocessing.util.Finalize(CONNECTION, close_connection, exitpriority=1)

    #use existing connection
    return CONNECTION

def loop(nloop, filename):
    conn = get_connection()
    cursor = conn.cursor()

    print 'This loop %s start at: %s'%(nloop, ctime())
    with open('C:\\Python27\\caihong\\%s'%filename, 'r') as newitem:
        data = [line.strip() for line in newitem.readlines()]

        # values=['%s'%data[0],'%s'%data[1],'%s'%data[2],'%s'%data[3],'%s'%data[4],
        #         '%s'%data[5],'%s'%data[6],'%s'%data[7]]
        # ^^^ Thats a bad way to stringify list

        cursor.execute('insert into record values(%s)', ','.join(data));

    conn.commit()

    # we dont need to close connection after each insert.
    # cursor.close()
    print 'This loop done at', ctime()

LOOPS = ['2013071818_1.txt', '2013071818_2.txt', '2013071818_3.txt', '2013071818_4.txt', '2013071818_5.txt']

if __name__=='__main__':
    pool = multiprocessing.Pool(processes=2)
    results = []
    for i, loopfile in enumerate(LOOPS):
        results.apply(pool.apply_async(loop, (i, loopfile)))

    pool.close()
    pool.join()

    if all((res.successful() for res in results)):
        print 'successful'

    print 'all Done at:', ctime()
        os.system('pause')


text:
Q: Passing an object from a controller to another I have an object called scope that allows me to connect to a server.
I want to keep that object throughout all the procedure so I need to pass it to another controller.
This is the connect to server controller :
public IActionResult Proceed(Server serverModel)
        {
            if (!ModelState.IsValid) return View("Connect");
            else
            {
                try
                {
                    // --------- This is what I need to save  ------------ \\
                    ManagementScope scope = Connecting.ConnectToServer(serverModel);
                    // --------- This is what I need to save  ------------ \\
                    return RedirectToAction("Menu", "Schema");
                }
                catch (Exception e)
                {
                    ViewBag.Message = e.Message.ToString();
                    return View("Failed");
                }
            }
        }

and in the other controller I need to pass it as a parameter :
public IActionResult ExportProceed(SchemaExport ex)
        {
            if (!ModelState.IsValid) return View("Export");
            else
            {
                try
                {
                    ExportProcess.CreateDirectories(ex, scope);
                    return RedirectToAction("Menu", "Schema");
                }
                catch (Exception e)
                {
                    ViewBag.Message = e.Message.ToString();
                    return View("Failed");
                }
            }
        }

A: You can use TempData["YourName"] = JsonConvert.SerializeObject(Connecting.ConnectToServer(serverModel));
then you do return RedirectToAction("Menu", "Schema");.
After that you just in Controller Menu take this data from TempData.
var scope = JsonConvert.DeserializeObject<ManagementScope>((string)TempData["YourName"]);

Remember TempData lives only two request

A: I usually don't advocate creating singletons, but as mentioned here they can be occasionally useful. Since you're not using DI this might be a good use case.
For example, what if you make your ConnectToServer class static?
public static class Connecting
{
    private static ManagementScope scope;

    public static void SetScope(Server sv)
    {
        //  WMI scope
        ConnectionOptions options = new ConnectionOptions
        {
            Username = sv.User,
            Password = sv.Pass
        };
        scope = new ManagementScope(@"\\" + sv.Name + @"\root\cimv2", options);
        scope.Connect();
    }

    public static ManagementScope GetScope { get { return scope; } }
}

Then in your Proceed action:
// ---------- This is the function returning the scope ---------- \\
Connecting.SetScope(serverModel);
// ---------- This is the function returning the scope ---------- \\

And in your ExportProceed action:
// ---------- This is where i need to pass the scope ---------- \\
var scope = Connecting.GetScope;
ExportProcess.CreateDirectories(ex, scope);
// ---------- This is where i need to pass the scope ---------- \\


text:
Q: 5V impulse relay I'm looking for relay similar to Finder 27.01.8.230 http://www.farnell.com/datasheets/1785142.pdf but with 5V coil voltage.
I'm confused about naming and other parameters. What is the correct name for this relay? Latching/impulse/signal? What does single coil and double coil mean? There are lots of types and parameters and I don't how to choose the right one.

A: I think this is a better/simpler solution.  The toggling behaviour you get from a flip-flop, in this case a "J-K" 74HC73 which with both inputs wired high, will toggle every time you clock it.

simulate this circuit – Schematic created using CircuitLab
R1/C1 is debounce circuit for SW1, which will cause the flipflop clock to go low for about 50ms each time you press the button.  M1 provides drive current (up to 100mA) for the coil of the relay and D1 protects M1 from overvoltage when turning off.
RLY1 has a 5V coil (they're usually about 80mA) and contacts rated for your load.  If you need a bigger relay with a coil that draws over 100mA, then use a bigger FET too like an AO3400 or similar.
R4/C3 is the reset circuit, which resets the flipflop to low (output off) on power-up.  It will be in reset for about 10ms.  D2 will quickly discharge C3 when the power is removed, forcing a clean reset.
C2 is a decoupling capacitor; you put it directly across the power terminals of the flipflop.
Edit: for completeness, I'll assume you may also need help with the 5V power supply.  Look for a 7805 and read the datasheet/appnote for that, it will give you a clean 5V to run this circuit from any source between about 7V and 20V.  The 7805 will need a heatsink if the source voltage is high and/or the relay coil draws a lot of current, but that's a whole other question and readily googleable.

A: Here's a circuit that should accomplish what you're wanting. Every time S1 (whatever is generating your pulses goes in place of S1) sends a pulse into the circuit, the relay will switch off-to-on, or on-to-off.
EDIT:
The DPDT relay, triple-latch buffer, and the attached network of resistors, capacitors & transistors (now added) will reset the entire circuit to 'off' state for your 230VAC circuit any time there is a power fault. You may want to attach a large capacitor to your 5VDC supply in order to keep the circuit from resetting during transient power losses, if you notice nuisance tripping of the reset.
/EDIT
All part numbers are given for parts that are available on http://www.digikey.com I selected them to be compatible with each other in this circuit and inexpensive (I think only 2 pieces were over $1.00USD/ea).

A: That device is a step relay, pulses of the same type  step it though the available states, an alternating relay is a similar device (but with dual-throw contacts)
A brief search didn't find any suited to DC drive at 5V
Latching relays use pulses of different types to select the different states. single coil latching relays use opposite polarity pulses, double coil latching relays use distinct coils for on and off (but will often respond suitably to pulse polarity too).
for 5V operation you could build a step relay from a latching relay and some ordinary relays, but I would look for an alternative solution


text:
Q: Not able to call a function for cronjob in wordpress I have created a cron job by creating a function for it.This function is created in functions.php in my theme folder in Wordpress. I have set logs in the function. The code for it goes as follows:-
add_action('my_daily_event','send_notification_daily');
function my_activation() {
        if ( !wp_next_scheduled('my_daily_event' ) ) {
                wp_schedule_event( current_time( 'timestamp' ), 'daily', 'my_daily_event');
        }
}
add_action('wp', 'my_activation');
function send_notification_daily(){
//send some notification daily
error_log("is this working");
}

The error_log does not show up with the set log "is it working". That means the function is not working. But why? I am not able to understand this.
I am scratching my head from last 2 days on this. But i am unable to figure out a solution for it. Please somebody help me making this function work.Thanks in advance.

A: If it is working normally without cron job and not with cron job, make sure all include paths are absolute. Relative path does not work fine with cron job


text:
Q: Negative Binomial likelihood and Beta prior I'm trying to settle what the posterior is (or more specifically, the parameters for the posterior) when we have a likelihood function that is coming from a Negative Binomial distribution and that we are assuming that the prior is beta [since it's a conjugate prior to the Negative Binomial distribution].
From this thread it is said that the posterior follows a Beta distribution with the parameters (same as Wikipedia) $$ \alpha^* = \alpha + \sum x_i, \qquad \beta^* = \beta + nk$$
From this thread it follows a Beta distribution with parameters $$ \alpha^* = \alpha + nr, \qquad \beta^* = \beta + \sum x_j - nr$$
Also, here is a third different example, with different parameters.
Do anyone have a explanation why it's differnet and how I should think?

A: Yes, the explanation is that it all depends on the parametrization of the negative binomial PMF.
For consistency, I will choose the parametrization in the second link, namely $$\Pr[X = x \mid r, p] = \binom{x - 1}{r - 1} p^r (1-p)^{x-r}, \quad x \in \{r, r+1, r+2, \ldots \}.$$ $X$ represents the random number of trials needed to observe the $r^{\rm th}$ success in a sequence of independent and identically distributed Bernoulli trials with probability of success $p$.  If $p$ is itself Beta distributed with hyperparameters $a, b$, then the kernel of the likelihood is
$$\Pr[X = x \mid r, p]f(p) \propto p^r (1-p)^{x-r} p^{a-1} (1-p)^{b-1} = p^{r+a-1} (1-p)^{x-r+b-1},$$ which is the kernel of a beta density with posterior hyperparameters $$a^* = r+a, \quad b^* = x-r+b.$$  This is for a single observation from $X$; if we have a sample $\boldsymbol x = (x_1, \ldots, x_n)$, then it is easy to see that our posterior kernel takes the form
$$\Pr[\boldsymbol X = \boldsymbol x \mid r, p]f(p) \propto p^{nr + a - 1} (1-p)^{\sum x - nr + b - 1},$$ hence the posterior is beta with hyperparameters $$a^* = nr + a, \quad b^* = n(\bar x - r) + b.$$  For convenience I have written the sample total $\sum x$ as $n \bar x$.  This result is consistent with the answer in the second link.

Now, say we compare this with the answer in the first link.  The difference is that in the first link, $X$ counts the number of successes needed to observe the $r^{\rm th}$ failure ; i.e., the parametrization is $$\Pr[X = x \mid r, p] = \binom{x+r-1}{r-1}(1-p)^r p^x, \quad x \in \{0, 1, 2, \ldots \}.$$  As before, $p$ represents the success probability for the Bernoulli trials.  Then the posterior kernel is
$$\Pr[\boldsymbol X = \boldsymbol x \mid r, p]f(p) \propto p^{\sum x} (1-p)^{nr} p^{a-1} (1-p)^{b-1} = p^{n \bar x + a - 1} (1-p)^{nr + b - 1}$$ and the posterior hyperparameters are $$a^* = n\bar x + a, \quad b^* = nr + b,$$ which is the result in the first link.
Since you did not point to a specific formula in the third link, I will not elaborate further, but as you can see from the first two links, the posterior parametrization depends on the way the observed variable is parametrized.  Whether you count trials or successes or failures, and whether you let the beta density model success or failure, all influence the parametrization.


text:
Q: Appium detects the WindowElements only 30% of the times I currently work with C# with AppWinDriver and Appium for automated tests for WPF, but in the project app that i work, it is detected correctly sometimes, others times work good and some times open the page but doesn't detect the WindowsElements of the app.
Any idea on the root cause of the issue or a solution or workaround?
Code:
AppiumOptions desiredCapabilities = new AppiumOptions();
desiredCapabilities.AddAdditionalCapability("app",app);
desiredCapabilities.AddAdditionalCapability("createSessionTimeout", "60000");
desiredCapabilities.AddAdditionalCapability("newCommandTimeout", "60000");
desiredCapabilities.AddAdditionalCapability("platformName", "Windows");
desiredCapabilities.AddAdditionalCapability("deviceName", "WindowsPC");
driver = new WindowsDriver<WindowsElement>(new Uri("http://127.0.0.1:4723"), desiredCapabilities, TimeSpan.FromMinutes(5));
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(120);


text:
Q: access view from within htmlhelper I am working with mvc 4 and have created a custom HtmlHelper.
Is it possible from within that helper, to access the view that is calling the helper? I want to use properties that I have on the base view within my helper method.

A: Yes, you can :)
public static void MyExtension(this HtmlHelper html)
{
    var view = html.ViewDataContainer;

    // accessing view properties
    var viewModel = view.Model;
    var viewAjax = view.Ajax;
    // etc
}


text:
Q: Is there a way to loop for the code to open multiple uploaded CSV files using PHP? I have this code for my HTML
  <input type="file" name="file[]" size="10000" multiple/>

And I have this working PHP code for storing the data of the CSV in the database
    $filename = $_FILES["file"]["tmp_name"];
    if ($_FILES["file"]["size"] > 0) {
    $file = fopen($filename, "r");
    $count = 0;

    while (($emapData = fgetcsv($file, 1000, ",")) !== FALSE) {

        $count++;

        $data1 = $emapData[0];
        $temp_2 = DateTime::createFromFormat('m/d/Y', $emapData[1]);
        $data2 = date_format($date1, 'Y-m-d');
        $data3 = $emapData[2];
        $data4 = $emapData[3];
        $data5 = $emapData[4];
        $data6 = $emapData[5];
        $data7 = $emapData[6];
        $data8 = $emapData[7];

How can I loop this PHP code to read multiple uploaded CSV files?

A: If you upload multiple csvs then, $filename should be an array of file names
  $filename = $_FILES["file"]["tmp_name"];

You only need to run a loop across $filename and execute the same working code.
foreach(  $filename as $key => $val){
//your working code.
}

A: if (isset($_FILES['files']) && !empty($_FILES['files'])) {
        $no_files = count($_FILES["files"]['name']);
        for ($i = 0; $i < $no_files; $i++) {
            //Your code, Whatever you want to do
            //Access your file by calling this $_FILES["files"]["tmp_name"][$i]
        }


text:
Q: Using F1_score to measure cluster validity I have clustered over 4000 textual files, and now I want to check and evaluate clusters. I want to use F-measure (a mix of recall and precision).
The formal definition of F1_score is:
$$
\text{F-measure} = 2 * \frac{\text{precision} * \text{recall}}{\text{precision} + \text{recall}}
$$
To calculate the precision and recall, I have to know in advance the correct number of documents retrieved and correct not-retrieved. That means I need to browse all documents and see what they contain. But the problem is, how can I know the precision and recall of more than 4000 textual files?

A: It seems that you have an unlabeled data set. The F1 score requires that you compare your experiment's results with actual results (i.e., count false positives and negatives). If you don't have any "correct" results against which to compare, you won't be able to calculate a F1 score.
To calculate Precision/Recall in an unsupervised approach, you need training data just for that purpose. You could manually label some data, or find a way to generate training data algorithmically, but these are difficult things to do.
You may be better off choosing a different and more applicable method by which to "check and evaluate" your clusters.


text:
Q: How can I optimize the rendering of a graph while preserving the shape? I've been writing a program to graph datapoints in Java. I need a lots of flexibility and speed so I don't want to use an existing library as much as possible. Right now, it essentially uses Graphics2D to draw lines and dots representing the points in a file of data.
My problem is, some of my datasets have upwards of 100,000 points.When it is going to be rendered with all full drag/zoom functionality, it is getting quite slow.
My question is, how can I reduce this dataset or make a simplification of it so that I can display the graph without changing the overall shape?
I could only draw every third point, for instance, but what if that skipped over and didn't display an important outlier? I could try averaging groups of points, but that could have the same problem.
And for services like Google Finance, where they probably have millions of points to display, how do they deal with this?

A: You may want to check for range differences between points before rendering them.  Give them a threshold that they need to stay within in order to not be re-rendered.


text:
Q: How to display message before redirecting to another page? I have a problem... I have registration form and when user has registred it redirect him to Home page..i want to display popup message before redirecting him that he is successfuly registred and then redirect him to Home page.
Controller:
  TempData["SuccessMessage"] = "A confirmation email will be sent to the address you've entered shortly";
  return RedirectToAction("Index", "Home");

View:
<script>
 if (@TempData["SuccessMessage"] != null)
  {
    alert('@TempData["SuccessMessage"]');
  }
</script>

A: store redirect url Like this way
ViewBag.Redirect = "Your URL ";

And do java script mention below
<script>
        if (@TempData["SuccessMessage"] != null)
        {
            alert('@TempData["SuccessMessage"]');

            window.setTimeout(function () {
                location.href = @ViewBag.Redirect;
            }, 5000);

        }

    </script>

A: Add your script in the Layout view page instance of your view page, which allows you to send messages from any Controllers to all views using the same layout.
moreover, using Tempdata not viewbag because Tempdata allows you to keep data between controllers but viewbag will be cleared after redirecting to another controller.
<script>
 if (@TempData["SuccessMessage"] != null)
  {
    alert('@TempData["SuccessMessage"]');
  }
</script>


text:
Q: Compute the Fourier series of a piecewise function. Consider the function:
$
 f(\theta) =
  \begin{cases}
   0 & \text{if } |\theta| >\delta \\
   1-|\theta|/\delta       & \text{if } |\theta| \leq \delta
  \end{cases}
$
I need to show that:
$$f(\theta)= \frac{\delta}{2\pi}+ 2\sum _{n=1}^{\infty} \frac{1-cos(n \delta)}{n^2 \pi \delta} cos(n\theta)$$
but the thing is that this integral $\int_{-\delta}^{\delta}( 1-|\theta|/\delta )e^{-in \theta}d \theta$ is a litle bit complicated for me because of the absolute value and how to make the substitution to integrate by parts, and the other thing is that $\int_{-\delta}^{\delta}( 1-|\theta|/\delta )d\theta \not= \frac{\delta}{2\pi}$
I dont know what I am doing wrong, Can you help me to complete this please?. Thanks a lot.


text:
Q: php array_map is not mapping arrays correctly I am fetching data from db.I am looping over the sql query and array_map() to get proper value.
$CompleteData = array();

foreach ( $Details as $d ) {
    $q = "SELECT "
        . "`log`.`id` AS 'id', "
        . "DATE_FORMAT( `log`.`timestamp`, '%d %b %Y %h:%i:%s %p' ) AS 'timestamp', "
        . "`log`.`Author` AS 'Author', "
        . "`log`.`message` AS 'message', "
        . "`log`.`bookname` AS 'bookname' "
        . "FROM `log` "
        . "WHERE `log`.`detailId` = '" . $d  . "'  "
        . "ORDER BY `log`.`timestamp` DESC, `log`.`id` DESC";

    $qr = mysql_query($q, $sql);
    for ($i = 0; $i < mysql_num_rows($qr); ++$i) {
        $LogId[$i] = mysql_result($qr, $i, 'id');
        $LogTimestamp[$i] = mysql_result($qr, $i, 'timestamp');
        $LogAuthor[$i] = mysql_result($qr, $i, 'Author');
        $LogMessage[$i] = mysql_result($qr, $i, 'shortmessage');
        $Logbookname[$i] = mysql_result($qr, $i, 'bookname');
    }

    $CompleteData[$d] = array_map(null, $LogId, $LogTimestamp, $LogAuthor, $LogMessage, $Logbookname);
}

Here array_map is not mapping data as desired and the output is collapsed.
Log table in DB:

Desired Output:

But with array_map(null,array1,arrar3..) the output is like below

It is combining 1st array with 2nd array and so on.
Can you pls tell am I doing wrong with array map?

A: I think you are doing it really wrong.
First I would like to inform you that mysql_ functions are deprecated and it's better starting looking for PDO, mysqli_ functions or MySQLi class and, of course, prepared statements.
What you are trying to do can be simplified as follows:
$query = "SELECT "
    . "`log`.`id` AS 'id', "
    . "DATE_FORMAT( `log`.`timestamp`, '%d %b %Y %h:%i:%s %p' ) AS 'timestamp', "
    . "`log`.`Author` AS 'Author', "
    . "`log`.`message` AS 'message', "
    . "`log`.`bookname` AS 'bookname' "
    . "FROM `log` "
    . "WHERE `log`.`detailId` IN ('" . implode("', '", $Details) . "') "
    . "ORDER BY `log`.`timestamp` DESC, `log`.`id` DESC";

$stmt = mysql_query($query);

$CompleteData = array();

while ($row = mysql_fetch_array($stmt)) {
    if (!isset($CompleteData[$row['detailedId']])) {
        $CompleteData[$row['detailedId']] = array($row);
    } else {
        $CompleteData[$row['detailedId']][] = $row;
    }
}

Why is better this way?

*

*You are executing a single query to get the info for all the logs

*The complexity of the code is smaller so the execution will be faster

*The code is more readable and easy to understand

Later edit:
If your $Details variable is an array of objects you can use array_map to get only the info you need to use in the query:
$detailsIds = array_map(function ($item) {
    return $item->detailsId;
}, $Details);

having the details ids you can use the array to create the where statement:
"WHERE `log`.`detailId` IN ('" . implode("', '", $detailsIds) . "')

A: I think an associative array will format your response with the columns without the need to use array map.
Associative array


text:
Q: IIF column comparison in Sybase How do we do following column comparison in Sybase (isql)
SELECT.....
FROM
WHERE IIF(Col1 = "4", "00", Col1)  = Mid (Col4,1,2)

I tried below, but didn't succeed
SELECT ...
FROM
WHERE
(case
      when Col1 = "4" then "00"
      else Col1
end)  = Mid (Col4,1,2)

Thanks

A: You have to use substring function instead of Mid.
SELECT ...
FROM
WHERE
(case
      when Col1 = "4" then "00"
      else Col1
end)  = substring(Col4,1,2)


text:
Q: Cassandra, how to compare field to current Date I am new using Cassandra, I have been looking for information but I do not finish solving the doubts.
First I have a .csv file from where I load the data of the last players of the football world wide cup.
My csv file has the following structure:
Group;Team;Number;Position;Name;Day;Month;Year;Club;Liga;Captain
A;Brasil;1;PORTERO;Jefferson;2;1;1983;Botafogo;Brasil;NO
A;Brasil;2;DEFENSA;Dani Alves;6;5;1983;FC Barcelona;Espana;NO
A;Brasil;3;DEFENSA;Thiago Silva (c);22;9;1984;Paris Saint-Germain;Brasil;NO

Based on the data I created the following statement to generate my new table:
CREATE TABLE players (
    group text,
    team text,
    number int,
    position text,
    name text,
    day int,
    month int,
    year int,
    club text,
    liga text,
    captain text,
    PRIMARY key (name)
);

Here I have my first question, what I have done is to create a int field for each of the data, day, month and year.
Would it be possible to encapsulate those three data in a format, for example DATE?
So for future calculations, do not have to do them one at a time.
I would like to know if those three fields in the table could be encapsulated in a date format, let's call it DATE or something similar.
Here is my second doubt; If I, for example, would like to get the older player, I had been thinking of comparing the current date with day, month, year fields of the players of the different teams that I own, here is the problem, since I can not find in the documentation how to perform this type of query and how to compare three data in my table with some function that returns to me the current date.

A: I can give you answer to your first question. You can use DATE data type starting from Cassandra 3.0.
CREATE TABLE players (
    group text,
    team text,
    number int,
    position text,
    name text,
    birth_date date,
    club text,
    liga text,
    captain text,
    PRIMARY key (name)
);

Sample CSV will look like the snippet below:
Group;Team;Number;Position;Name;Birth_Date;Year;Club;Liga;Captain
A;Brasil;1;PORTERO;Jefferson;1983-01-02;Botafogo;Brasil;NO
A;Brasil;2;DEFENSA;Dani Alves;1983-05-06;FC Barcelona;Espana;NO
A;Brasil;3;DEFENSA;Thiago Silva (c);1984-09-22;Paris Saint-Germain;Brasil;YES

You can load the CSV into table definition using the following command:
COPY players (group, team, number, position, name, birth_date, club, liga, captain)
FROM './players.csv'
WITH HEADER = 'true' AND DELIMITER = ';';


text:
Q: Is there a way to resolve FORBIDDEN FOR url? import requests
from bs4 import BeautifulSoup
url = "https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY"

headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) chrome/85.0.4183.102 Safari/537.36','Accept-Language': 'en-US,en;q=0.9,hi;q=0.8,es;q=0.7','Accept-Encoding': 'gzip, deflate, br'}

response.raise_for_status()
df = response.json()

This used to work but  now this error comes up HTTPError: 401 Client Error: Unauthorized for url: https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY.
any idea what should i do to access the web site in python ?

A: Well in that case, we should visit the main page to obtain the Cookies and then contact the API:
import requests

params = {
    'symbol': 'BANKNIFTY'
}

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:81.0) Gecko/20100101 Firefox/81.0'
}

def main(url):
    with requests.Session() as req:
        req.headers.update(headers)
        r = req.get("https://www.nseindia.com")
        r = req.get(url, params=params).json()
        print(r)

main("https://www.nseindia.com/api/option-chain-indices")


text:
Q: How to get SVG elements and Divs into an image so the user can download? I would like to know how to render SVG elements with divs into one image.
Example:

START

test

STOP

        <svg style="position:absolute;left:519.5px;top:48px" width="20" height="38" pointer-events="none" position="absolute" version="1.1" xmlns="http://www.w3.org/1999/xhtml" class="_jsPlumb_connector"><path d="M 0.5 -1 L 0.5 31 M 1.5 30 L -0.75 30 M 0.25 31 L 0.25 -1 M 1.25 0 L -1 0 M 0 0 L 0 30 " transform="translate(9.999999999999998,4)" pointer-events="visibleStroke" version="1.1" xmlns="http://www.w3.org/1999/xhtml" fill="none" stroke="rgb(7,152,216)" style="" stroke-width="2"></path><path pointer-events="all" version="1.1" xmlns="http://www.w3.org/1999/xhtml" d="M4.684274006738627e-16,32.650000000000006 L10.000000000000002,7.650000000000007 L1.4221210955098638e-15,17.075000000000006 L-9.999999999999998,7.650000000000005 L4.684274006738627e-16,32.650000000000006" class="" stroke="rgb(7,152,216)" fill="rgb(7,152,216)" transform="translate(9.999999999999998,4)"></path></svg>

        <svg style="position:absolute;left:520px;top:122px" width="20" height="38" pointer-events="none" position="absolute" version="1.1" xmlns="http://www.w3.org/1999/xhtml" class="_jsPlumb_connector"><path d="M 0 -1 L 0 31 M -1 30 L 1.25 30 M 0.25 31 L 0.25 -1 M -0.75 0 L 1.5 0 M 0.5 0 L 0.5 30 " transform="translate(9.499999999999998,4)" pointer-events="visibleStroke" version="1.1" xmlns="http://www.w3.org/1999/xhtml" fill="none" stroke="rgb(7,152,216)" style="" stroke-width="2"></path><path pointer-events="all" version="1.1" xmlns="http://www.w3.org/1999/xhtml" d="M0.5000000000000004,32.650000000000006 L10.500000000000002,7.650000000000007 L0.5000000000000014,17.075000000000006 L-9.499999999999998,7.650000000000005 L0.5000000000000004,32.650000000000006" class="" stroke="rgb(7,152,216)" fill="rgb(7,152,216)" transform="translate(9.499999999999998,4)"></path></svg>

Current JS code:
$("#btnExp").click(function(){
            canvg();
            html2canvas($(".objects"), {
                onrendered: function(canvas) {
                    theCanvas = canvas;
                    document.body.appendChild(canvas);

                    // Convert and download as image
                    Canvas2Image.saveAsPNG(canvas);
                    $("body").append(canvas);

                   }
               });

        });

With the code above, every element gets rendered, but the picture is not right. How elements get rendered , how they should render.

A: The most promising method is rendering a part of the DOM to a canvas. This canvas can be displayed as image and downloaded by the users. Or you could save the canvas as blob, but not all browsers support that, so additional libraries could be used.
More information :
https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Drawing_DOM_objects_into_a_canvas
https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob

A: What you can do is you can save parent div to a canvas and then to image and download it by using js

START

test

STOP

    <svg style="position:absolute;left:519.5px;top:48px" width="20" height="38" pointer-events="none" position="absolute" version="1.1" xmlns="http://www.w3.org/1999/xhtml" class="_jsPlumb_connector"><path d="M 0.5 -1 L 0.5 31 M 1.5 30 L -0.75 30 M 0.25 31 L 0.25 -1 M 1.25 0 L -1 0 M 0 0 L 0 30 " transform="translate(9.999999999999998,4)" pointer-events="visibleStroke" version="1.1" xmlns="http://www.w3.org/1999/xhtml" fill="none" stroke="rgb(7,152,216)" style="" stroke-width="2"></path><path pointer-events="all" version="1.1" xmlns="http://www.w3.org/1999/xhtml" d="M4.684274006738627e-16,32.650000000000006 L10.000000000000002,7.650000000000007 L1.4221210955098638e-15,17.075000000000006 L-9.999999999999998,7.650000000000005 L4.684274006738627e-16,32.650000000000006" class="" stroke="rgb(7,152,216)" fill="rgb(7,152,216)" transform="translate(9.999999999999998,4)"></path></svg>

    <svg style="position:absolute;left:520px;top:122px" width="20" height="38" pointer-events="none" position="absolute" version="1.1" xmlns="http://www.w3.org/1999/xhtml" class="_jsPlumb_connector"><path d="M 0 -1 L 0 31 M -1 30 L 1.25 30 M 0.25 31 L 0.25 -1 M -0.75 0 L 1.5 0 M 0.5 0 L 0.5 30 " transform="translate(9.499999999999998,4)" pointer-events="visibleStroke" version="1.1" xmlns="http://www.w3.org/1999/xhtml" fill="none" stroke="rgb(7,152,216)" style="" stroke-width="2"></path><path pointer-events="all" version="1.1" xmlns="http://www.w3.org/1999/xhtml" d="M0.5000000000000004,32.650000000000006 L10.500000000000002,7.650000000000007 L0.5000000000000014,17.075000000000006 L-9.499999999999998,7.650000000000005 L0.5000000000000004,32.650000000000006" class="" stroke="rgb(7,152,216)" fill="rgb(7,152,216)" transform="translate(9.499999999999998,4)"></path></svg>

<input type="button" id="btnSave" value="Save PNG"/>

js:
$(function() {
$("#btnSave").click(function() {
    html2canvas($("#widget"), {
        onrendered: function(canvas) {
            theCanvas = canvas;
            document.body.appendChild(canvas);

            // Convert and download as image
            Canvas2Image.saveAsPNG(canvas);
            $("#img-out").append(canvas);

          }
       });
    });
 });

it has dependency over jquery,html2canvas.js,base64.js,canvas2image.js
I think this will work for you.


text:
Q: Problem with the datepicker plugin in QueryBuilder I'm using QueryBuilder and I have a search that is of type date. The problem is that I'm getting an error because of the Plugin Datapicker, but I do not know what the reason for the error, can anyone help me?
My code:
        {
        id: 'pac_dt_validate',
        label: 'Data Validade',
        type: 'date',
        operators: ['equal', 'less', 'less_or_equal', 'greater', 'greater_or_equal', 'between'],
        validation: {
          format: 'dd/mm/yy'
        },
        plugin: 'datepicker',
        plugin_config: {
          dateFormat: 'dd/mm/yy',
          dayNames: ['Domingo','Segunda','Terça','Quarta','Quinta','Sexta','Sábado'],
          dayNamesMin: ['D','S','T','Q','Q','S','S','D'],
          dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb','Dom'],
          monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
          monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'],
          nextText: 'Próximo',
          prevText: 'Anterior',
          todayBtn: 'linked',
          todayHighlight: true,
          autoclose: true
        }

    <script src="{{ asset('vendor/adminlte/vendor/jquery-builder/js/query-builder.standalone.min.js') }}"></script>
    <script src="{{ asset('vendor/adminlte/vendor/jquery-builder/query-builder.pt-BR.js') }}"></script>
    <script src="{{ asset('vendor/adminlte/vendor/momentJs/moment-with-locales.min.js') }}"></script>

The Bootstrap Js has already been imported, so that's not the problem, the error that appears is this:
Uncaught TypeError: n[i.plugin] is not a function
at c.createRuleInput (query-builder.standalone.min.js:7)
at c.updateRuleFilter (query-builder.standalone.min.js:7)
at n.update (query-builder.standalone.min.js:7)
at n.dispatch (jquery.js:2)
at n.y.handle (jquery.js:2)

Can someone help me? Thank you in advance.

A: You need to import the bootstrap-datepicker.js. Remember that this import needs to be after the import of bootstrap.js.
After that, you will need to import the bootstrap-datepicker.css to style the plugin


text:
Q: Почему фонят колонки? Я записал звук + сделал скрины эквалайзера. Есть скрин с шумодавом, но по пикам можно понять где косяк.
Запись тоже сделал само собой, только что-то не вижу, как её подгрузить сюда) Не нашёл в редакторе.


text:
Q: iOS 10 - Swift still Notification CloudKit: App is not launched, read Notification after didFinishLaunchingWithOptions I have a problem with reading the notification when the app is not in background mode anymore. So it is completely off.
The notification setup works fine.
Even if the app is no longer in the background, the notification is read. In the log files you can see the arrival.
For testing purposes I have turned on the notification pointer. It counts up.
What works:
When the app is in the background:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {}

Correctly executed and I can access the data via the CKRecordID.
But if the app is no longer in the background, i.e. completely off, the fetchCompletionHandler is not executed anymore.
I have checked this via NSLog.
Now I need a way to read the notification again when the app is started. So I need the CKRecordIDs.
It is only about data that is transferred. I don't need a display on the screen.
It is also possible to change the settings so that only the data is received when the app is started again. I don't really need them in the background.
It is about a game to transfer data from one device to another.
Who has a code snippet for me?
Or a hint where I can search?

A: As far as I know, there is not a way to get missed notifications when the device is offline or the app is not running.
You are going to need to create a CKQuery to check CloudKit for what the device missed the last time it launched. Your CKQuery will have to compare against a timestamp saved locally to the device with UserDefaults to know what to fetch from CloudKit.
See my answer here to a similar question for a longer description of what I mean.


text:
Q: What are some good Iron Man comics for a beginner? I'm a 15 year old girl who would like to get into comics such as Iron Man (I'm a brand new reader of comics). I already saw Iron Man 1 but I want to understand his story in the comics because they have more depth. So what is a good Iron Man comic for a newer reader like me? *(please give Title, Volume and number).
(P.S. I most likely won't catch up on 40+ years of Iron Man comics)

A: Having done this myself a couple of years ago, here's my recommendation.  Note that the films are a different continuity (or version) of Iron Man, so you won't see comics that tell an identical version of events as what the films show.  In the comics, there are multiple universes with different versions of the Marvel universe as well, the two big ones are:

*

*The main line continuity which includes what I'm recommending below (AKA Earth-616)

*The Ultimate universe, which I don't include here.  This was an initiative that Marvel started to have a new universe that didn't have the half-century of backstory that the main line continuity has.  This would then be more welcoming to new readers.

The films borrow elements from both of these universes, while also making up their own stuff as well.  So there are 2 separate comics universes, both with their own versions of Iron Man, and with their own stories.  On top of this, you have the films which blend them while also inventing new elements.

I got interested in Iron Man due to the films, and I got some recommendations of where to start from off comic book forums:

*

*Iron Man: Extremis (a motion comic version is also available on Netflix Streaming) - This is a sort of modern reboot for Iron Man.  It's a self-contained tale that provides a good introduction to the modern Tony Stark et al.  It also provides a good understanding of who and what Tony Stark is for later books, as he is no longer just a guy who builds suits of armor.

*Invincible Iron Man (by Fraction/Larroca) - A modern ongoing Iron Man comic.  The story develops a little slowly, but since you're reading collected editions instead of buying it once a month, it doesn't detract from the books.  These have excellent art and writing, it's the only comic I was regularly reading last year.  This series starts with the omnibus I linked, they released the second omnibus volume last year, but after that you'll have to switch over to normal collected editions.  The omnibuses provide a ton of issues for a low per issue price.  These issues are occasionally tied in to the Marvel crossovers.  The early "World's Most Wanted" storyline, for example, springs out of the ending of Secret Invasion which had

 Norman Osborn running a replacement for SHIELD.  Tony previously ran SHIELD.

It's helpful to have some rough knowledge of these crossovers, but isn't required.  Invincible Iron Man's run recently ended.  Personally I'm looking for an Iron Man book to replace it, but you should be set for a while, there are a few dozen issues there that I've recommended.

A: I think if you want the comics that most closely match the movie series (though there are of course significant differences), what you want is Iron Man vol. 4
Some of these have been published as collected editions, including Extremis (issues 1-6), which I think covers the new origin story.

A: Marvel has a section on their site for new readers, it looks like they suggest starting with Invincible Iron Man. New Readers
If you don't mind digital comics you may want to look into a Marvel Digital Comics Unlimited subscription. It's probably the most cost effective way to catch up on the past stuff, if you look around the internet you can find deals for new subscribers

A: @ Keen while I love Matt Fraction and the Extremis is a good story idea I wouldn't recommend them to a 15 year old who's just getting into comics.  In my humble opinion the stories you mentioned just don't have the right balance of character arcs and weight.  Plus they tend to be stories that long-time readers would get more from then first-time readers.
Recently something has come out (which I noticed at my public library) that I think would better fit a young new reader: The Iron Man Omnibus by Kurt Busiek & Sean Chen.
This is THE "Jump On" book to get for anyone who wants to find out who Iron Man is as well as read excellent stories which involve The Golden Avenger in deep and interesting ways.  It's not only jam-packed with arcs (see below) it also represents the fresh start Marvel gave their core heroes after the re-imagining of Heroes Reborn. So, essentially Tony has to come back from supposed death to rebuild his life and fortunes as well as get back to wearing the Red and Gold again.
This new beginning jumps right in with Shellhead facing-off against a collection of familiar opponents that will give the reader an understanding of the Armored Avenger's history and complications. Opponents include, but aren't limited to, the well-known and the obscure alike, with Whiplash, M.O.D.O.K., Fin Fang Foom, Count Nefaria and Ultimo  rounding out the line-up. There's also a brand-new villainous 'War Machine' Tony must uncover the mystery of and you-guessed-it Busiek couldn't resist working in The Mandarin.
We also have Happy Hogan and Pepper Potts supporting the cast while Stark somehow finds time to romance Rumiko Fujikawa.  What's great about Kurt Busiek's work is that he always seems to keep the integrity of characters while giving us new spins on older characterizations and relationships.  Something many of the newer stories tend to miss, Extremis for example, is Tony Stark's personality.  Extremis not a bad story, far from it, but it doesn't have the intimacy with the characters that the award-winning Busiek can provide a reader.

Kurt Busiek explained in a interview, "Iron Man was the Marvel book I always wanted
  to write, but it wasn't because I was a huge fan of the series. There
  are runs I like enormously, notably Archie Goodwin's run on the
  character, but what made me want to write Iron Man was that I saw so
  much potential in the character, potential that I thought was only
  partly-realized in the various runs of the past."

That is why I would say this collection, more then any other, would be a great place for a new young reader to start.  If it can't be found at the local library near you or at a shop for a good price you can check online.
This book collects a whooping amount of stories including cross-overs with other titles as well as the core IRON MAN Vol 3 series (#1-25).  Some highlights: CAPTAIN AMERICA #8, AVENGERS #7, IRON MAN & CAPTAIN AMERICA ANNUAL, FANTASTIC FOUR #15, THOR #17, PETER PARKER: SPIDER-MAN #11 and IRON MAN: THE IRON AGE (Year One Style) mini-series.


text:
Q: Why runAllManagedModulesForAllRequests on true when using Systme.Web.Routing.Route Based on an article of Scott Hanselman we always had the option runAllManagedModulesForAllRequests on false in our Webforms project.
Also we have a few routes.MapPageRoute configurations running succesfully.
Now we need to add ICS (internet calendar) support to our webform project. To create a clean, readable url for the users, which could be handled by a IHttpHandler, I've added the following:
routes.Add(new Route("ical/{username}/{somecheck}", new ICalHandler()));

Now, the url is the way we want it, like this:
http://foo.com/ical/username/abc.ics

On localhost (VS2012, Windows 8) the runAllManagedModulesForAllRequests can be on false.
On the testserver (Win2k8 R2, IIS7.5) I get a "Page Not Found" error. But, when I enable runAllManagedModulesForAllRequests, it works.
If it has to be this way, so be it. But I would realy like to know why... Can anyone explain why I need to enable this setting?
Many thanks in advance.

A: from MSDN
an update that was made to IIS 7 makes the runAllManagedModulesForAllRequests setting unnecessary and supports ASP.NET routing natively. (For information about the update, see the Microsoft Support article An update is available that enables certain IIS 7.0 or IIS 7.5 handlers to handle requests whose URLs do not end with a period.)
If your website is running on IIS 7 and if IIS has been updated, you do not need to set runAllManagedModulesForAllRequests to true. In fact, setting it to true is not recommended, because it adds unnecessary processing overhead to request. When this setting is true, all requests, including those for .htm, .jpg, and other static files, also go through the ASP.NET request pipeline.
The default setting for runAllManagedModulesForAllRequests is false. If the site's configuration file does not explicitly set runAllManagedModulesForAllRequests to true, when you then run the website on Windows 7 without SP1 installed, IIS 7 will not include the required update. As a consequence, routing will not work and you will see errors. If you have a problem where routing does not work, you can do the following:
Update Windows 7 to SP1, which will add the update to IIS 7.
Install the update that's described in the Microsoft Support article listed previously.
Set runAllManagedModulesForAllRequests to true in that website's Web.config file. Note that this will add some overhead to requests.


text:
Q: postgres container creating database but not creating tables and adding data I'm trying to setup a postgres container with ansible, but the database isn't created completely. Via docker logs, it shows that the script has been executed entirely, but the result in always an empty database.
Playbook script:
- name: Run PostgreSQL container
  become: no
  docker_container:
    env:
      POSTGRES_PASSWORD: "{{ postgres_pw }}"
    name: postgres
    image: postgres:11
    ports: "5432:5432"
    restart_policy: unless-stopped
    volumes:
      - /tmp/{{ db_backup_file }}:/docker-entrypoint-initdb.d/{{ db_backup_file }}:ro
      - pgdata:/var/lib/postgresql/data

sql file:
CREATE DATABASE database5;

--
-- TOC entry 647 (class 1247 OID 16548)
-- Name: geslacht; Type: TYPE; Schema: public; Owner: postgres
--

CREATE TYPE public.geslacht AS ENUM (
    'm',
    'v',
    'x'
);

ALTER TYPE public.geslacht OWNER TO postgres;

SET default_tablespace = '';

--
-- TOC entry 197 (class 1259 OID 16555)
-- Name: antwoorden; Type: TABLE; Schema: public; Owner: postgres
--

CREATE TABLE public.antwoorden (
    id integer NOT NULL,
    bericht text NOT NULL,
    gebruiker integer NOT NULL,
    vraag integer NOT NULL,
    gepost_op timestamp without time zone DEFAULT now() NOT NULL,
    actief boolean DEFAULT true NOT NULL,
    is_verkozen boolean DEFAULT false NOT NULL
);

Note: this is only a part of a script that creates all tables and adds sample data.
What's the reason why database5 is not being filled with the tables and data?


text:
Q: Change value column a if column b contains conditional string This issue is giving me a lot of trouble, even though it should be fixed eaily. I have a dataset with the columns id and poster. I want to change the poster's value if the id value contains a certain string. See data below:
test_df
id                   poster
143537222999_2054    Kevin
143115551234_2049    Dave
14334_5334           Eric
1456322_4334         Mandy
143115551234_445633  Patrick
143115551234_4321    Lars
143537222999_56743   Iris

I would like to get
test_df
id                   poster
143537222999_2054    User
143115551234_2049    User
14334_5334           Eric
1456322_4334         Mandy
143115551234_445633  User
143115551234_4321    User
143537222999_56743   User

Both the columns are characters. I would like to change the poster's value to "User" if id value contains "143537222999", OR "143115551234". I have tried the following codes:
Match within/which
test_df <- within(test_df, poster[match('143115551234', test_df$id) | match('143537222999', test_df$id)] <- 'User')

This code gave me no errors, but it didn't change any of the values in the poster column. When I replace within for which, I get the error:
test_df <- which(test_df, poster[match('143115551234', test_df$id) | match('143537222999', test_df$id)] <- 'User')
Error in which(test_df, poster[match("143115551234", test_df$id) |  :
  argument to 'which' is not logical

Match different variant
test_df <- test_df[match(id, test_df, "143115551234") | match(id, test_df, "143537222999"), test_df$poster] <- 'User'

This code gives me the error:
Error in `[<-.data.frame`(`*tmp*`, match(id, test_df, "143115551234") |  :
  missing values are not allowed in subscripted assignments of data frames
In addition: Warning messages:
1: In match(id, test_df, "143115551234") :
  NAs introduced by coercion to integer range
2: In match(id, test_df, "143537222999") :
  NAs introduced by coercion to integer range

After looking up this error I found out that the integers in R are 32-bits and the maximum value of an integer is 2147483647. I'm not sure why i'm getting this error because R states that my column is a character.
> lapply(test_df, class)

$poster
[1] "character"

$id
[1] "character"

Grepl
test_df[grepl("143115551234", id | "143537222999", id), poster := "User"]

This code raises the error:
Error in `:=`(poster, "User") : could not find function ":="

I'm not sure what the best way is to fix this error, I have tried multiple variaties and keep getting across different errors.
I have tried multiple answers from multiple questions that were asked before on here, but I still can't get to fix some errors.

A: Use grepl with ifelse:
df$poster <- ifelse(grepl("143537222999|143115551234", df$id), "User", df$poster)

Demo

A: You may try this using grepl.
df[grepl('143115551234|143537222999', df$id),"poster"] <- "User"

So, all the true for above matched in poster column getting replaced by "User"
> df[grepl('143115551234|143537222999', df$id),"poster"] <- "User"
> df
                   id poster
1   143537222999_2054   User
2   143115551234_2049   User
3          14334_5334   Eric
4        1456322_4334  Mandy
5 143115551234_445633   User
6   143115551234_4321   User
7  143537222999_56743   User


text:
Q: Problems with Xamarin Asynchronous Methods In the event of a button from my APP I had the following code it worked running on android emulator, but when I passed the app to the phone generates a message the app stopped.
    Button buttonPessoasNecessita = FindViewById<Button> (Resource.Id.mybuttonPesNec);
    buttonPessoasNecessita.Click += delegate {
    Service1Client client;
    var binding = new BasicHttpBinding () { Name= "basicHttpBinding", MaxReceivedMessageSize = 67108864,};

    binding.ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas()
    { MaxArrayLength = 2147483646, MaxStringContentLength = 5242880, };

    var timeout = new TimeSpan(0,60,60);
    binding.SendTimeout= timeout;
    binding.OpenTimeout = timeout;
    binding.ReceiveTimeout = timeout;

    client = new Service1Client(binding, new EndpointAddress ("http://engb.uni5.net/Service1.svc"));

    buttonPessoasNecessita.text = client.envioPessoa();

    };

Trying to solve the case thought to use asynchronously, I tried various examples but none became clear to me and I saw that my object 'client' is there a method has a beginenvioPessoa () method and other endenvioPessoa (); Based on this link Easy way to use WCF service with async / await tried to set up a method to consume the web service async way
call the method:
 var t = await executeAsync(binding);

Method:
public async Task<string> executeAsync(BasicHttpBinding binding){

    Service1Client client = new Service1Client(binding, new EndpointAddress ("http://engb.uni5.net/Service1.svc"));

    var t = Task<string>.Factory.FromAsync (
        ((IService1)client.InnerChannel).BeginenvioPessoa,
        ((IService1)client.InnerChannel).EndenvioPessoa);
    return await t;
}

Error CS1502: The best overloaded method match for
  'System.Threading.Tasks.TaskFactory.FromAsync(System.IAsyncResult,
  System.Func)' has some invalid arguments
  (CS1502)
Error CS1503: Argument 1: cannot convert from 'method group' to
  'System.IAsyncResult' (CS1503)

A: Signature is:
Task<string>.Factory.FromAsync(IAsyncResult asyncResult, Func<IASyncResult, string> endMethod)

so try this instead
var t = Task<string>.Factory.FromAsync(
  ((IService1)client.InnerChannel).BeginenvioPessoa, result =>
    ((IService1)client.InnerChannel).EndenvioPessoa);


text:
Q: Set custom appdata environment variable for a Steam app I have user name with non-latin characters and this really messes up some of my Steam apps.
I need a way to launch these apps with a custom APPDATA.
I tried to use bat file to launch Steam:
set APPDATA=C:\Users\LatinName\AppData\Roaming
start "" "path\to\steam.exe"

And tried to do the same in powershell:
$env:APPDATA='C:\Users\LatinName\AppData\Roaming'
& 'path\to\steam.exe'

Also tried to create a bat file and to set it as a custom launch command in Steam (so Steam would launch this file and it will launch a game):
set APPDATA=C:\Users\LatinName\AppData\Roaming
start "" "path/to/game.exe"

But it didn't work, app still uses default appdata path. I thought that child processes should inherit variables.
I tried an answer from this thread but Steam just says that it can't find APPDATA=C:\Users\Avorion\AppData\Roaming.
The other 2 ways are renaming my current profile or creating a new one.

*

*Renaming profile on Windows 10 is a long and not safe process.

*Creating a new profile requires me to set every setting again and for some reason makes my PC much slower, so it's not an option.