text:
Q: Absolute convergence of Fourier series of periodic adelic function I've asked several questions about this topic before, including here and here.  I've gotten many helpful responses, but I still do not completely understand what is going on.
Let $f: \mathbb A_{\mathbb Q}/\mathbb Q \rightarrow \mathbb C$ be a smooth function.  Here smooth means that as a function of $\mathbb A_{\mathbb Q} = \mathbb R \times \mathbb A_f$, $f$ is smooth in the first argument and "uniformly locally constant" in the second argument.  This last condition means that for every point $(x_0,y_0) \in \mathbb R \times \mathbb A_f = \mathbb A_{\mathbb Q}$, there exist neighborhoods $U$ and $V$ of $x_0$ and $y_0$ such that $f(x,y) = f(x,y_0)$ for all $x \in U$ and $y \in V$.
Let $\Psi$ be a fixed nontrivial character of $\mathbb A_{\mathbb Q}/\mathbb Q$.
Being continuous and therefore square integrable, $f$ has a Fourier expansion
$$f(x) = \sum\limits_{\alpha \in \mathbb Q}c_{\alpha} \Psi(\alpha x) \tag{1} $$
for uniquely determined complex numbers $c_{\alpha}$.  The sum (1) on the right converges to $f$ in the $L^2$-norm on $\mathbb A_{\mathbb Q}/\mathbb Q$.  We can recover the coefficients $c_{\alpha}$ by the usual orthogonality relations:
$$c_{\alpha} = \int\limits_{\mathbb A_{\mathbb Q}/\mathbb Q}f(x)\Psi(-\alpha x)dx$$

What I want to understand:

*

*1 . Under the assumption that $f$ is smooth, show that the right hand side of (1) converges absolutely (and therefore (1) is actually a pointwise, even a uniform, limit).

*2 . Identify $f$ as a smooth function $\phi$ on some torus $T$, as explained in the links above (which I still don't totally understand).

*3 . Relate the adelic Fourier coefficients of $f$ to the classical Fourier coefficients of $\phi$.

For #1, I know that from the compactness of $\mathbb A/\mathbb Q$, it follows that there is an open compact subgroup $H$ of $\mathbb A_f$ such that $f(x+h) = f(x)$ for all $x \in \mathbb A = \mathbb A_{\mathbb Q}$ and $h \in H$.  It follows that $f$ is well defined on the quotient $\mathbb A/(i(\mathbb Q) + H)$, where $i$ is the diagonal embedding of $\mathbb Q$.
Special case I have worked out: I have worked out the special case $H = \prod\limits_p \mathbb Z_p$.  We may assume $\Psi$ is the canonical additive character $(\Psi_{\infty}(x) = e^{2\pi i x}$, and $\Psi_p(x) = e^{2 \pi i [x]}$, where $[x]$ is the reduction of $x$ in $\mathbb Q_p/\mathbb Z_p = \mathbb Q/\mathbb Z$).  The inclusion $\mathbb R \rightarrow \mathbb A$ induces an isomorphism of topological groups
$$\mathbb R/\mathbb Z \rightarrow \mathbb A/(i(\mathbb Q)+H)$$
Injectivity comes from the fact that $\mathbb Z = \mathbb Q \cap H$.  Surjectivity comes from the equation $\mathbb A = \mathbb R + H + i(\mathbb Q)$.  Now we can identify $f$ as a function on $\mathbb R/\mathbb Z$, which by smoothness has an absolutely convergent Fourier expansion
$$f(x_{\infty}) = \sum\limits_{n \in \mathbb Z} d_n \Psi_{\infty}(nx_{\infty})$$
$$d_n = \int\limits_{\mathbb R/\mathbb Z} f(x_{\infty})e^{-2\pi i n x_{\infty}}dx_{\infty}$$
Now for $\alpha \in \mathbb Q$, we have
$$c_{\alpha} = \int\limits_{\mathbb A/\mathbb Q} f(x)\Psi(-\alpha x)dx = \int\limits_{(\mathbb A/\mathbb Q)/((i(\mathbb Q)+H)/\mathbb Q)} \space \space \int\limits_{(i(\mathbb Q)+H)/\mathbb Q} f(x+b)\Psi(-\alpha(x+b))\space  db \space dx$$
Using the third isomorphism theorem, the isomorphism $(i(\mathbb Q)+H)/\mathbb Q = H$, and the fact that $f$ is invariant under $i(\mathbb Q)+H$, this is equal to
$$\int\limits_{\mathbb A/(i(\mathbb Q)+H)} f(x)\Psi(-\alpha x) \int\limits_{H}\Psi(-\alpha b) \space db \space dx = \Bigg( \int\limits_{\mathbb R/\mathbb Z} f(x_{\infty}) \Psi_{\infty}(-\alpha x_{\infty}) \space dx_{\infty} \Bigg) \Bigg( \int\limits_H \Psi(-\alpha b) db \Bigg)$$
$$ = \Bigg( \int\limits_{\mathbb R/\mathbb Z} f(x_{\infty}) e^{-2\pi i \alpha x_{\infty}} \space dx_{\infty} \Bigg)\Bigg( \int\limits_H \Psi(-\alpha b) db \Bigg)$$
Now $b_p \mapsto \Psi(-\alpha b_p)$ is the trivial character on $\mathbb Z_p$ if and only if $\alpha \in \mathbb Z_p$.  It follows that
$$ \int\limits_H \Psi(-\alpha b) db  = \prod\limits_p \int\limits_{\mathbb Z_p} \Psi_p(-\alpha b_p)db_p = \begin{cases} 1 & \textrm{ if  $\alpha \in \mathbb Z$} \\ 0 & \textrm{if $\alpha \not\in \mathbb Z$} \end{cases}$$
Therefore, the adelic Fourier coefficients $c_{\alpha}$ are related to the classical Fourier coefficients $d_n$ by
$$c_{\alpha} = \begin{cases} d_{\alpha} & \textrm{ if $\alpha \in \mathbb Z$} \\ 0 & \textrm{ if $\alpha \not\in \mathbb Z$} \end{cases}$$
This gets us #1 and #3 in this special case.

A: I have worked out the case of a general $H$, which turns out to not be so different from what I did above.  It turns out exactly as user reuns suggested in his comments on my mathoverflow question about the same topic.
So there is an open compact subgroup $H$ of $\mathbb A_f$ such that $f(x+h) = f(x)$ for all $x \in \mathbb A$ and $h \in H$.  We may shrink $H$ and assume it is of the form
$$p_1^{e_1}\mathbb Z_{p_1} \times \cdots \times p_s^{e_s}\mathbb Z_{p_s} \times \prod\limits_{p \neq p_i} \mathbb Z_p$$
If we let $H_0 = \prod\limits_p \mathbb Z_p$, with $m = p_1^{e_1} \cdots p_s^{e_s}$, then $[H_0 : H] = m$, and $(n_1, ... , n_s, 0, ...)$ with $0 \leq n_j < p_j^{e_j}$ is a complete set of representatives for $H$ in $H_0$.  We see that
$$(x_{\infty},n_1, ... , n_s) \mapsto (x_{\infty}, n_1, ... , n_s, 0, ... )$$
induces an isomorphism of topological groups
$$\mathbb R/m\mathbb Z \times \mathbb Z/p_1^{e_1}\mathbb Z \times \cdots \mathbb Z/p_s^{e_s}\mathbb Z \longrightarrow \mathbb A/(\mathbb Q+H)$$
Injectivity is straightforward, and surjectivity follows by the same reasoning that $\mathbb R/\mathbb Z \cong \mathbb A/(\mathbb Q + H_0)$: the key fact is that $\mathbb A = \mathbb R + \mathbb Q + H_0$.
Our assumption on $f$ is that each map $x_{\infty} \mapsto f(x_{\infty}, n_1, ... , n_s)$
is smooth and $m\mathbb Z$-periodic, and therefore for each $\underline{n} = (n_1, ... , n_s)$, we have an absolutely convergent Fourier expansion
$$f(x_{\infty}, n_1, ... , n_s) = \sum\limits_{k \in m\mathbb Z} d_{\underline{n},k}e^{2\pi i kx_{\infty}/m}$$
$$d_{\underline{n},k} = \int\limits_{\mathbb R/m\mathbb Z} f(x_{\infty}, n_1, ... , n_s)e^{-2\pi i kx_{\infty}/m}$$
Now we can relate these classical Fourier coefficients to the adelic Fourier coefficients.  We choose the character $\Psi$ so that...  By the same reasoning as in the special case in the statement of my question (skipping a few details), we have
$$c_{\alpha} = \int\limits_{\mathbb A/\mathbb Q} f(x) \Psi(-\alpha x)dx = \int\limits_{\mathbb A/(\mathbb Q+H)} f(x)\Psi(-\alpha x) \int\limits_H \Psi(-\alpha h) \space dh \space dx$$
Now
$$\int\limits_H \Psi(-\alpha h) \space dh = \prod\limits_{i=1}^s \int\limits_{p_i^{e_i}\mathbb Z_{p_i}} \Psi_{p_i}(\alpha h_{p_i}) dh_{p_i} \prod\limits_{p \neq p_i} \int\limits_{\mathbb Z_p} \Psi_p(\alpha h_p) dh_p = \begin{cases} 1 & \textrm{ if $\alpha \in m \mathbb Z$} \\ 0 & \textrm{ if $\alpha \not\in m\mathbb Z$} \end{cases}$$
So the Fourier coefficient $c_{\alpha}$ is zero unless $\alpha \in m\mathbb Z$.  If this is the case, then
$$c_{\alpha} = \int\limits_{\mathbb A/(\mathbb Q+ H)} f(x)\Psi(-\alpha x)dx = \sum\limits_{\underline{n}} \int\limits_{\mathbb R/m\mathbb Z} f(x_{\infty},n_1, ... , n_s) e^{-2\pi i \alpha x_{\infty}/m} dx_{\infty}$$
where the sum is over all $\underline{n} = (n_1, ... , n_s)$ with $0 \leq n_i < p_i^{e_i}$.  We have shown that
$$c_{\alpha} = \begin{cases} \sum\limits_{\underline{n}} d_{\underline{n},\alpha} & \alpha \in m \mathbb Z \\ 0 & \alpha \not\in m\mathbb Z \end{cases}$$
and since each sum $\sum\limits_{k \in m\mathbb Z} d_{\underline{n},k}$ is absolutely convergent, so are the $c_{\alpha}$.


text:
Q: Is it okay to ignore concurvity on our GAM model? I'm trying to model a relationship between marine debris concentration (item/m^2) with several covariates using GAM with MGCV R package. I found that the concurvity values at worst-case scenario are very high when i checked it. I read on GAM website tutorial that suggests that if a high concurvity value appears, check the partial smooth plot to see if variables with high values have problematic shapes or confidence intervals, and to be careful in making interpretations. is it means that i could trust the model and keep making interpretation a.k.a ignore the concurvity?. Since i think i don't see any problematic shapes of curve and confidence intervals in paratial plot (?). And also, i don't remove the covariate with high concurvity because i think i need them in my model, and they have significance p-value but i'm not really sure about this because of the concurvity values. Big appreciate for an advice and suggestions. Here i attached the code and the plot. Thanks in advance
m1 <- gam(Concentration ~s(Gradient, k =4) + Shore_exposure + Substrate_type +
            Backshore_type + s(DistBN_River, k=5) + s(DistBL_River, k = 4) +
            Dist_Tourism + s(Dist_Settlement, k=4) + s(Population,k=3),
          family='tw', data=debris.data, method="REML")

concurvity(m1, full = TRUE)

          para   s(Gradient) s(DistBN_River) s(DistBL_River) s(Dist_Settlement) s(Population)
worst  0.9915294   0.9732331      0.9788846       0.9920508         0.9951241         0.9969839

summary(m1)

Family: Tweedie(p=1.99)
Link function: log

Formula:
Concentration ~ s(Gradient, k = 4) + Shore_exposure + Substrate_type +
    Backshore_type + s(DistBN_River, k = 5) + s(DistBL_River,
    k = 4) + Dist_Tourism + s(Dist_Settlement, k = 4) + s(Population,
    k = 3)

Parametric coefficients:
                              Estimate Std. Error t value Pr(>|t|)
(Intercept)                  4.8870188  0.6809171   7.177 6.35e-09 ***
Shore_exposureHEADLAND      -0.5363288  0.3923668  -1.367 0.178610
Shore_exposureSTRAIGHT      -0.1624164  0.2160818  -0.752 0.456274
Substrate_typeROCK SLAB     -0.9361547  0.4760029  -1.967 0.055555 .
Substrate_typeSAND          -1.2949689  0.3355633  -3.859 0.000369 ***
Backshore_typeFOREST/TREE   -1.2002933  0.5409765  -2.219 0.031717 *
Backshore_typeGRASS-PASTURE -1.4185890  0.7063872  -2.008 0.050792 .
Backshore_typeGRASS-TUSSOCK -1.1531053  0.6468418  -1.783 0.081552 .
Backshore_typeMANGROVE      -0.3041392  0.7563493  -0.402 0.689549
Backshore_typeSEAWALL       -1.3858871  0.7793002  -1.778 0.082264 .
Backshore_typeSHRUB         -0.6497938  0.6057003  -1.073 0.289220
Dist_Tourism                -0.0005501  0.0000742  -7.413 2.87e-09 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Approximate significance of smooth terms:
                     edf Ref.df      F  p-value
s(Gradient)        2.722  2.933 12.277 2.79e-06 ***
s(DistBN_River)    3.650  3.905  3.017  0.01665 *
s(DistBL_River)    2.865  2.975 12.722 4.58e-06 ***
s(Dist_Settlement) 2.835  2.959 13.734 1.73e-06 ***
s(Population)      1.000  1.000  9.308  0.00381 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

R-sq.(adj) =  0.649   Deviance explained = 86.8%
-REML = 133.24  Scale est. = 0.30842   n = 69

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rewrite correlated subquery in SELECT into JOIN statement I have following source table:
CREATE TABLE test
    (`step` varchar(1), `cost_time` int, `rank_no` int)
;

INSERT INTO test
    (`step`, `cost_time`, `rank_no`)
VALUES
    ('a', 10, 1),
    ('b', 20, 2),
    ('c', 30, 3)
;

and query like this:
select
  main.step,
  main.cost_time,
  main.rank_no,
  (select sum(sub.cost_time)
  from test sub
  where sub.rank_no <= main.rank_no)  as total_time
from
  test main

and the result is expected:
| step | cost_time | rank_no | total_time |
|------|-----------|---------|------------|
|    a |        10 |       1 |         10 |
|    b |        20 |       2 |         30 |
|    c |        30 |       3 |         60 |

is it possible to rewrite this sql using join statement and achieve same result?

A: The best way to write this query is using a cumulative sum:
select main.step, main.cost_time, main.rank_no,
       sum(cost_time) over (order by rank_no) as total_time
from test main;

You cannot rewrite this just using join.  You could rewrite it using join and group by:
select main.step, main.cost_time, main.rank_no,
       sum(sub.cost_time) as total_time
from test main join
     test sub
     on sub.rank_no <= main.rank_no
group by main.step, main.cost_time, main.rank_no;

However, I think the correlated subquery is a better solution.


text:
Q: How does work import in python project (django) or issue with import models from tests in django project I have an issue with import models from tests in django project. That is structure of my project:
D:\learn_django\mysite
|   db.sqlite3
|   manage.py
|   test.txt
|   tree.txt
|
+---catalog
|   |   admin.py
|   |   apps.py
|   |   forms.py
|   |   models.py
|   |   urls.py
|   |   views.py
|   |   __init__.py
|   |
|   +---tests
|   |   |   test_forms.py
|   |   |   test_models.py
|   |   |   test_views.py
|   |   |   __init__.py
|   |   |
|   |   \---__pycache__
|   |           test_forms.cpython-39.pyc
|   |           test_models.cpython-39.pyc
|   |           test_views.cpython-39.pyc
|   |           __init__.cpython-39.pyc
|   |

And test_models.py file (which have problem with improt) look like:
from catalog.models import Author
from django.test import TestCase

class AuthorModelTest(TestCase):
    @classmethod
    def setUpTestData(cls):
        # Set up non-modified objects used by all test methods
        Author.objects.create(first_name='Big', last_name='Bob')

    def test_first_name_label(self):
        author = Author.objects.get(id=1)
        field_label = author._meta.get_field('first_name').verbose_name
        self.assertEquals(field_label, 'first name')

*

*If I wirte import like this: from ..models import Author It will be work.

*But if I write import like says in mozilla lesson: from catalog.models import Author
Pycharm report errors: Unresolved reference 'catalog'

*If I try import by absolute path: from mysite.catalog.models import Author Test fails with error: ModuleNotFoundError: No module named 'mysite.settings'
Here you can clone my project - https://gitlab.com/Galoperidol/learn_django3

So my questions are:

*

*Why second and third ways don't work?

*Why, if I replace folder "test" from folder "catalog" to folder "mysite" and try import like: from ..catalog.models import Author
Test fails with error: ModuleNotFoundError: No module named 'mysite.settings'
I know, that all folder to be correct import should have file init.py to be are packages, but it doesn't help.


text:
Q: How to stop Microsoft Cognitive TTS audio playing? I am using the JavaScript version of Microsoft Cognitive Services Speech SDK from https://github.com/Azure-Samples/cognitive-services-speech-sdk.
The audio is played by the browser when synthesizer.speakTextAsync is called. When the audio is too long I want to stop the audio play but I couldn't find any documentation on how to do that?
Any help is appreciated!
    synthesizer = new SpeechSDK.SpeechSynthesizer(speechConfig,
        SpeechSDK.AudioConfig.fromDefaultSpeakerOutput());

    synthesizer.speakTextAsync(
      inputText,
      result => {
        if (result) {
          console.log(JSON.stringify(rssesult));
         }
      },
      error => {
        console.log(error);
      }
    );

A: Stopping audio playing is supported.
You need to create a SpeechSDK.SpeakerAudioDestination() object and use it to create audioConfig like this.
var player = new SpeechSDK.SpeakerAudioDestination();
var audioConfig  = SpeechSDK.AudioConfig.fromSpeakerOutput(player);
var synthesizer = new SpeechSDK.SpeechSynthesizer(speechConfig, audioConfig);
synthesizer.speakTextAsync(
...
);

Then you can call player.pause() and player.resume() to pause and resume the playback.
You can find more info from the doc and sample.


text:
Q: StrongLoop: "in" filter not working for string type ORIGINAL POST
In StrongLoop, the "in" filter it is not working for fields of string type.
I'm posting here to see if anyone else have seen this issue or if its a known issue in StrongLoop MongoDB connector. Also to see if there is any workaround.
It does work for me for integer types fields. But when I test it on string type it doesnt return anything.
I tried the same queries directly in my database MongoDB command line and both integer and string filters worked. So I know my format is correct and that the query I'm trying is valid.
This is part of the code that I'm using in my StrongLoop model custom API to query the database using the in filter.
This works fine:
Grades.find({where: {grade: {in:[1,2]} }},

This doest not work:
Grades.find({where: {subject: {in:["math","biology"]} }},

I didn't put much code here since this requires both database setup and strongloop setup, let me know and I can add more code if necessary.
Thanks,
Carlos
ADDITIONAL DEBUG #1: posting some notes from my continuous debug.
The issue seem to be outside the mongo-db connector. After debugging the following connector (loopback-connector-mongodb/lib/mongodb.js) I see the "function all" is receiving the incorrect filter when the field type is string.
loopback-connector-mongodb/lib/mongodb.js:
//
// Find matching model instances by the filter
//
// param {String} model The model name
// param {Object} filter The filter
// param {Function} [callback] The callback function
//

MongoDB.prototype.all = function all(model, filter, options, callback) {
  var self = this;
  if (self.debug) {
    debug('all', model, filter);
  }

  console.log("carlos999: HERE!!!!");
  if(filter.where['subject']){
    console.log('carlos998: cond:%s cond.constructor.name:%s', filter.where['subject'],   filter.where['subject'].constructor.name);
  }
  if(filter.where['grade']){
   console.log('carlos997: cond:%s cond.constructor.name:%s', filter.where['grade'], filter.where['grade'].constructor.name);
  }

My model:
"grade": {
  "type": "number",
  "required": true
},
"subject": {
  "type": "string",
  "required": true
},

In below sample code you can see how the Array is process properly when the field type is Integer (in this case for debugging purpose, I passed string values inside the array, you can see how they propagate all the way to the MongoDB call). But in the case of string type field ("subject"). The array is not processed properly.
This case works okay
Query:
Grades.find({where: {grade: {in:["math","biology"]} }},

Output:
carlos997: cond:[object Object] cond.constructor.name:Object
carlos929: cond:[object Object] cond.constructor.name:Object
carlos29: k:grade cond:[object Object] cond.constructor.name:Object cond.options:undefined
carlos: propName:grade prop:[object Object]
carlos: spec: in k:grade cond:math,biology cond.constructor.name:Array cond.options:undefined
carlos: MongoDB: model=grades command=find [ { importance: { '$in': [Object] } }, [Function] ]

This case has an issue (possible StrongLoop bug):
Query:
Grades.find({where: {subject: {in:["math","biology"]} }},

Output:
carlos998: cond:[object Object] cond.constructor.name:String
carlos929: cond:[object Object] cond.constructor.name:String
carlos29: k:subject cond:[object Object] cond.constructor.name:String cond.options:undefined
carlos: propName:subject prop:[object Object]
carlos: spec: false k:subject cond:[object Object] cond.constructor.name:String cond.options:undefined
carlos: MongoDB: model=grades command=find [ { subject: '[object Object]' }, [Function] ]

I'm continuing debug, but would be great if other people joins the effort.
Thanks,
Carlos
ADDITIONAL DEBUG #2: more debug notes
To confirm the problem is related to the String type. I changed my model to use "number" instead of "string" just to confirm that the array used by the $in filter is handled properly. And indeed, it worked.
Model change:
"grade": {
  "type": "number",     //changed from string
  "required": true
},
"subject": {
  "type": "number",
  "required": true
},

Output:
carlos998: cond:[object Object] cond.constructor.name:Object
carlos929: cond:[object Object] cond.constructor.name:Object
carlos29: k:subject cond:[object Object] cond.constructor.name:Object cond.options:undefined
carlos: propName:subject prop:[object Object]
carlos: spec: in k:subject cond:math,biology cond.constructor.name:Array cond.options:undefined
carlos: MongoDB: model=grades command=find [ { subject: { '$in': [Object] } }, [Function] ]

A: I think your operator name "in" is misspelled, and shuold be "inq".
From loopback's doc:

The inq operator checks whether the value of the specified property matches any of the values provided in an array.  The general syntax is:

{ where: { property: { inq: [val1, val2, ...] } } }

where:
  property is the name of a property (field) in the model being queried.
  val1, val2, and so on, are literal values in an array.


text:
Q: Add placeholder for free text contact form 7 Hi guys I want to add placeholder for the last option checkbox. Here is my cf7 code,
[checkbox check-question1 free_text id:question1 use_label_element class:filled-in class:other "Instagram" "Facebook" "Twitter" "Tumblr" "Path" "Lainnya:(Social Media Lain)"]
I'm read CF7 documentation here https://contactform7.com/checkboxes-radio-buttons-and-menus/ but nothing documentation for add free text placeholder. How to add placeholder for free text ?

A: You want to add a placeholder to an input checkbox ? That not possible in HTML.
To add a placeholder to an input text, this is the way :
[text your-text placeholder "Lorem"]

A: Unhappily it's not possible right now.
The text input created when free_text options is active has no placeholder option.

A: You can add one last option to your list, like 'Other', and that will display before the free text.
[checkbox check-question1 free_text id:question1 use_label_element class:filled-in class:other "Instagram" "Facebook" "Twitter" "Tumblr" "Path" "Lainnya:(Social Media Lain)" "Other:"]


text:
Q: In Ubuntu, routes are not added as defined in rc.local file....why? I need to setup my ubuntu pc single nic card ip as 192.168.1.6 for internet and 10.172.170.95 and 135.10.86.100 for my lan and for another network through my 4port DSL modem.So i defined like this.
Except addition of last two routes(10.0.0.0/8 & 200.200.176.0/24) everything worked as defined, what is the mistake i did?
In /etc/network/interfaces file
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet static
address 192.168.1.6
netmask 255.255.255.0
gateway 192.168.1.1

In /etc/rc.local file
/sbin/ifconfig eth0:0 135.10.86.100 netmask 255.255.255.0
/sbin/ifconfig eth0:1 10.172.170.95 netmask 255.0.0.0.0
ip route add 10.0.0.0/8 via 10.172.170.6 src 10.172.170.95
ip route add 200.200.176.0/24 via 135.10.86.176 src 135.10.86.100

after restart,
i found
ifconfig output as,
eth0      Link encap:Ethernet  HWaddr 00:11:82:87:12:4b
          inet addr:192.168.1.6  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::221:85ff:fe96:441b/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:760 errors:0 dropped:0 overruns:0 frame:0
          TX packets:576 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:417620 (417.6 KB)  TX bytes:93772 (93.7 KB)
          Interrupt:26 Base address:0xa000

eth0:0    Link encap:Ethernet  HWaddr 00:11:82:87:12:4b
          inet addr:135.10.86.100  Bcast:135.10.86.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          Interrupt:26 Base address:0xa000

eth0:1    Link encap:Ethernet  HWaddr 00:11:82:87:12:4b
          inet addr:10.172.170.95  Bcast:10.255.255.255  Mask:255.0.0.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          Interrupt:26 Base address:0xa000

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:4 errors:0 dropped:0 overruns:0 frame:0
          TX packets:4 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:240 (240.0 B)  TX bytes:240 (240.0 B)

and route -n as,
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
135.10.86.0     0.0.0.0         255.255.255.0   U     0      0        0 eth0
192.168.1.0     0.0.0.0         255.255.255.0   U     0      0        0 eth0
169.254.0.0     0.0.0.0         255.255.0.0     U     1000   0        0 eth0
10.0.0.0        0.0.0.0         255.0.0.0       U     0      0        0 eth0
0.0.0.0         192.168.1.1     0.0.0.0         UG    100    0        0 eth0

A: rc.local is not the best place to set up additional NIC aliases and routes.
Just use /etc/network/interfaces for that.
NIC alias example
static routes example
Concerning your problem:
you use an absolute path to the ifconfig tool, but a relative path to the ip tool. Try using an absolute path there too. Find it by using which ip or whereis ip.


text:
Q: Swift - Assigning struct to a var result always nil i have a little problem with this simple code. I have a var selectedItem of type MyStruct that is alway nil
I have this class
class Test: UIViewController {

var selectedItem: MyStruct?
var collectionData: [OtherStruct]

....

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

     selectedItem = collectionData[indexPath.row].item
}

Then selected item is always nil.
struct OtherStruct {
    var item: MyStruct
    .....
    .....

    init(item: MyStruct) {
        self.item = item
    }
}

struct MyStruct: Codable {
    var test: String
    init(from decoder: Decoder) throws {
        ...
    }
}

My variable selectedItem is always nil. Why?
if i do
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

  let localeSelectedItem = collectionData[indexPath.row].item
}

localeSelectedItem is not nil and is of MyStruct type.
EDIT
If i change
var selectedItem: MyStruct?

to
var selectedItem: Any?

and then i do
if let item = selectedItem as? MyStruct {
}

works
Please note, that collectionData[indexPath.row].item is of type MyStruct (checked with the debugger)


text:
Q: A function with a single if statement returns a display, a function without multiple ifs does not I have a function that contains a single If statement that returns values accordingly.
  const displayMovements = () => {
  return(
  movements.map((e) => {
    if (e.equipment == availableEquipment && e.movementPattern == selectedMovementPattern) {
      console.log(e.movement + " matches")
      return(

{e.movement}

      )
    }
  })
)

}
Another function is similar, but contains multiple If statements that do not display anything, although the console.log() does display accordingly.
  const functionTwo= () => {
  return(
  movements.map((m) => {
    availableEquipment.map((e) => {
      if (m.equipment == e) {
        if (m.movementPattern == selectedMovementPattern) {
          console.log(m.movement + " matches")
          return(

{m.movement}

          )
        }
      }
    })
  })
)
}

Both functions are being called in an identical manner.


text:
Q: How do the macroscopic observables $T$, $ρ$, and $P$ change in an ideal gas after flowing through a turbine? I'm trying to better understand how turbines effect the flow of gas and gain or expend energy in the process. It's easy to understand with incompressible fluids as all you need to know is the pressure differential, rate of flow, and density.
Let's say we have a compressible fluid(ideal gas to be more specific) flowing through a pipe of cross-sectional area A with flow rate f(kg/s), temperature T, density ρ, pressure P, velocity v(v=f/Aρ), heat capacity ratio γ. The gas flows through a turbine of efficiency η and the turbine produces W watts of energy as a result. What are T, ρ, and P for the gas after it passes through the turbine?


text:
Q: What does EnableWindowsFormsHighDpiAutoResizing setting do in C# .NET windows forms application? I am trying to make a per-monitor DPI aware application using C# .NET with regular windows forms (not WPF).
I understand the concept of opting into per-monitor DPI support, and have done this in the manifest:
<!-- Indicates that the application is DPI-aware and will not be automatically scaled by Windows at higher
   DPIs. Windows Presentation Foundation (WPF) applications are automatically DPI-aware and do not need
   to opt in. Windows Forms applications targeting .NET Framework 4.6 that opt into this setting, should
   also set the 'EnableWindowsFormsHighDpiAutoResizing' setting to 'true' in their app.config. -->

<application xmlns="urn:schemas-microsoft-com:asm.v3">
  <windowsSettings>
    <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">True/PM</dpiAware>
  </windowsSettings>
</application>

When I opt into that, my application does not change its pixel size at all when it is dragged from a 96DPI monitor (my default monitor) onto a 144DPI monitor (i.e. the application is pixel-for-pixel identical on both monitors, save for very slight differences in the minimize-maximize-close glyphs). Hence the application is very small and the text is hard to read on the 144DPI monitor.
It seems that the EnableWindowsFormsHighDpiAutoResizing setting has no effect, as my app displays in exactly the same way whether this setting is true or false, unless I have done something wrong in my app.config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="EnableWindowsFormsHighDpiAutoResizing" value="true" />
  </appSettings>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2"/>
  </startup>
</configuration>

Can anybody shed light on what this option does?
Is it part of the solution for writing a C# windows form application which will automatically resize itself when dragged from a 96DPI monitor onto a 144DPI monitor? (by automatic I mean, without me writing code to iterate over all the controls and set a custom scale factor).
I have done many hours of research into this problem and don't have a clear answer myself yet.
It seems that if I opt into per-monitor DPI awareness then I must hanldle the WM_DPICHANGED myself in order to do something. If that is the answer, so be it, but I really feel like I have missed some built in way of doing things.

A: "dpiAware = true" means application should handle the DPI change, otherwise Windows OS will scale the form/font for you. This is my understanding.


text:
Q: Return response.data in function inside .then callback | Axios Is it possible to return a function inside the .then callback?
I want to do something like this:
axios.post('url_api/endpoint')
  .then(function(response){

     renderAdmissionReponse(){

Success response.data

     }

  })

To later render it in a component like this: "

 {this.renderAdmissionReponse()}

Is it possible to do it?

A: I can actually understand your need, however, your above code is wrong!
What you want is: after data are loaded successfully by using axios, the data will be rendered properly on page. If so, you can use the following way:
constructor(props) {
    // ...
    this.state = ({
        admissionResponse: [],
        // your other state variables here
    })
}

renderAdmissionReponse = (data) => {
    this.setState({
        admissionResponse: data,
    });
}

// ... You can put this inside `ComponentDidMount()`, then just call the function to setState with returned data
axios.post('url_api/endpoint')
    .then((response) => {

        this.renderAdmissionReponse(response.data);

    })
// ...

render() {
    return (

{this.state.admissionResponse.authorizationId}

{this.state.admissionResponse.authorizationNum}

            {this.state.admissionResponse.lineItems.map((line) =>{
              return(

{line.id}

{line.lineItemNumber}

              )
            })}

    );
}

Please also check your response.data structure then retrieve the correct keys, the above code I just try to explain about correct react's way on how to load data asynchronously and render on page after that. Please post here some errors if any, thanks.


text:
Q: Methods for finding polynomials in Bézout's identity I need to find (if they exists) $h(x)$ and $k(x)$ in $\mathbb{Q}[x]$ such that
$20 = h(x) (x^2 +1) + k(x) (x^3 -3)$
my manual does not provide any method to compute the unknown functions, I was suggested to use the Euclidean extended algorithm but since it is not treated in the book I'd prefer not using it.

A: $\!\!\bmod\,\overbrace{ x^2+1}^{\color{#c00}{\textstyle \!\!x^2\!\equiv\! -1}\!\!\!}\!:\,\ {-}20 \equiv (\overbrace{3-x\color{#c00}{x^2}}^{\!\!\!\!\!\textstyle 3+x})\,k$ $\iff k \equiv\dfrac{-20^{\phantom{|^|}}}{x+3} \equiv -20\left[ \dfrac{x\, -\, 3}{\smash{\underbrace{\color{#c00}{x^2}-9}_{\large\!\!\! -10}}}\right] \equiv 2(x-3)$
Remark $ $ If mod arithmetic is unfamiliar we can do the same by evaluating the hypothesized Bezout equation  $\, 20 = k(x) (x^2-3) + h(x) (x^2+1)\,$  at $\,x = i^{\phantom{|^|}}\!\!,\,$ yielding
$$20 = k(i)(-i-3)\iff k(i) = \dfrac{\!\!-20}{i+3} = 2(i-3)\ \ \rm as\ above\quad $$
By theory we know there is a solution with $\,\deg k < \deg(x^2+2),\,$ so $\,k = ax+b,\,$ so $\, 2i-6 = k(i) = ai+b \iff (2-a)i = b+6\iff a=2,\, b=-6,\,$ by $\,i\not\in \Bbb Q$

A: Use the extended Euclidean algorithm (same as for $\mathbf Z$):
\begin{array}{r| c c l}
r(x)&u(x)&v(x) & q(x) \\ \hline
x^3-3 & 0 & 1 \\
x^2+1& 1 & 0 & x \\ \hline
-x-3 & -x & 1 & -x+3 \\
10  &1+3x-x^2 & x-3 \\ \hline
\end{array}
Therefore, one obtains
$$ 10 =(1+3x-x^2)(x^2+1) +(x -3)(x^3-3)$$
whence   $\quad 20=2(1+3x-x^2)(x^2+1)+2 (x-3)(x^3-3)$.

A: Just to show that it can be done: $$20=(x^2+1)(ax^2+bx+c)+(x^3-3)(dx+e)$$ $$=(a+d)x^4+(b+e)x^3+(a+c)x^2+(b-3d)x+c-3e$$ so $$a+d=0, b+e=0, a+c=0, b-3d=0,c-3e=20$$ so $$b=3d,e=-b=-3d,c=-a=d,20=c-3e=d+9d=10d$$ hence $$d=2,b=6,e=-6,c=2,a=-2$$ and we have $$h(x)=-2x^2+6x+2,k(x)=2x-6$$


text:
Q: Display PDF in browser with a servlet I want to display a PDF file in browser.  I have the path to the pdf in JS and I am making a call to grab the PDF as a servlet from java.  Here's what I have so far:
JavaScript:
RequestManager.getJSON(Config.server + "getPDF.json?pdfPath=" + this.pathToPdfFile, (function(data){
        $("#" + this.divId).append('<object id="' + this.pdfObjectId + '" data="' + data + '" type="application/pdf" width="600" height="800"></object>');
        ResizeManager.addResizeHandler(this.pdfObjectId, this.divId, -10, -10);
    }).bind(this));

Java:
@RequestMapping("/getPDF")
public void pdfPathToServlet(Model model, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    String pdfPath = request.getParameter("pdfPath");
    if (pdfPath == null || pdfPath.equals(""))
        throw new ServletException("Invalid or non-existent file parameter in UrlServlet servlet.");

    if (pdfPath.indexOf(".pdf") == -1)
        pdfPath += ".pdf";

    File pdf = new File(pdfPath);
    String pdfName = pdfPath.substring(pdfPath.lastIndexOf("/") + 1, pdfPath.length());
    logger.debug(pdfName);
    ServletOutputStream stream = null;
    BufferedInputStream buf = null;
    try
    {
        stream = response.getOutputStream();
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "inline; filename='" + pdfName + "'");
        FileInputStream input = new FileInputStream(pdf);
        response.setContentLength((int) pdf.length());
        buf = new BufferedInputStream(input);
        int readBytes = 0;
        while ((readBytes = buf.read()) != -1)
            stream.write(readBytes);
    }
    catch (IOException ioe)
    {
        throw new ServletException(ioe.getMessage());
    }
    finally
    {
        if (stream != null)
            stream.close();
        if (buf != null)
            buf.close();
    }
}

My problem is that this is showing the binary output in my browser as text.
I'm not sure what I am doing incorrectly.  I have tried changing the header to be attachment instead of inline, but that showed the same thing.  I believe I want inline though, as I wish to show it in browser and not download it.

A: Your JavaScript part makes no sense. You're obtaining a PDF file as ajax response and then attempting to set it as data attribute of the <object> element. The data attribute must point to a real URL, not to the file content. Fix your JS accordingly:
$("#" + this.divId).append('<object id="' + this.pdfObjectId + '" data="' + Config.server + "getPDF.json?pdfPath=" + this.pathToPdfFile + '" type="application/pdf" width="600" height="800"></object>');

The webbrowser will take care about sending the appropriate HTTP request on the given URL and initializing/rendering the <object> element using the Adobe Acrobat Reader plugin — if any available, I'd rather enclose a PDF inside the <object> so that there's at least a graceful degradation to a download link.

Unrelated to the concrete question, that Java code is not part of a servlet at all, but a Spring MVC action. I recommend to get your terms straight and read in our Servlets wiki page to learn what they really are.

A: response.setHeader("Content-Disposition", "attachment;filename=" + pdfName);

A:  response.setHeader("Content-Disposition", "inline; filename='" + pdfName + "'");

You cannot display a PDF inline. It needs to be alone on its own page (or Iframe).


text:
Q: Python - Append input to .txt but deletes prior data I´m trying to append input to a .txt and succeed to do so, however the data previously present in my .txt file gets overwritten by the data inputted. I wish for the data to stay with the input added.
Heres my code so far:
def tilføjMedlem():
    while True:
        tilføjFornavn = input("Skriv fornavn på det medlem du ønsker at tilføje: (Tast q for at afslutte)")
        if tilføjFornavn == 'q':
            break
        else:
            tilføjEfternavn= input("Efternavn:")
            tilføjJollypoints= input("Jollypoints:")
            tilføjInstagram = input("Instagram:")
            tilføjMedlemSiden = input('Medlem siden:')

    with open('fans.txt', 'a') as text_file:
        text_file.write(tilføjFornavn+" "+tilføjEfternavn+" "+tilføjJollypoints+" "+tilføjInstagram+" "+tilføjMedlemSiden)

tilføjMedlem()

A: You need to fix the indentation of the with open() function.
Your code is re-assigning the values to variables you have declared. It will call write to file function only once with the last values entered in the variables after user had entered q to quit.
def tilføjMedlem():
    while True:
        tilføjFornavn = input("Skriv fornavn på det medlem du ønsker at tilføje: (Tast q for at afslutte)")
        if tilføjFornavn == 'q':
            break
        else:
            tilføjEfternavn= input("Efternavn:")
            tilføjJollypoints= input("Jollypoints:")
            tilføjInstagram = input("Instagram:")
            tilføjMedlemSiden = input('Medlem siden:')

        with open('fans.txt', 'a') as text_file:
            text_file.write(tilføjFornavn+" "+tilføjEfternavn+" "+tilføjJollypoints+" "+tilføjInstagram+" "+tilføjMedlemSiden)

tilføjMedlem()

A: The code work
Actually, the code append the text correctly to the .txt file. But it overwrite the previous input you may enter in the while loop.
If the input getter behave like intended, then there is no issues with your code. It get the 4 last inputs you enter, then append them in the file without overwriting it:

however the data previously present in my .txt file gets overwritten by the data inputted

This is false. Your code works.
Here is what I executed:
def tilføjMedlem():
    while True:
        tilføjFornavn = input("Skriv fornavn på det medlem du ønsker at tilføje: (Tast q for at afslutte)")
        if tilføjFornavn == 'q':
            break
        else:
            tilføjEfternavn= input("Efternavn:")
            tilføjJollypoints= input("Jollypoints:")
            tilføjInstagram = input("Instagram:")
            tilføjMedlemSiden = input('Medlem siden:')

    with open('fans.txt', 'a') as text_file:
        text_file.write(tilføjFornavn+" "+tilføjEfternavn+" "+tilføjJollypoints+" "+tilføjInstagram+" "+tilføjMedlemSiden)

tilføjMedlem()

Original file:

This is the original data

Script execution:
Skriv fornavn på det medlem du ønsker at tilføje: (Tast q for at afslutte)
>>>? n
Efternavn:
>>>? First input
Jollypoints:
>>>? second input
Instagram:
>>>? third input
Medlem siden:
>>>? and this is the last one.
Skriv fornavn på det medlem du ønsker at tilføje: (Tast q for at afslutte)
>>>? q

Final file:

This is the original data
q First input second input third input and
  this is the last one.

If the intended behavior is that EVERY inputs append to the file, you have to change the indent of the with block:
def tilføjMedlem():
    while True:
        tilføjFornavn = input("Skriv fornavn på det medlem du ønsker at tilføje: (Tast q for at afslutte)")
        if tilføjFornavn == 'q':
            break
        else:
            tilføjEfternavn= input("Efternavn:")
            tilføjJollypoints= input("Jollypoints:")
            tilføjInstagram = input("Instagram:")
            tilføjMedlemSiden = input('Medlem siden:')

        with open('fans.txt', 'a') as text_file:
            text_file.write(tilføjFornavn+" "+tilføjEfternavn+" "+tilføjJollypoints+" "+tilføjInstagram+" "+tilføjMedlemSiden)

tilføjMedlem()


text:
Q: Ошибки в среде разработки при работе с Unity После переустановки ОС установил Unity Hub, далее unity и visual studio, unity работает, создаю скрипт, открываю и сразу летят ошибки про отсутствующие скобки. Visual studio не дает подсказки про синтаксис юнити. Попробовал подключить Sublime Text и все равно ошибки. Юнити не запускает проект из-за этих ошибок. Подскажите, в чем может быть проблема? Юнити и визуал студио переустанавливал, пробовал удалять все файлы с юнити и визуал студии.

В коде вообще не важно что пишу, даже если ставлю пробел и удаляю, сразу появляются эти ошибки.

A: Свойства класса с модификатором доступа пишутся вне методов.
А переменные методов - без модификаторов доступа

A: Проблема решилась, спасибо за совет добрым людям. Переустановил юнити без визуал студио. Визуал установил отдельно с офф сайта( а не из юнити хаб), предварительно поудалял все папки с остатками визуал студио от предыдущих установок.


text:
Q: Copula of $C_{s(X),t(Y)}$ A question on copula: If $s: \Bbb R\to \Bbb R$ is an increasing function, and $t: \Bbb R\to \Bbb R$ is a decreasing function, find the copula $C_{s(X),t(Y)}$ of $(s(X), t(Y))$ in terms of $C_{X,Y}$. (Assume $X$ and $Y$ to be continuous random variables)

A: Let's introduce some notation, we have the cumulative distribution of $(X,Y)$, $X$ and $Y$ :
$$F_{(X,Y)}(x,y) = \mathbb{P}(X\leq x, Y \leq y) \; , \;\; F_X(x)=\mathbb{P}(X\leq x) \; \mbox{ and } \; F_Y(y)=\mathbb{P}(Y\leq y) \; .$$
Likewise for $(s(X),t(Y))$, $s(X)$ and $t(Y)$ :
$$F_{(s(X),t(Y))}(u,v) = \mathbb{P}(s(X)\leq u, t(Y) \leq v) \; , \;\; F_{s(X)}(u)=\mathbb{P}(s(X)\leq u) \; \mbox{ and } \\ \; F_{t(Y)}(v)=\mathbb{P}(t(Y)\leq v) \; .$$
Now, we first establish the relationship between $F_{(X,Y)}$ and $F_{(s(X),t(Y))}$ :
$$F_{(X,Y)}(x,y) = \mathbb{P}(X\leq x, Y \leq y) = \mathbb{P}(s(X)\leq s(x), t(Y) \geq t(y))$$
The last step is obtained by applying the functions $s$ and $t$ since $s$ preserves order and $t$ reverses it. This can be further transformed into
$$F_{(X,Y)}(x,y) = \mathbb{P}(s(X)\leq s(x)) - \mathbb{P}(s(X)\leq s(x), t(Y) \leq t(y)) = F_{s(X)}(s(x)) - F_{(s(X),t(Y))}(s(x),t(y))$$
Since our random variables are continuous, we assume that the difference between $t(Y) \leq t(y)$ and $t(Y)<t(y))$ is just a set of zero measure.
Now, to transform this into a statement about copulas, note that
$$C_{(X,Y)}(a,b) = F_{(X,Y)}(F_X^{-1}(a),F_Y^{-1}(b))$$
Thus, plugging $x=F_X^{-1}(a)$ and $y=F_Y^{-1}(b)$ into our previous formula, we get
$$F_{(X,Y)}(F_X^{-1}(a),F_Y^{-1}(b)) = F_{s(X)}(s(F_X^{-1}(a))) - F_{(s(X),t(Y))}(s(F_X^{-1}(a)),t(F_Y^{-1}(b)))$$
The left hand side is the copula $C_{(X,Y)}$, the right hand side still needs some work. Note that
$$F_{s(X)}(s(F_X^{-1}(a))) = \mathbb{P}(s(X)\leq s(F_X^{-1}(a))) = \mathbb{P}(X\leq F_X^{-1}(a)) = F_X(F_X^{-1}(a)) = a$$
and likewise
$$F_{t(Y)}(s(F_Y^{-1}(b))) = \mathbb{P}(t(Y)\leq t(F_Y^{-1}(b))) = \mathbb{P}(Y\geq F_Y^{-1}(b)) = 1-F_Y(F_Y^{-1}(b)) = 1-b$$
Combining all results we obtain for the relationship between the copulas
$$C_{(X,Y)}(a,b) = a-C_{(s(X),t(Y))}(a,1-b) \; .$$


text:
Q: Element count of an array in C++ Let's say I have an array arr. When would the following not give the number of elements of the array: sizeof(arr) / sizeof(arr[0])?
I can thing of only one case: the array contains elements that are of different derived types of the type of the array.
Am I right and are there (I am almost positive there must be) other such cases?
Sorry for the trivial question, I am a Java dev and I am rather new to C++.
Thanks!

A: Arrays in C++ are very different from those in Java in that they are completely unmanaged. The compiler or run-time have no idea whatsoever what size the array is.
The information is only known at compile-time if the size is defined in the declaration:
char array[256];

In this case, sizeof(array) gives you the proper size.
If you use a pointer as an array however, the "array" will just be a pointer, and sizeof will not give you any information about the actual size of the array.
STL offers a lot of templates that allow you to have arrays, some of them with size information, some of them with variable sizes, and most of them with good accessors and bounds checking.

A: There are no cases where, given an array arr, that the value of sizeof(arr) / sizeof(arr[0]) is not the count of elements, by the definition of array and sizeof.
In fact, it's even directly mentioned (§5.3.3/2):

.... When applied to an array, the result is the total number of bytes in the array. This implies that the size of an array of n elements is n times the size of an element.

Emphasis mine. Divide by the size of an element, sizeof(arr[0]), to obtain n.

A: Since C++17 you can also use the standardized free function:
std::size(container) which will return the amount of elements in that container.
example:
std::vector<int> vec = { 1, 2, 3, 4, 8 };
std::cout << std::size(vec) << "\n\n";    // 5

int A[] = {40,10,20};
std::cout << std::size(A) << '\n';      // 3

A: No that would still produce the right value because you must define the array to be either all elements of a single type or pointers to a type.  In either case the array size is known at compile time so sizeof(arr) / sizeof(arr[0]) always returns the element count.
Here is an example of how to use this correctly:
int nonDynamicArray[ 4 ];

#define nonDynamicArrayElementCount ( sizeof(nonDynamicArray) / sizeof(nonDynamicArray[ 0 ]) )

I'll go one further here to show when to use this properly.  You won't use it very often.  It is primarily useful when you want to define an array specifically so you can add elements to it without changing a lot of code later.  It is a construct that is primarily useful for maintenance.  The canonical example (when I think about it anyway ;-) is building a table of commands for some program that you intend to add more commands to later.  In this example to maintain/improve your program all you need to do is add another command to the array and then add the command handler:
char        *commands[] = {  // <--- note intentional lack of explicit array size
    "open",
    "close",
    "abort",
    "crash"
};

#define kCommandsCount  ( sizeof(commands) / sizeof(commands[ 0 ]) )

void processCommand( char *command ) {
    int i;

    for ( i = 0; i < kCommandsCount; ++i ) {
        // if command == commands[ i ] do something (be sure to compare full string)
    }
}

A:
Let's say I have an array arr. When
  would the following not give the
  number of elements of the array:
  sizeof(arr) / sizeof(arr[0])?

One thing I've often seen new programmers doing this:
void f(Sample *arr)
{
   int count = sizeof(arr)/sizeof(arr[0]); //what would be count? 10?
}

Sample arr[10];
f(arr);

So new programmers think the value of count will be 10. But that's wrong.
Even this is wrong:
void g(Sample arr[]) //even more deceptive form!
{
   int count = sizeof(arr)/sizeof(arr[0]); //count would not be 10
}

It's all because once you pass an array to any of these functions, it becomes pointer type, and so sizeof(arr) would give the size of pointer, not array!

EDIT:
The following is an elegant way you can pass an array to a function, without letting it to decay into pointer type:
template<size_t N>
void h(Sample (&arr)[N])
{
    size_t count = N; //N is 10, so would be count!
    //you can even do this now:
    //size_t count = sizeof(arr)/sizeof(arr[0]);  it'll return 10!
}
Sample arr[10];
h(arr); //pass : same as before!

A: _countof(my_array) in MSVC

I can thing of only one case: the array contains elements that are of different derived types of the type of the array.

Elements of an array in C++ are objects, not pointers, so you cannot have derived type object as an element.
And like mentioned above, sizeof(my_array) (like _countof() as well) will work just in the scope of array definition.

A: It seems that if you know the type of elements in the array you can also use that to your advantage with sizeof.
int numList[] = { 0, 1, 2, 3, 4 };

cout << sizeof(numList) / sizeof(int);

// => 5

A: First off, you can circumvent that problem by using std::vector instead of an array. Second, if you put objects of a derived class into an array of a super class, you will experience slicing, but the good news is, your formula will work. Polymorphic collections in C++ are achieved using pointers. There are three major options here:

*

*normal pointers

*a collection of boost::shared_ptr

*a Boost.Pointer Container

A:
Let's say I have an array arr. When would the following not give the number of elements of the array: sizeof(arr) / sizeof(arr[0])?

In contexts where arr is not actually the array (but instead a pointer to the initial element). Other answers explain how this happens.

I can thing of only one case: the array contains elements that are of different derived types of the type of the array.

This cannot happen (for, fundamentally, the same reason that Java arrays don't play nicely with generics). The array is statically typed; it reserves "slots" of memory that are sized for a specific type (the base type).

Sorry for the trivial question, I am a Java dev and I am rather new to C++.

C++ arrays are not first-class objects. You can use boost::array to make them behave more like Java arrays, but keep in mind that you will still have value semantics rather than reference semantics, just like with everything else. (In particular, this means that you cannot really declare a variable of type analogous to Foo[] in Java, nor replace an array with another one of a different size; the array size is a part of the type.) Use .size() with this class where you would use .length in Java. (It also supplies iterators that provide the usual interface for C++ iterators.)

A: Use the Microsoft "_countof(array)" Macro. This link to the Microsoft Developer Network explains it and offers an example that demonstrates the difference between "sizeof(array)" and the "_countof(array)" macro.
Microsoft and the "_countof(array)" Macro

A: If you can not use C++17, which allows to use std::size(container), you can easily implement your own generic sizeofArray template function as a one-liner:
#include <cstddef>
#include <cstdio>

template< typename T, std::size_t N >
inline constexpr std::size_t sizeofArray( const T(&)[N] ) noexcept { return N; }

int x[10];
void* y[100];
long z[1000];
struct {int x; char y; long z;} s[123];

static_assert( sizeofArray(x) == 10, "error" );
static_assert( sizeofArray(y) == 100, "error" );
static_assert( sizeofArray(z) == 1000, "error" );
static_assert( sizeofArray(s) == 123, "error" );

int main() {
    puts( "ok" );
}

test it here: http://cpp.sh/8tio3

A: It will work if and only if arr is a C-Array (type[size]; except for function parameters!), a reference to a C-Array (type(&)[size]) or a pointer to a C-Array (type(*)[size]).
Note you should use std::size or std::ssize instead with current C++-Standards!
In C++17 you can use std::size:
int arr[] = {1, 2, 3};
auto count = std::size(arr); // type std::size_t, value == 3

In C++20 you can additionally get a signed value by using std::ssize:
int arr[] = {1, 2, 3};
auto count = std::ssize(arr); // type std::ptrdiff_t, value == 3

*

*https://en.cppreference.com/w/cpp/iterator/size

Also note that C++ unfortunately inherited from C that C-Arrays are never passed by value (deep copy) to functions.
void f(int a[3]);

is the same as
void f(int* a);

so you loose the information that a is an array and with this, how much elements it had. The 3 is completely ignored by the compiler!
If you want to preserve the datatype (including the array element count), you can use a pointer or a reference to an C-Array:
void f(int (&a)[3]); // reference to C-Array with 3 elements
void f(int (*a)[3]); // pointer to C-Array with 3 elements
void f(int a[3]);    // pointer to int
void f(int* a);      // pointer to int

If you want to call functions with Arrays call-by-value, you can use C++-Arrays (std::array) from the C++ standard library:
f(std::array<int, 3> a);

std::array<int, 3> arr = {1, 2, 3};
f(arr); // deep copy

*

*https://en.cppreference.com/w/cpp/container/array

A: Determine how many numbers are in your array.
#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n[10]  ;

    int l = sizeof(n)/sizeof(n[0]);

    cout << l;

    return 0;
}

A: I know is old topic but what about simple solution like while loop?
int function count(array[]) {

    int i = 0;

    while(array[i] != NULL) {

        i++;

    }

    return i;

}

I know that is slower than sizeof() but this is another example of array count.


text:
Q: How to do antialiasing on a rotated view?
Possible Duplicate:
Any quick and dirty anti-aliasing techniques for a rotated UIImageView?

when a UIView is rotated, it's borders look incredible ugly. There's no antialiasing happening  at all. Also if it's a UIImageView, no antialiasing happens when rotating the transform matrix. Is there a way to achieve smooth edges and smooth rotation of images?

A: For a UIImageView, add a one-pixel transparent border around the image. This will cause the edges of your image to be on the "inside", and because the inside pixels are interpolated when rotating, the borders will magically become antialiased. This also works for rotating UIButtons that have a custom image.


text:
Q: Write left header (´ihead´) normal NOT cursively using ´scrpage2´ Purpose
Write left header (´ihead´) normal NOT cursively using ´scrpage2´.
I tried some code but it made no sense.
Code
This code is used:
\usepackage{scrpage2}
\pagestyle{scrheadings}
\usepackage{totpages}
\clearscrheadfoot
\ihead{Header Left }
\ohead{Header Right}
\ifoot{Footer Left}
\ofoot{Footer Right}
\setheadtopline{0mm}
\setheadsepline{0.1mm}
\setfootsepline{0.1mm}
\setfootbotline{0mm}

Footer left and right are written normal.
Header left is written cursively.

A: scrpage2.sty defines a command, \headfont that controls the font used to typeset headers. This is initially defined as \normalfont\slshape, i.e., using the slanted (italic) version of the default font. There are several things you can do to change this:

*

*If all you want to do is change only the inner header without affecting the outer header, change your \ihead command:
\ihead{\upshape Header Left}

*If you want to change the default for headers (which will change the outer header as well), redefine \headfont:
 \renewcommand*{\headfont}{\normalfont}

You can then use something like \ohead{\slshape Header Right} if you want the right header to be italicised.
A couple of (unsolicited) remarks:

*

*scrpage2 has been deprecated in favour of scrlayer-scrpage.

*Technically speaking \ihead is the inner header and not necessarily the left header of the page. You may want to look at Figure 5.1 of the KOMA-Script documentation for a picture of what's going on. Of course, if your page style doesn't distinguish between even and odd pages, this is irrelevant, but its worth being aware of.


text:
Q: Div height changing with new media screen CSS The page here has a fixed header and header highlight box-shadow with 3ems of padding added to the body, but when changing this to relative positioning for laptop resolutions so they can see more of the page, the header text moves down slightly with the new CSS and the header highlight is 1px too high so you can't see it.
It's quite subtle, but you can notice it.  Here's the new CSS:
body {
  padding-top: 0;
  }

.headerHighlight, .header {
  position: relative;
  }

#main-content {
  padding-top: 0.7em;
  }

Any ideas appreciated

A: The .headerHighlight element should be inside of the .header element:

The .headerHighlight element needs to be positioned absolutely, and the .header element must remain positioned relatively:
    .header {
        position: relative;
    }
.headerHighlight {
    position: absolute;
    bottom: 0px;
    right: 0px;
}


text:
Q: Save data to file not working properly I use the following code to save password in a txt file:
String  FILE_NAME="lol.txt";
public void writeData(String password){
            FileOutputStream fOut = null;
            OutputStreamWriter osw = null;
            try{
                fOut = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
                osw = new OutputStreamWriter(fOut);
                osw.write(password);
                osw.close();
                fOut.close();
                }catch(Exception e){
                    e.printStackTrace(System.err);
                }
            }

but When I retrive the password that I just Saved using toast its appears OK, but when I Log it into my LogCat I got Something like the following:
gana???????????????????????????????????? .... and more four lines.

I save the word gana into my file using save method which work as OnClikc method that set value of EditText as password as below:
public void save(View v){
            password= txt.getText().toString();
            writeData(password);
     }

any Way or clue how can I solve this problem?
regards

A: Use below code to reading file
byte[] b = null;
    try
    {
        //read file data...
        FileInputStream myFile = openFileInput("lol.txt");
        b = new byte[1024];
        myFile.read(b);
        Log.i("Pass", "File data is: " + new String(b).trim());
        myFile.close();
    }
    catch (IOException e)
    {
    }

only difference with your code is that i am using new String(b).trim() to remove blank space.


text:
Q: SQuirrelSQL redirect ouput to a file? Does anybody knows if SQuirrel SQL client may output the of several SQL commands to a single result window in textplain or to a file ( as SQL+ would )
So I can:
 select * from dual;
 select * from dual;

And have both results in a single "ready to" Ctrl-C format?

A: I don't know SQuirreL, but this works on every SQL variant I have tried:
select * from dual;
union all
select * from dual;

A: I managed to find out where to specify the output format.
With this I could at least copy/paste the output but still I have to click on each tab result.
I guess this would do for now.


text:
Q: How to properly get screen rotation programmatically? I need to programatically obtain screen rotation. I'm using Qt and the X extension XRandr. I'm trying the following:
Display *dpy;
Window root;
XRRScreenConfiguration *conf;
Rotation rotation;

int screen;

dpy = QX11Info::display();
root =  QX11Info::appRootWindow();
conf = XRRGetScreenInfo(dpy, root);
screen = DefaultScreen(dpy);
XRRRotations(dpy, screen, &rotation);

qDebug() << "CURRENT ROTATION:" << rotation;

The problem is that independently of the current screen orientation, set through Displays settings app from Ubuntu, the CURRENT ROTATION output is always 1.
Does anyone knows why?
Thanks

A: I finally found the answer to this. I'm using Qt. Some of the calls are from Qt to get the Window and Screen of X11.
Display *dpy;
Window root = this->winId();
dpy = QX11Info::display();

XRRScreenResources *scrres = XRRGetScreenResources(dpy, root);
XRRCrtcInfo *crtcInfo = XRRGetCrtcInfo(dpy, scrres, *scrres->crtcs);

crtcInfo->rotation can be 1, 2, 4, or 8

Hope this helps someone in the future.


text:
Q: How to update an attribute in object based on a variable in javascript I want to update an attribute of an object but the attribute is not known before hand and is rather stored in a variable.
I have an object "obj" like below
 var obj={ a : 1, b : 2 }

if I want to change attribute "a" to 3 then I can just do
obj.a = 3
but I have a variable "attribute_to_change" which has the attribute that I want to change. I want to be able to somehow use the variable value to change the respective object attribute.
Something like below
obj.attribute_to_change = 3

Currently I have to write a separate line code of for each type of attribute that I want to change. But I can actually just make one function and pass the value and the attribute to be changed if I figure this out.


text:
Q: how to handle $updates array in Facebook real time update callback.php page Here is the code of Facebook callback.php page.
Now how can I handle post method response ($updates variable)?
if ($method == 'GET' && $_GET['hub_mode'] == 'subscribe' &&
    $_GET['hub_verify_token'] == VERIFY_TOKEN)
    {
     echo $_GET['hub_challenge'];
    }
else if ($method == 'POST') {
  $updates = json_decode(file_get_contents("php://input"), true);

  //what to do here.

  error_log('updates = ' . print_r($updates, true));
}

A: Since many people seem to be struggling with this, I therefor decided to make a detailed tutorial on how to use the Facebook Real-Time Updates API:
http://www.codedestination.com/1/post/2013/05/-facebook-real-time-updates-api-tutorial-part-i.html
What you are looking for is explained in part two of the tutorial-series.
It explains both how to decode the JSON object notifications that you receive from FaceBook and also how to store these updates into your own database.
I hope this helps! Best of luck!


text:
Q: How change host for mongodb using spring boot? Here are my beans:
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:mongo="http://www.springframework.org/schema/data/mongo"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<!-- Activate annotation configured components -->
<context:annotation-config/>

<!-- Scan components for annotations within the configured package -->
<context:component-scan base-package="document">
    <context:exclude-filter type="annotation" expression="org.springframework.context.annotation.Configuration"/>
</context:component-scan>

<!-- Define the MongoTemplate which handles connectivity with MongoDB -->

<mongo:mongo host="192.168.0.10" port="27017" />
<mongo:db-factory dbname="yourdb" />

<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
</beans>

Here is my DAO
@Repository
public class DocumentRepository {

    @Autowired
    MongoTemplate mongoTemplate;

    def insertDocument(DocumentModel document) {
        return mongoTemplate.insert(document)
    }
}

Every time I call insert I get the following error:
*Timed out after 10000 ms while waiting for a server that matches
 AnyServerSelector{}. Client view of cluster state is {type=Unknown,
 servers=[{address=localhost:27017, type=Unknown, state=Connecting,
 exception={com.mongodb.MongoException$Network: Exception opening the
 socket}, caused by {java.net.ConnectException: Connection refused}}];

 nested exception is com.mongodb.MongoTimeoutException: Timed out after
 10000 ms while waiting for a server that matches AnyServerSelector{}.

 Client view of cluster state is {type=Unknown, servers=
 [{address=localhost:27017, type=Unknown, state=Connecting, exception=
{com.mongodb.MongoException$Network: Exception opening the socket},
 caused by {java.net.ConnectException: Connection refused}}]*

Here is my main file
@Configuration
@EnableAutoConfiguration
@ComponentScan("document , filter")
class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

I have mongodb running on a different box i.e. 192.168.0.10. For some reason it keeps showing it's trying to connect to localhost. Any ideas what I am missing?

A: I ended up getting the host to change by adding the following line to my main class.
/*
 * Factory bean that creates the com.mongodb.Mongo instance
 */
public @Bean MongoClientFactoryBean mongo() {
    MongoClientFactoryBean mongo = new MongoClientFactoryBean();
    mongo.setHost(host);
    return mongo;
}

A: Replace
<mongo:mongo host="192.168.0.10" port="27017" />
<mongo:db-factory dbname="yourdb" />

with
<mongo:db-factory host="192.168.0.10" port="27017" dbname="yourdb" />

A: When using
<mongo:db-factory dbname="yourdb" />

an internal Mongo client instance is registered with the db factory using the default host and port number.
In order to fix it, use
<mongo:db-factory dbname="yourdb" mongo-ref="mongo"/>

which references the mongo bean instance created just above.

A: Why are you using all those XML config stuff in addition to spring boot which does pretty much the same under the hood for you.
Add
spring.data.mongodb.host=192.168.0.10
spring.data.mongodb.database=YOURDB

to your application.properties alternatively:
-Dspring.data.mongodb.host=192.168.0.10 -Dspring.data.mongodb.database=YOURDB

as parameters for your program


text:
Q: How to deserialize json to a complicated object by using spring mvc? Let's say i have posted JSON to server as following:
{
    warFile: {name: "test1", dependencies: [test0, test2]},
    param: {build: true, test: true}
}

And i have 3 classes as following:
public class WarFile{
   private String name:
   private String[] dependencies;
   public void setName(){...};
   public String getName(){...};
   public void setDependencies(){...};
   public String[] getDependencies(){...};
}

public class Param{
   private boolean build;
   private boolean test;
   public void setBuild(){...};
   public boolean isBuild(){...};
   public void setTest(){...};
   public boolean isTest(){...};
}

public class Command{
    private WarFile warFile;
    private Param param;
    private void setWarFile(){...};
    private WarFile getWarFile(){...};
    private void setParam(){...};
    private Param getParam(){...};
}

Controller as below:
@RequestMapping(value = "/test.ajax", method = RequestMethod.POST)
public @ResponseBody
BuildResult buildWar(@RequestBody Command cmd) {
    return logic.build(cmd.getWarFile(), cmd.getParam());
}

And since warFile and param in Command are not a primitive type, I always get the following error:
The request sent by the client was syntactically incorrect.

I'm sure that there is not any problem if all the properties in Command are primitive type. But how comes this error happened? I mean, the objects are simple, no need to write a custom deserializer for them.

A: Is your request mapping is /test.ajax or /test in your html <form>?
Have you added jackson mapper jar dependency ? if yes next solution would be escape your quotes i guess. this might help
Spring MVC : The request sent by the client was syntactically incorrect
Getting HTTP status 400 - The request sent by the client was syntactically incorrect: using curl to post/put json request

A: "The request sent to the client was syntactically incorrect" means there is something wrong with the content of the request you sent, not necessarily your controller or Spring configuration. First off, your JSON is not valid. Jackson can't properly map the JSON to the objects it should represent. It should be:
{
    "warFile": {
        "name": "test1",
        "dependencies": ["test0", "test2"]
    },
    "param": {
        "build": true,
        "test": true
    }
}

Second, make sure the content type is application/json. Lastly, why does your Command object have private getters/setters, and your setters don't have field parameters?


text:
Q: Should I enable or disable upside down in my iOS app? I made an iOS app with some web views an a contact page. You can navigate by using the toolbar on the bottom. I enabled landscape and, of cause portrait mode.
Should I enable upside down in my iOS app, too? Ore should i rather disable it? What is more user-friendly? What do you prefer?

A: If your app contains web views and contact pages then you should probably not enable upside down as it may not be user-friendly and cause inconvenience to the user while receiving calls, etc.
However, music and voice memo seems to be some situations where Apple saw fit to enable upside down. The reason is:
1.Voice Memos: Since the main microphone is on the bottom of the device, this app decides to allow this seemingly taboo orientation and kindly rotates the interface for you.
2.Music: It seems to be another case where Apple saw fit to allow an upside down orientation, but only if your device is plugged into, and playing music through, something like a car stereo. Maybe Apple accommodated for that kind of situation where the device often needs to be placed in a strange orientation in order to fit into a car setup.
Check this for reference.
There are also some apps which support upside-down texting. Go through the link for details.
So, it entirely depends on the functionality of your app to decide whether upside-down should be enabled or not. You can provide the use of your app to get more precise answers.

A: The upside down orientation on iOS was introduced mainly for iPad apps, where it's more common open an app with the device rotated of 180°.
So if your app support iPad you should enable this orientation. As confirmation in Apple Documentation you can read:

Important: It is strongly recommended that your iPad applications
  support all orientations. This includes portrait, portrait
  upside-down, landscape left and landscape right. iPad apps that
  require an orientation must support both variants of that orientation.


text:
Q: onsubmit breaks Jade view I have a form page that takes some inputs, stores the data in mongo and returns the data to the view underneath the form. However, when a user submits new data on the form, the jade view crashes and displays the following error:
TypeError: /Users/rhysedwards/Downloads/insightful/food/views/index.jade:29
    27|         label
    28|           input.btn.btn-default(name='submit', type='submit', onsubmit="this.submit(); this.reset(); return false;")
  > 29|       each Entry, i in entries
    30|         div.title= Entry.title
    31|         div.url= Entry.url
    32|         div.selectedDate= Entry.selectedDate

Cannot read property 'length' of undefined

The expected behaviour is that when a user submits new data through the form, it displays underneath the form. Why does Entry become undefined onsubmit but the data still displays prior to a submit?
Router
router.get('/', function(req, res, next){
  Entry.find({}, function (err, entries) {
    res.render('index', {
      "entries": entries
    });
  });
});

Jade
block content
  .container
    h1 London Plans
    form(method='post' action='post', class='plans', id='plans')
      .form-group
        label Do you have a link?
        input.form-control(name='search', id='search' type='url', required='required')
        h2#title
      .form-group
        label What looks cool?
        input.form-control(name='title', type='text', required='required' class='title')
      .form-group
        label When is it?
        label
          input(type='checkbox' name='week' value='week')
          span This week
        label
          input(type='checkbox' name='month' value='month')
          span This Month
        label
          input(type='checkbox' id='date')
          span Date
        label
          input(type='textbox' class='datepicker' name='date' value='')
        label
          input.btn.btn-default(name='submit', type='submit', onsubmit="this.submit(); this.reset(); return false;")
      each Entry, i in entries
        div.title= Entry.title
        div.url= Entry.url
        div.selectedDate= Entry.selectedDate

Post function
router.post('/post', function(req, res, next) {
  var url = req.body.search;
  var title = req.body.title;
  var week = req.body.week;
  var month = req.body.month;
  var date = req.body.date;

  console.log(url + ' ' + title + ' ' + week + ' ' + month + ' ' + date);

  //FIND WHICH DATE WAS SELECTED BY USER AND ASSIGN THAT TO selectedDate
  if (typeof week != 'undefined' ){
    var selectedDate = 'week';
  } else if (typeof month != 'undefined') {
    var selectedDate = 'month';
  } else {
    var selectedDate = date;
  };

  //CREATE NEW OBJECT
  var data = new Entry ({
    url: url,
    title: title,
    selectedDate: selectedDate
  })

  //STORE NEW OBJECT TO THE DB
  Entry.createEntry(data, function(err, entry){
    if (err) throw err;
    console.log(entry);
  })

  //RENDER THE HOMEPAGE TO CLEAR THE FORM
  res.render('index');
  return false;
});

A: The reason why entries is undefined upon resubmission is because in your router.post handler you're not supplying the Jade template with a value for that variable.
Here is the code in your router.post handler which causes this:
res.render('index'); // telling the page to render without variables

Now, compare this to the successful code in the router.get handler:
res.render('index', {
    "entries": entries // here is where you assign variables for Jade
});

As you can see, in the router.get handler you're supplying the Jade template engine with a value for the "entries" variable with entries, which is a value returned by the call you make to mongodb.
It might be worth having a look at the express docs for res.render() for more information. Here's the excerpt in question which sheds some light on the situtation:

res.render(view [, locals] [, callback])
Renders a view and sends the rendered HTML string to the client.
  Optional parameters:
locals, an object whose properties define local variables for the
  view.

From the definition of the locals argument, you can see where you went wrong! Happy coding :)


text:
Q: How does vlc.py play video stream? I want to use vlc.py to play mpeg2 stream http://wiki.videolan.org/Python_bindings.
There are some examples here: http://git.videolan.org/?p=vlc/bindings/python.git;a=tree;f=examples;hb=HEAD
When I run the examples, it just can play video file, I want to know is there any examples to play video stream ?

A: According to this Pastebin entry, linked to in this mailing list, it can be solved using a method like this:
import vlc
i = vlc.Instance('--verbose 2'.split())
p = i.media_player_new()
p.set_mrl('rtp://@224.1.1.1')
p.play()

I haven't tried it though, so please let me know if it works.

A: This is a bare bones solution:
import vlc
Instance = vlc.Instance()
player = Instance.media_player_new()
Media = Instance.media_new('http://localhost/postcard/GWPE.avi')
Media.get_mrl()
player.set_media(Media)
player.play()

if the media is a local file you will have to alter:
Media = Instance.media_new('http://localhost/postcard/GWPE.avi')
Media.get_mrl()

to:
Media = Instance.media_new_path('/path/to_your/file/filename.avi')

note that you must lose the get_mrl() as well as changing the function.

A: import vlc
vlcInstance = vlc.Instance()
player = vlcInstance.media_player_new()
player.set_mrl("rtsp://URL_PATH")
player.play()

I was able to open a stream with the following code, combining the previous answers.
Tested this with a network webcam


text:
Q: is there standard sql that works in all database As seen below the syntax is different for different Database .Isnt there a standard way that works in all Databases.
Is there any tool to convert any sql to any sql
SqlServer2005:
 CREATE TABLE Table01 (
 Field01  int  primary key identity(1,1)
 )

Sqlite:
CREATE TABLE Table01 (
  Field01  integer PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE
);

A: The "query" part of SQL (commonly called DML - Data Manipulation Language) is reasonably standardized, and queries written on one database will often run on another database if no "vendor enhancement" features are used.  The "create database bits" parts of SQL (often known as DDL - Data Definition Language) is not standardized, and every database out there does it a little differently.  So, as you've discovered, statements such as CREATE TABLE written for one database will not work without some tweaking on another database.
<soapbox>
In my opinion this is a Good Thing.  DDL effectively defines what can be created in the database.  If all vendors use exactly the same DDL, then all products are going to be exactly the same in terms of the features they support.  For example, in order to allow for table inheritance in PostgreSQL there must be some way to define how one table inherits from another, and this definition must be part of how a table is defined, either as part of the CREATE TABLE statement or in some other fashion, but it has to be a DDL statement.  Thus, for purely functional reasons (because PostgreSQL supports a feature which most databases do not) DDL in PostgreSQL must be different than in other databases.  A similar situation arises in MySQL because it allows the use of different ISAM engines with different capabilities.  Similar situations arise in Oracle...and in SQL Server...and <your favorite database here>.
Standards are a double-edged sword.  One one hand they're a great thing, because they provide a "standard" way of doing something.  On the other hand they're a terrible thing because the very purpose of a standard is to provide a "standard" way of doing something, which is another way of saying "create stagnation and inhibit innovation".
</soapbox>
Share and enjoy.

A: There are several SQL standards out there, and SQL 1999 is probably the closest you will get, as each DB adopted a different standard (if any).

A: No, there's no standard SQL for this. As a shameless plug, I can recommend trying Wizardby if you're into anything related to database schema migration/continuous integration.


text:
Q: Ellipsis after a comma I want to use an ellipsis to indicate a sentence is being interrupted. That point of interruption happens to be right after an appositive which has commas around it. Does the second comma get omitted or does it stay?
A: The owner, Carl...
B: The owner, Carl,...

The second way seems more correct, but it looks funny.

A: Ellipses can sometimes be confused as trailing off rather than an interruption in dialogue. The em dash is more clearly recognizable as an interruption. Also, it's a lot easier to see an interruption if it's in the middle of a word. I would use:

"The owner, Carl, w--"

If you're sure you want to use ellipses, and you want the comma, then put a space between them. The ",..." looks like you either made a typo or are trying to invent a new weird punctuation mark. I like the look of this better:

"The owner, Carl, ..."

A: If you're writing this (as a work of fiction, particularly) you have some idea of how the sentence might have continued had it not been interrupted. But if a sentence really is interrupted no-one listening will know, at that point, how the sentence was intended to continue. The comma after Carl is only there to make sense of what comes after. But nothing does.
So it's my contention that the ellipsis cuts off the flow before the comma, which is therefore inappropriate.
(A comma also represents a pause, but not one quite as long as an ellipsis, so again, it's unnecessary.)

A: I, on the other hand from sooeithdk, regard the first as misleading, almost completely wrong. And why? Because Carl does not stand in any sort of equivalence to the clause that follows the comma. The sentence is not a parallel to the following type of constructions, where the single comma makes sense:
After the death, Carl was trying to hire more workers.
During the strike, Carl was trying to hire more workers.
Standing on a beer barrel, Carl was tryimg to hire more workers.
Carrying a pink parasol, Carl was trying to hire more workers.
I therefore prefer your second construct because it clearly equates "Carl" to "the owner". The use of both commas rather than one parallels the parenthetical sentence "Carl (the owner) was trying to hire more workers." This makes the meaning entirely clear.

A: Second one is definitely the correct one. You will understand it better once you see example sentences.

The owner, Carl was trying to hire more workers.
The owner,  (who was) Carl, was trying to hire more workers.

The second one is rather explaining who Carl is than interrupting the sentence to inform what the name of the owner is.
The first one sounds more natural and complete. Even though you can use the first example in case you want to, I definitely suggest that you use the first one if it is to be used as an interruption.

A: I would omit the comma if you are replacing it with a dash or ellipsis.
Why? Because the comma and ellipsis both indicate pauses when speaking, and you don't typically double up punctuation of the same type.  For example, the ellipsis represents a pause.  But you don't keep adding dots to lengthen it (although that's a common mistake to see), and you don't combine it with a dash to indicate a longer pause.
Even if you add the rest of the sentence later, that doesn't mean you should keep the comma. Punctuation is not deferred in my experience. It represents something immediately connected to the word it's next to or surrounding.  So if you're writing dialogue, and you cut a sentence off because another character interrupts, you would use punctuation that fits what the other characters actually "heard", not what might have been correct if the sentence had completed in its entirety.


text:
Q: Applying Logic to Grouped SQL Results Looking for some Oracle SQL theoretical help on the best way to handle a grouped result set.  I understand why it groups the way it does, but I'm trying to figure out if there's a way to
I have a table that lists the activity of some cost centers.  It looks like this:
Company    Object    Sub    July    August
A          1                20      50
A          1                10      0
A          1         10     0       20
B          1                0       0

I then need to flag whether or not there was activity in August.  So I'm writing a CASE statement where if August = 0 THEN 'FALSE' ELSE 'TRUE'.  Then I need to group all records by Company, Object, and Sub.  The Cumulative column is a SUM of both July and August.  However, my output looks like this:
Company    Object    Sub    SUM    ActivityFlag
A          1                70        TRUE
A          1                10        FALSE
A          1         10     20        TRUE
B          1                0         FALSE

What I need is this:
Company    Object    Sub    August    ActivityFlag
A          1                80        TRUE
A          1         10     20        TRUE
B          1                0         FALSE

Obviously, this is a simplified example of a much larger issue, but I'm trying to think through this problem theoretically so I can apply similar logic to my actual issue.
Is there a good SQL method for adding the August amount for rows 1 and 2, and then selecting TRUE so that this appears on a single row?  I hope this makes sense.

A: use aggregation
select company,object,sub,sum(july+august),
max(case when august>0 then 'True' else 'false' end)
from table_name group by company,object,sub

A: If you are flagging your detail with the case statement you can either put the case in a sum similar to:
MAX(CASE WHEN August = 0 THEN 1 ELSE 0 END)

Another way if to aggregate the flag upward in an inner query:
SELECT IsAugust = MAX(IsAugust) FROM
(
   ...
   IsAugust = CASE WHEN August=0 THEN 1 ELSE 0 END
   ...
)AS X
GROUP BY...


text:
Q: Is there a way to obtain the keys from a deleted record? I'm using PostgreSQL to save a form in three tables, one for the name and id, another one for the fields to populate, and a third to store values for the fields.
private static final String REMOVE_FORM = "DELETE FROM forms WHERE name = ?";
private PreparedStatement removeFormQuery;

public boolean connect() throws SQLException{
    this.connection = DriverManager.getConnection(URL);
    this.removeFormQuery = this.connection.prepareStatement(REMOVE_FORM);
}
public void close() throws SQLException {
    if(null != this.connection) {
        this.connection.close();
    }
    if(null != this.removeFormQuery) {
            this.removeFormQuery.close();
    }
}

private void removeForm(String form) {
    try {
        removeFormQuery.setString(1, form);
        int execute = removeFormQuery.executeUpdate();
        System.out.println(execute);
        ResultSet generatedKeys = removeFormQuery.getGeneratedKeys();
        while (generatedKeys.next()) {
            int anInt1 = generatedKeys.getInt("id");
            removeFieldQuery.setInt(1, anInt1);
            if (removeFieldQuery.execute())
                System.out.println("remove field failed");
            else
                System.out.println("remove field success");
            ResultSet generatedFieldsKeys = removeFieldQuery.getGeneratedKeys();
            while (generatedFieldsKeys.next()) {
                int anInt = generatedFieldsKeys.getInt("id");
                removeListItemQuery.setInt(1, anInt);
                if (removeListItemQuery.execute())
                    System.out.println("remove listItem failed");
                else
                    System.out.println("remove listItem success");
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

The code doesn't generate keys after the remove query is executed, am I missing something?

A: While you haven't told us what queries you are running, if they are deletes then you wouldn't expect any generated keys.
From the Javadoc for Statement.getGeneratedKeys():
     * Retrieves any auto-generated keys created as a result of executing this
     * Statement object. If this Statement object did
     * not generate any keys, an empty ResultSet
     * object is returned.

Keys may be auto generated when you insert into a table, creating a new row which needs a primary key, but when you delete a row no key generation occurs.


text:
Q: caching sam setup in github workflow I have this reusable workflow:
`
test:
    name: Test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - uses: actions/setup-python@v3
        with:
          python-version: '3.8'

      - uses: aws-actions/setup-sam@v2

      - name: build
        run: sam build --beta-features

`
I call this workflow with a matrix from outside. However the setup=-sam@v2 is taking a lot of time: around 26secs. Is it possible to cache this between matrix runs?
Thanks
Trying to fasten the setup of sam in github workflow

A: Matrix strategy is used per job, so one possibility is to pull this
- name: build
  run: sam build --beta-features

into a separate job instance. Then you will use with matrix strategy only this part:
- name: build
  run: sam build --beta-features

If you want to use caching try sth like:
test:
  name: Test
  runs-on: ubuntu-latest
  steps:
    - uses: actions/checkout@v3

    - uses: actions/setup-python@v3
      with:
        python-version: '3.8'

    - name: Cache sam
        id: cache-sam
        uses: actions/cache@v3
        with:
          path: <specify the path>
          key: ${{ runner.os }}-sam

    - uses: aws-actions/setup-sam@v2
      if: steps.cache-sam.outputs.cache-hit != 'true'

    - name: build
      run: sam build --beta-features

However, we have to provide a path in the above code snipped. Maybe the installation path will be good.
Please check out the following links:

*

*https://github.com/actions/cache

*How do I cache steps in GitHub actions?


text:
Q: Where is the wormhole in a Schwarzschild geometry? I am new on wormholes and in my understanding, an interpretation of a wormhole connecting two "universes" can be obtained by doing coordinate transformations on the Schwarzschild metric.
I am following Harlows notes (sec. 2) where he starts reviewing the Schwarzschild black hole solution which most people are familiar with:
$$ds^2 = -\frac{r-2GM}{r} dt^2 + \frac{r}{r-2GM}dr^2 + r^2 d\Omega^2 $$.
To avoid coordinate singularities one can play around and let $t = \pm r_* + C$ where C is some constant and $r_* = r + \log(r-1)$ is a new radial coordinate. Furthermore, we can now define useful Kruskal-Szekeres coordinates:
\begin{equation}
U=-e^{\frac{r_*-2}{2}}, \quad V=e^{\frac{r_*+t}{2}}.
\end{equation}
These coordinates has many useful features. Finally, we can define the last two coordinates, $T$ and $X$ via
\begin{equation}
U = T-X, \quad, V = T+X.
\end{equation}
The resulting metric yields
\begin{equation}
ds^2 = \frac{4}{r}e^{-r} \Big(-dT^2 + dX^2 \Big) + r^2 d\Omega^2.
\end{equation}
As I understand it, these coordinates can describe more spacetime around the Schwarzschild black hole. What does not really sit well with me is where the wormhole comes into the picture? How do we know that wormholes are not just an artifact of playing around with coordinates?
I also have the main follow-up questions I would love some input on.
If there are two "external spacetimes" that can be interpreted as a wormhole, where exactly is this wormhole? Is it like a hyperboloid "laying on top" of the black hole?
If a particle approaches the back hole, is there a chance that it instead enters the worm hole and "escapes" the black hole? In this particular case the worm hole is non transversable so I guess the particle gets stuck in the middle of the wormhole but still, can it rest there instead of falling into the singularity?
I am sure the below Penrose diagram actually has all the answers I am looking for, since it is supposed to tell me the faith of particles coming in from different places, the problem is that I am not fluent in Penrose diagrams yet so I find it a bit hard to encode.

A: That isn't a Penrose diagram; a Penrose diagram shows the whole spacetime including limit points at infinity. Your diagram is probably fine for this question, though.
The wormhole is just an artifact, not of the coordinates but of ignoring the matter whose collapse made the black hole. When the Schwarzschild geometry is used as the exterior of an ordinary gravitating object, only part of the right (blue) region is used; the object itself has a different geometry. When the Schwarzschild geometry is used for a black hole, only part of the blue and green (upper) regions are used; the collapsing object (which always exists in spacetime, even if not "in space") has a different geometry. If you could somehow move faster than light and tried to enter the wormhole, you'd just hit the collapsing object.
The full Schwarzschild geometry is what you get if you analytically extend the realistic part of the geometry as though the collapsing object wasn't there. Obtaining the full Schwarzschild geometry from the Schwarzschild coordinates is technically not sensible, but you can directly verify that the result is valid solution of the GR field equation, so its provenance doesn't matter.
In the full geometry, if you head in really fast (faster than light), then instead of hitting the collapsing object, you end up in a time-reversed second half of the vacuum (time reversed only in its shape, not in the sense that anything happens backward there). I don't know how to visualize the full geometry, but the +X axis of the vacuum solution, with one angular coordinate suppressed, looks like this:

Realistically, even in a black hole, that's joined to some geometry representing the interior of the collapsing object, like this:

But if you don't add that part, and just extend the vacuum part, then because the vacuum part is a paraboloid of revolution, it ends up looking like this:

All worldlines on that surface are spacelike/tachyonic. So if (a) you could move faster than light and (b) the black hole didn't form from a collapsing object but had just existed forever, then maybe you could reach a second exterior region.


text:
Q: How to resolve CMake Error: Could not find a package configuration file provided by "boost_python3" I tried to install the lanelet2 library according to the github installation guide at https://github.com/fzi-forschungszentrum-informatik/Lanelet2.
When I perform catkin build I get the following error:
Errors     << lanelet2_python:cmake /home/student/catkin_ws/logs/lanelet2_python/build.cmake.000.log
CMake Error at /usr/lib/x86_64-linux-gnu/cmake/Boost-1.71.0/BoostConfig.cmake:117 (find_package):
  Could not find a package configuration file provided by "boost_python3"
  (requested version 1.71.0) with any of the following names:

    boost_python3Config.cmake
    boost_python3-config.cmake

  Add the installation prefix of "boost_python3" to CMAKE_PREFIX_PATH or set
  "boost_python3_DIR" to a directory containing one of the above files.  If
  "boost_python3" provides a separate development package or SDK, be sure it
  has been installed.

My OS is Ubuntu 20.04 with ROS noetic. The build is performed inside a venv with Python Version 3.8.10.
The command python is pointing to python3. I've also installed the following dependencies:
sudo apt-get install ros-noetic-rospack ros-noetic-catkin ros-noetic-mrt-cmake-modules

sudo apt-get install libboost-dev libeigen3-dev libgeographic-dev libpugixml-dev libpython3-dev libboost-python-dev python3-catkin-tools

Does someone have an idea how to resolve this error?

A: See neutrinoyu's comment at https://github.com/ethz-asl/kalibr/issues/368#issuecomment-651726289

/kalibr/Schweizer-Messer/numpy_eigen/cmake/add_python_export_library.cmake:89
change
list(APPEND BOOST_COMPONENTS python3)
to
list(APPEND BOOST_COMPONENTS python)


text:
Q: Permutations where the values $|\sigma(k)-k|$ are distinct
Find the values of $n \geq 1$ for which there exists a permutation $\sigma$ of $\left\{1, \dots, n\right\}$ such that $|\sigma(k) - k|$ are distinct for each $k = \overline{1, n}$.

My idea is to prove that the structure is possible for $n := 4k$ and $n := 4k + 1$, while not being possible for $n := 4k + 2$ and $n := 4k + 3$. For showing the impossibility part, i have defined a parameter:
$$T = \sum_{k = 1}^n |\sigma(k) - k|$$
Since $a \equiv |a| \ (\text{mod} \ 2)$, $T \equiv S \ (\text{mod} \ 2)$, where $S$ parameter is defined as:
$$S = \sum_{k = 1}^n (\sigma(k) - k) = 0$$
So, the parameter $T$ is an even number.
However, since all the absolute values of the differences are distinct, they have all the values from $0$ to $n - 1$, so:
$$T = \sum_{q = 0}^{n - 1} q = \frac{(n - 1)n}{2}$$
Which means that $n := 4k + 2$ and $n := 4k + 3$ are not viable solutions (easy to verify by plugging in the values and observing by calculation that $T$ is odd, which is obviously false.
However, I am not able to prove the example construction part. I have some examples for $n = 4 : [4 - 2 - 1 - 3]$ and for $n = 5 : [5 - 2 - 4 - 1 - 3]$, but I still can't generalize them.

A: You can find the solution in:
M. J. Pelling and J. H. Steelman, E3269. Permutations with distinct displacements, (problem by Pelling and solution by Steelman), The American Mathematical Monthly, 96 (1989), 843-844. I have found the reference at OEIS A042948.
The part that you are missing is:

Conversely, if $n \equiv 0$ or $1 \pmod 4$, one can construct a
permutation with the desired property by letting
$$\sigma(k) = \begin{cases}
n+1-k,  & \text{if $1 \le k \le \lfloor n/4 \rfloor$} \\
n-k,  & \text{if $\lfloor n/4 \rfloor \lt k \lt \lceil n/2 \rceil$} \\
1,  & \text{if $k = \lceil n/2 \rceil$} \\
n+1-k,  & \text{if $\lceil n/2 \rceil \lt k \lt \lceil 3n/4 \rceil$} \\ k,  & \text{if $k = \lceil 3n/4 \rceil$} \\
n+2-k,  & \text{if $\lceil 3n/4 \rceil \lt k \le n$} \\
\end{cases}$$


text:
Q: Angularjs - Field mandatory if condition i am using angular-messages.min.js for the validations.
I have the next web form:
<form role="form" name="form">

                Field1
                <select class="form-control" name="field1" ng-model="field1" ng-options="item for item in device" ng-change="deviceChange();"></select>

                Field2
                <select class="form-control" name="field2" ng-model="field2" ng-options="item for item in use"></select>

                Field3
                <input type="text" class="form-control" name="field3" ng-model="field3" />

Your field3 is required

</form>

The fields, field1, field2 and field3 are not mandatory, but if the field1 and field2 has content, the field3 is mandatory.
How could to show the validation message in field3? thanks,

A: This should help:
 <input type="text" class="form-control" name="field3" ng-required="field1 && field2" ng-model="field3" />


text:
Q: Proving that sum of two measurable functions is measurable. Suppose $f$ and $g$ are Lebesgue measurable, we want to show $f+g$ is measurable. So, the hint is to consider the continuous functions $F : \mathbb{R}^2 \to \mathbb{R} $ given by $h(x) = F(f ,g ) $. If we can show $F$ Is measurable, then Taking $F = f +g $ would solve our problem.
In other words, I want to show that the set $R = \{ (f,g) : F(f,g) > a $ } is lebesgue measurable.. But this set is just a rectangle in the plane. And since $F$ is continuous, then $R$ must be open, and hence a union of open rectangles which are measurable and hence $R$ must be measurable. Is this a correct approach to the problem? Can someone help me to make this formal? thanks

A: This is a method I used in my analysis class. Note that $f(x) + g(x) < t$ iff $f(x) < t-g(x)$ iff there exists a rational  number $r$ such that $f(x) < r < t-g(x)$.
Therefore $\{x : f(x) + g(x) < t\} = \bigcup_{r\in\Bbb Q} [f^{-1}((-\infty, r)) \cap g^{-1}((-\infty, t-r))]$.
Both the sets being intersected in the union are measurable sets. Hence the set on the left is also measurable, meaning that $f+g$ is measurable.