text:
Q: How to animate to position fixed? I try to animate a DIV that gets fixed after 1 second. But I can't make it done. I want after one second the div called "homepage-hero-module" to slide from right to left. As you can see in the FIDDLE it changes to fixed after one second. So How to animate this?
I tried with css, but no luck.
-webkit-transition: left 1s;
  -moz-transition: left 1s;
  -o-transition: left 1s;
  transition: left 1s;

and
-webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    transition: all 0.5s ease;

JSFIDDLE
HTML CODE:

        Container with data

CSS CODE:
    body, html {
  margin: 0px;
  padding: 0px;
  width: 100%;
  height: 100%;
}
.container-fluid {
  width: 100%;
  height: 100%;
  position: relative;
}
.homepage-hero-module {
  background: #DDD;
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0px;
  left: 0px;
}
.fixed {
    position: fixed;
    top: 0px;
    left: 0px;
    width: 20px;
    height: 100%;
    background: red;
}
img {
  height: 100%;
  width: auto;
}

JS code:
$(document).ready(function() {
    setTimeout( function(){
              $('.homepage-hero-module').addClass('fixed');
    },1000);
});

A: You need to animate the width while position is still absolute, and then set the position to fixed

        Container with data

body, html {
  margin: 0px;
  padding: 0px;
  width: 100%;
  height: 100%;
}
.container-fluid {
  width: 100%;
  height: 100%;
  position: relative;
}
.homepage-hero-module {
  background: #DDD;
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0px;
  left: 0px;
  transition:all .2s ease;
}
.fixed {
    top: 0px;
    left: 0px;
    width: 20px;
    height: 100%;
    background: red;
}
img {
  height: 100%;
  width: auto;
}

$(document).ready(function() {
setTimeout( function(){
    $('.homepage-hero-module').addClass('fixed');
},1000);
    $('.homepage-hero-module').css('position','fixed');
});

A: Already working I guess, check the below snippet and let me know your feedback. Thanks!

$(document).ready(function() {
  setTimeout(function() {
    $('.homepage-hero-module').addClass('fixed');
  }, 1000);
});
body,
html {
  margin: 0px;
  padding: 0px;
  width: 100%;
  height: 100%;
}
.container-fluid {
  width: 100%;
  height: 100%;
  position: relative;
}
.homepage-hero-module {
  background: #DDD;
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0px;
  left: 0px;
}
.fixed {
  position: fixed;
  top: 0px;
  left: 0px;
  width: 20px;
  height: 100%;
  background: red;
  -webkit-transition: all 0.5s ease;
  -moz-transition: all 0.5s ease;
  -o-transition: all 0.5s ease;
  transition: all 0.5s ease;
}
img {
  height: 100%;
  width: auto;
}

    Container with data

A: You can do it just with CSS. Check CSS3 animation.
Live demo :

body,
html {
  margin: 0px;
  padding: 0px;
  width: 100%;
  min-height: 100%;
}
.container-fluid {
  width: 100%;
  height: 100%;
  position: relative;
}
.homepage-hero-module {
  width: 100%;
  height: 100vh;
  position: absolute;
  top: 0px;
  left: 0px;
  background-color: #f5f5f5;
  animation: slideleft 1s 0.3s ease-out forwards;
}
img {
  height: 100%;
  width: auto;
}
@keyframes slideleft {
  to {
    background: coral;
    width: 70px;
    position: fixed;
  }
}

    Container with data


text:
Q: laravel view pdf file with ajax method I am implementing a post method with Ajax and I have to get a PDF output after this post process.
After post method i get certain data and print this data in PDF.
When I post with ajax, I need to output a pdf. in console it gives me output like this:

When I run these codes with ajax, there is no problem, but when I run them with ajax, I can't get the result I want.
What should I do exactly? Where am I missing?
And this is my codes
Route
Route::post('/label',[HomeController::class,'createLabel'])->name('create-label')->middleware('auth');

Controller:
$dompdf = new PDF();
$dompdf = PDF::loadView('myPDF', $data);
$customPaper = array(0, 0, 288.64, 419.53);
$dompdf->setPaper($customPaper, 'portrait');
$content = $dompdf->output();
file_put_contents('label2.pdf', $content);
$pdf = new \Clegginabox\PDFMerger\PDFMerger;
$data = base64_decode($r->labelData);
file_put_contents('label1.pdf',$data);
$pdf->addPDF('label1.pdf', 'all');
$pdf->addPDF('label2.pdf', 'all');
$pdf->merge('browser', 'LABEL'.$order->orderNumber.'.pdf', 'P');

Ajax
$.ajax({
            url:"{{route('create-label')}}",
            type:"post",
            data:{
              orderId:orderId,
              _token:'{{ csrf_token() }}'
            },
            success:function(response){
              console.log(response);
            },
            error: function(response) {
              console.log(response);
              });
            }
        });

redpajama_set_name: RedPajamaStackExchange


text:
Q: Share on FB page showing image that I didnt included in my site I am currently working on http://rightinfo.co.in
When I am trying to share this site on a FB page it is showing an image that I have not included in my site.
I have tried by adding ?v=1 to the url and url shortner services.
In facebook debugger also , the image is not showing. But in actual sharing , unknown image is showing.
Please help me to solve this
Thanks

A: It's because the og:image (see here) meta tag is set. This tag defines the image, which will be shown on facebook.
To change this image, try to edit this tag, take a look at the theme settings.
Another way is to change/delete the image itself, e.g. via FTP.
You can find it here: WEBROOT/wp-content/themes/Morpheus/img/portfolio/folio01-preview.jpg
Btw, I see you are using wordpress, I'd consider using a SEO plugin, which makes a proper use of the og-tags as explained here

A: You have issue with tags Please check this facebook debugger it explains alot Facebook debugger


text:
Q: PHP dynamic session variable to query another page I am new to PHP so I may be using the wrong method to accomplish this.  I am trying to use a session variable to store part of my query result: bugid 1, bugid 2, bugid 3 (query works great) and then use that result by clicking the bugid on page1.php to run a query using it on page2.php.
    <?php

    if(isset($results)){
        foreach($results as $r){
        $_SESSION["bugid"] = $r ['_source']['BugID']; // assigning session value
        echo print_r($_SESSION["bugid"]);

    ?>

BugID:
                <?php echo $_SESSION["bugid"]; ?>

AttachmentTitle: <?php echo $r ['_source']['AttachmentTitle']; ?>

AttachmentBody: <?php echo $r ['_source']['AttachmentBody']; ?>

    <?php
        }
    }
    ?>

Below is the query on page2.php.  The problem is that it always uses bugid 3 regardless of which bugid I click on page1.php.  I am not sure if I got my question out clear enough, but I would appreciate any help you have even if its another solution!  Thanks.
$query1 = $Client->search([
    'index' => 'defects',
    'type' => 'detail',
    'body' => [
        'query' => [
            'bool' => [
            'should' => [
                ['match' => ['BugID'           => $_SESSION["bugid"]]],
                ]
            ]
        ]
    ]
]);


text:
Q: Intuition behind $\zeta(-1)$ = $\frac{-1}{12}$ When I first watched numberphile's 1+2+3+... = $\frac{-1}{12}$ I thought the sum actually equalled $\frac{-1}{12}$ without really understanding it.
Recently I read some wolframalpha pages and watched some videos and now I understand (I think), that $\frac{-1}{12}$ is just an associative value to the sum of all natural numbers when you analytically continue the riemann-zeta function. 3Blue1Brown's video really helped. What I don't really understand is why it gives the value $\frac{-1}{12}$ specifically. The value $\frac{-1}{12}$ seems arbitrary to me and I don't see any connection to the sum of all natural numbers. Is there any intuition behind why you get $\frac{-1}{12}$ when analytically continue the zeta function at $\zeta(-1)$?
EDIT(just to make my question a little clearer):
I'll use an example here. Suppose you somehow didn't know about radians and never associated trig functions like sine to $\pi$ but you knew about maclaurin expansion. By plugging in x=$\pi$ to the series expansion of sine, you would get sine($\pi$) = 0. You might have understood the process in which you get the value 0, the maclaurin expansion, but you wouldn't really know the intuition behind this connection between $\pi$ and trig functions, namely the unit circle, which is essential in almost every branch of number theory.
Back to this question, I understand the analytic continuation of the zeta function and its continued form for $s < 0$ $$\zeta(s)=2^s\pi^{s-1}\sin\frac{\pi s}2\Gamma(1-s)\zeta(1-s)$$ and how when you plug in s = -1, things simplify down to $\frac{-1}{12}$ but I don't see any connection between the fraction and the infinite sum. I'm sure there is a beautiful connection between them, like the one between trig functions and $\pi$, but couldn't find any useful resources on the internet. Hope this clarified things.

A: We have the functional equation for $\;\zeta\;$ :
$$\zeta(s)=2^s\pi^{s-1}\sin\frac{\pi s}2\Gamma(1-s)\zeta(1-s)$$
which allows to extend the usual definition of the zeta function as infinite series to $\;\text{Re}\,s<1\;$, and then:
$$\zeta(-1)=\frac1{2\pi^2}\cdot(-1)\cdot1\cdot\frac{\pi^2}6=-\frac1{12}$$

A: The following is taken from this answer.
Using the Dirichlet Eta function and integration by parts twice, we get
$$
\begin{align}
(1-2^{1-z})\zeta(z)\Gamma(z)
&=\eta(z)\Gamma(z)\\
&=\int_0^\infty\frac{x^{z-1}}{e^x+1}\,\mathrm{d}x\\
&=\frac1z\int_0^\infty\frac{x^ze^x}{\left(e^x+1\right)^2}\,\mathrm{d}x\\
&=\frac1{z(z+1)}\int_0^\infty\frac{x^{z+1}\left(e^{2x}-e^x\right)}{\left(e^x+1\right)^3}\,\mathrm{d}x\\
\end{align}
$$
Multiply by $z(x+1)$ to get
$$
(1-2^{1-z})\zeta(z)\Gamma(z+2)=\int_0^\infty\frac{x^{z+1}\left(e^{2x}-e^x\right)}{\left(e^x+1\right)^3}\,\mathrm{d}x
$$
Plugging in $z=-1$, gives a pretty simple integral.
$$
\begin{align}
(1-2^2)\zeta(-1)\Gamma(1)
&=\int_0^\infty\frac{e^{2x}-e^x}{(e^x+1)^3}\mathrm{d}x\\
&=\int_1^\infty\frac{u-1}{(u+1)^3}\mathrm{d}u\\
&=\int_1^\infty\left(\frac1{(u+1)^2}-\frac2{(u+1)^3}\right)\mathrm{d}u\\
&=\frac14
\end{align}
$$
This gives
$$
\bbox[5px,border:2px solid #C0A000]{\zeta(-1)=-\frac1{12}}
$$

The relation between $\boldsymbol{\zeta(z)}$ and $\boldsymbol{\eta(z)}$
An alternating sum can be viewed as the sum of the non-alternating terms minus twice the sum of the even terms.
$$
\begin{align}
\eta(z)
&=\sum_{n=1}^\infty\frac{(-1)^{n-1}}{n^z}\\
&=\sum_{n=1}^\infty\frac1{n^z}-2\sum_{n=1}^\infty\frac1{(2n)^z}\\
&=\left(1-2^{1-z}\right)\sum_{n=1}^\infty\frac1{n^z}\\[6pt]
&=\left(1-2^{1-z}\right)\zeta(z)
\end{align}
$$

The integral for $\boldsymbol{\eta(z)\Gamma(z)}$
$$
\begin{align}
\int_0^\infty\frac{x^{z-1}}{e^x+1}\,\mathrm{d}x
&=\int_0^\infty x^{z-1}\sum_{k=1}^\infty(-1)^{k-1}e^{-kx}\,\mathrm{d}x\\
&=\sum_{k=1}^\infty\frac{(-1)^{k-1}}{k^z}\int_0^\infty x^{z-1}e^{-x}\,\mathrm{d}x\\[6pt]
&=\eta(z)\Gamma(z)
\end{align}
$$

A: In equation $(10)$ of this answer, it is shown, using the Euler-Maclaurin Sum Formula, that the analytic continuation of the zeta function for $\newcommand{\Re}{\operatorname{Re}}\Re(z)\gt-3$ is given by
$$
\zeta(z)=\lim_{n\to\infty}\left[\sum_{k=1}^n{k^{-z}}-\frac1{1-z}n^{1-z}-\frac12n^{-z}+\frac{z}{12}n^{-1-z}\right]\tag{1}
$$
Note that for $\Re(z)\gt1$, the terms beyond the sum vanish and we are left with the well-known definition of $\zeta(z)$:
$$
\zeta(z)=\sum_{n=1}^\infty n^{-z}\tag{2}
$$

For $z=-1$, $(1)$ becomes
  $$
\begin{align}
\zeta(-1)
&=\lim_{n\to\infty}\left[\sum_{k=1}^nk-\frac12n^2-\frac12n-\frac1{12}\right]\\
&=\lim_{n\to\infty}\left[\frac{n^2+n}2-\frac12n^2-\frac12n-\frac1{12}\right]\\[3pt]
&=-\frac1{12}\tag{3}
\end{align}
$$

Furthermore, for $z=0$, $(1)$ becomes
$$
\begin{align}
\zeta(0)
&=\lim_{n\to\infty}\left[\sum_{k=1}^n1-n-\frac12+\frac0{12n}\right]\\
&=\lim_{n\to\infty}\left[n-n-\frac12+\frac0{12n}\right]\\[3pt]
&=-\frac12\tag{4}
\end{align}
$$
and for $z=-2$, $(1)$ becomes
$$
\begin{align}
\zeta(-2)
&=\lim_{n\to\infty}\left[\sum_{k=1}^nk^2-\frac13n^3-\frac12n^2-\frac16n\right]\\
&=\lim_{n\to\infty}\left[\frac{2n^3+3n^2+n}6-\frac13n^3-\frac12n^2-\frac16n\right]\\[9pt]
&=0\tag{5}
\end{align}
$$

A: An Elementary Non-Proof
Note that $\dfrac{1}{(1-z)^2}=\sum\limits_{k=0}^\infty\,(k+1)\,z^{k}$ leads to $$\beta = 1-2+3-4+\ldots=\frac{1}{\big(1-(-1)\big)^2}=\frac{1}{4}\,.$$
Hence, if $\alpha =1+2+3+\ldots$, then $$\alpha-\beta =4+8+12+\ldots=4\,(1+2+3+\ldots)=4\,\alpha \,.$$
Thus, $$\zeta(-1)=\alpha=-\frac{\beta}{3}=-\frac{1}{12}\,.$$
Hope it helps.

A: $$1+1+1+\dots+1=n$$
$$\int_{-1}^0x\ dx=-\frac12$$

$$1+2+3+\dots+n=\frac{n(n+1)}2$$
$$\int_{-1}^0\frac{x(x+1)}2\ dx=-\frac1{12}$$

$$1^2+2^2+3^2+\dots+n^2=\frac{n(n+1)(2n+1)}6$$
$$\int_{-1}^0\frac{x(x+1)(2x+1)}6\ dx=0$$

Integrating the formula for the sum of all natural numbers

A: There is a really nice answer by master Terence Tao on his blog.
The Euler-Maclaurin formula, Bernoulli numbers, The zeta function and real variable analytic continuation/
It shows that smoothed sums $\eta$ for $\sum\limits_{n\le N}n^s\,\eta(n/N)$ have a divergent part in $N^{s+1}$ and a convergent part $-\frac{B_{s+1}}{s+1}$.
The second part of the paper shows how it is related to analytics continuation in the complex plane.

A: The values of $\zeta$ for negative integers can be directly calculated from the Bernoulli numbers, from:
$$\zeta(-n)=(-1)^n\frac {B_{n+1}}{n+1}$$
and $B_2=\dfrac 16$.


text:
Q: How does a scalar potential $V$ that follows $\rho$ momentarily lead to infinite propagation velocity? $$\nabla^2V(\mathbf r,t)=-\frac{\rho(\mathbf r,t)}{\epsilon_0}\implies V(\mathbf r,t)=\frac1{4\pi\epsilon_0}\int\frac{\rho(\mathbf r',t)}R\mathrm d\tau'$$
I am trying to  understand how this equation $\implies\infty$ propagation velocity. During lecture it was a heavy proof that I didn't understand, so maybe someone could explain the basic idea how to interprete this equation.

A: I don't quite understand the equation as-written - ordinarily, I would expect to see
$$V(\mathbf r, t) = \frac{1}{4\pi \epsilon_0}\int\frac{\rho(\mathbf r',t)}{|\mathbf r - \mathbf r'|}\mathrm d^3 r'$$
In any case, the reason for this is straightforward.  If $\rho(\mathbf r',t)$ suddenly changes at $t=0$, then $V(\mathbf r,t)$ changes suddenly at $t=0$. For example, imagine two point charges sitting on top of each other at the origin, so the charge density vanishes everywhere.  Suddenly at time $t=0$ the two charges move an infinitesimal distance $\epsilon$ apart, creating a dipole with moment $\mathbf p = q\epsilon \hat z$.  If you compute $ V(\mathbf r, t)$ for any $t>0$, you will clearly obtain the dipole potential
$$V(\mathbf r,t) = \frac{1}{4\pi \epsilon_0}\left( \frac{q}{|\mathbf r - \epsilon \hat z/2|} - \frac{q}{|\mathbf r+\epsilon \hat z/2|}\right)\simeq \frac{\mathbf r \cdot \mathbf p}{4\pi\epsilon_0 r^3}$$
In this sense, the time variable is just a spectator; it doesn't play an active role in the integral. Any change that occurs in $\rho$ is immediately reflected in a change in $V$ at every point in space.
On the other hand, if we utilize the Lorenz gauge then we find that
$$V(\mathbf r,t) = \frac{1}{4\pi\epsilon_0}\int \frac{\rho(\mathbf r', t')}{|\mathbf r- \mathbf r'|} \mathrm d^3r' \qquad t' \equiv t - |\mathbf r-\mathbf r'|/c$$
This is a different story because the $\rho$ inside the integral is evaluated at $t'$ rather than at $t$.  The contribution to $V$ from a point $\mathbf r'$ depends on the charge density at $\mathbf r'$ at a time $\delta t =|\mathbf r-\mathbf r'|/c$ in the past. Changing the charge density at a point $\mathbf r'$ does not change the potential at some point $\mathbf r$ until the time $|\mathbf r-\mathbf r'|/c$ has elapsed, which means that changes in $V$ propagate at $c$.

As pointed out by Michael Seifert in the comments, there is no causality violation in the Coulomb gauge even though changes in $V$ apparently propagate infinitely quickly. The reason for this is that neither $V$ nor the vector potential $\mathbf A$ are physically observable; only the electric and magnetic fields are, and $\mathbf E$ depends on both $V$ and $\mathbf A$ as
$$\mathbf E = -\nabla V - \frac{\partial}{\partial t} \mathbf A$$
It is an excellent exercise to show that the apparently acausal propagation of changes in $\nabla V$ is exactly canceled out by a corresponding term in $\partial \mathbf A/\partial t$, with the result being that changes in $\mathbf E$ propagate at $c$.
Of course, this is also clear because causality is manifestly preserved in the Lorenz gauge, and $\mathbf E$ and $\mathbf B$ are invariant under gauge transformation.


text:
Q: ConnectApi.ConnectApiException: Mentioned group does not exist I have a chatter feed publisher component at 2 places(topics page and article page) in a community and whenever user posts something, I'm writing a trigger code on FeedItem object to auto at mention a public chatter group(topic discussions). For example, if I post 'test' , trigger automatically appends @topic doscussions to the test and updates the feed item post. It's working as expected from article page but from topic page , I'm getting the error

ConnectApi.ConnectApiException: Mentioned group does not exist

It's really odd because its the same code that was working for one feeditem record but not for the other. Any insights into this would help!
String communityId = '0DB5O0000000***';

// Get the last feed item created by the context user.
List<FeedItem> feedItems = [SELECT Id FROM FeedItem WHERE id = '0D55O000000XTai***'];//feed item posted on topic : erroring out
//List<FeedItem> feedItems = [SELECT Id FROM FeedItem WHERE id = '0D55O000000XVF9***'];//feed item posted on article : working fine

String feedElementId = feedItems[0].id;

    ConnectApi.FeedItemInput feedItemInput = new ConnectApi.FeedItemInput();
    ConnectApi.MessageBodyInput messageBodyInput = new ConnectApi.MessageBodyInput();
    ConnectApi.TextSegmentInput textSegmentInput = new ConnectApi.TextSegmentInput();
    ConnectApi.MentionSegmentInput mentionSegmentInput = new ConnectApi.MentionSegmentInput();
    messageBodyInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();
    mentionSegmentInput.id = '0F95O0000000I7bSAE'; // topic discussion : public group

    textSegmentInput.text = 'This is my edited post1.';
    messageBodyInput.messageSegments.add(textSegmentInput);
    messageBodyInput.messageSegments.add(mentionSegmentInput);
    feedItemInput.body = messageBodyInput;

    ConnectApi.FeedElement editedFeedElement = ConnectApi.ChatterFeeds.updateFeedElement(communityId, feedElementId, feedItemInput);

A: I figured it out. if in case anyone face the issue- create the groups inside the community to be able to mention them from a community. More details here https://success.salesforce.com/answers?id=90630000000Zj8TAAS


text:
Q: Уникальный идентификатор компьютера есть приложение на Python и есть сервер, там уже всё на php.
Суть в том, что нужно как-то идентифицировать пользователя на сайте и в приложении, а потом всё это связать.
Человек скачивает на сайте, в бд заносится IP и дата
Пользователь устанавливает приложение и запускает его. При первом запуске отправляется запрос на сайт с IP адресом, полученным уже средствами Python, там идёт поиск по бд и если есть совпадение, то всё хорошо.
Но тут же есть и проблемы, человек может скачать приложение сегодня, а установить его через пару дней, что практически 100% означает то, что IP сменится.
Из чего сразу вытекает вопрос: Как идентифицировать человека в двух разных языках?
Была идея идентифицировать по материнской плате, но тут уже вопрос в том, а будет ли это идентификация? Как часто встречаются одинаковые платы?
В общем, идеи есть, но насколько они правильные - не знаю.

A: Вариант №1:
import subprocess
current_machine_id = subprocess.check_output('wmic csproduct get uuid').decode().split('\n')[1].strip()
print(current_machine_id)

Это просто, но только для OS Windows
Вариант №2:
Создайте уникальный идентификатор не по определенному оборудованию, а по определенному алгоритму из совокупности железа пользователя, например:
mainboard + GPU + SSD

В этом случае совпадения и ошибки идентификации будут минимальны. Пример по SSD:
https://stackoverflow.com/questions/4193514/how-to-get-hard-disk-serial-number-using-python


text:
Q: get the Full name of the authenticated user Goal
I have a WCF Service using Windows Authentication. I want to determine the Full name of the user that connected. The user can either be a domain or a local user. For local users, you can view the Full name in [Computer Management (local) > Local Users and Groups > Users > [user] > Full Name].
Almost successful with FindByIdentity
I can use UserPrincipal.FindByIdentity() to retrieve a UserPrincipal object, and then get it from UserPrincipal.DisplayName. The first parameter of FindByIdentity requires specifying ContextType, such as Domain or Machine.

*

*Calling FindByIdentity with ContextType.Domain and a local user, produces a "Specified Domain Does Not Exist or Could Not Be Contacted" exception

*Calling FindByIdentity with ContextType.Machine and a domain user, produces a UserPrincipal without a filled DisplayName property

So i would like to avoid guessing.
Question

*

*How can i get the Full name of the connected user?

*Or how can i distinguish whether the connected user is a domain user or a local user?

Code so far
string GetFullName()
{
    using (var ctx = new PrincipalContext(ContextType.Domain))
    {
        string userName = OperationContext.Current.ServiceSecurityContext.WindowsIdentity.Name;
        UserPrincipal u = UserPrincipal.FindByIdentity(ctx, userName);
        return u.DisplayName;
    }
}

A: You can use the Environment.UserDomainName property to get the domain name of the current user. If the domain is not joined, the host name of the current user will be returned.

A: I'm using the following for now. If anyone has any better ideas, then please post your answer
bool LocalUserConnected()
{
    string userName = OperationContext.Current.ServiceSecurityContext.WindowsIdentity.Name;
    return userName.StartsWith(Environment.MachineName + @"\");
}


text:
Q: Solve limit using Stolz's theorem: $\lim_{n\to\infty} \frac{n}{\sqrt[n]{n!}}$ Solve this limit usinig Stolz's theorem. Any help?!
$$\lim\limits_{n\rightarrow \infty} \frac{n}{\sqrt[n]{n!}}$$

A: This provides another way.
Let $a_{n} > 0$ for all $n \geq 1$. Then it can be shown that
$$\liminf a_{n+1}/a_{n} \leq \liminf (a_{n})^{1/n} \leq \limsup (a_{n})^{1/n} \leq \limsup a_{n+1}/a_{n}.$$
Thus if there is some $l \in \mathbb{R}$ such that $a_{n+1}/a_{n} \to l$ then $(a_{n})^{1/n} \to l$.
Let $a_{n} := n^{n}/n!$ for all $n \geq 1$. Then $(a_{n})^{1/n} = (n^{n}/n!)^{1/n}$ for all $n \geq 1$. But,
since
$$
\frac{a_{n+1}}{a_{n}} = \frac{(n+1)^{n+1}}{(n+1)!}\cdot \frac{n!}{n^{n}} = (1+\frac{1}{n})^{n} \to e
$$
as $n$ grows,
we have
$(a_{n})^{1/n} \to e$ as $n$ grows.


text:
Q: TPS560200 - Output voltage wrong One of the students at my uni has laid out a PCB with a TPS560200 step-down converter. However, instead of 5V it only outputs 0.9V. I've checked the feedback resistors and they are correct*. The problem happens on multiple boards.
My initial guess was that the layout is wrong. Suggested layout is:

And this is what was produced:

My guess is that the output inductor is too far away. Would this be the likely cause? What else should I suggest to change or troubleshoot?
Update*
It turns out the feedback resistors were all swapped.


text:
Q: Calling executeBatch() method of two Batchable classes in execute method of a Schedule class I was just wondering is it possible to class executeBatch method of two different Batchable classes inside the execute method of a Schedule class. For example;
global class BatchClassA implements Database.Batchable<sObject>
{
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        //query goes here;
    }

    global void execute(Database.BatchableContext BC, List<Child__c> scope)
    {
        //execution goes here
    }
    global void finish(Database.BatchableContext BC)
    {
    }
}

global class BatchClassB implements Database.Batchable<sObject>
{
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        //query goes here;
    }

    global void execute(Database.BatchableContext BC, List<Child__c> scope)
    {
        //execution goes here
    }
    global void finish(Database.BatchableContext BC)
    {
    }
}

global class Scheduler_class implements Schedulable{

    global void execute(SchedulableContext sc) {

        BatchClassA b1 = new BatchClassA();
        ID batchprocessidA = Database.executeBatch(b1,50);

        BatchClassB b1 = new BatchClassB();
        ID batchprocessidA = Database.executeBatch(b1,50);
    }

}

Will this actually work?

A: global class Scheduler_class implements Schedulable{

    global void execute(SchedulableContext sc) {

        BatchClassA b1 = new BatchClassA();
        ID batchprocessidA = Database.executeBatch(b1,50);

        BatchClassB b2 = new BatchClassB();
        ID batchprocessidA = Database.executeBatch(b2,50);
    }
}

It will work without any issue. But make sure that you are not going to hit maximum batch execution queue/run limit, it is 5.


text:
Q: I'm screwing up this LEFT JOIN I'm doing a left join on several tables. What I want to happen is that it list all the businesses. Then, it looks through the photos, videos, specials and categories. IF there are photos, then the tables shows yes, if there are videos, it shows yes in the table.
It does all that without any problems. Except for one thing. For every photo, it shows the business that many times. For example, if there are 5 photos in the DB for a business, it shows the business five times.
Obviously, this is not what I want to happen. Can you help?
function frontPageList() {
    $this->db->select('b.id, b.busname, b.busowner, b.webaddress, p.thumb, v.title, c.catname');
    $this->db->from ('business AS b');
    $this->db->where('b.featured', '1');
    $this->db->join('photos AS p', 'p.busid = b.id', 'left');
    $this->db->join('video AS v', 'v.busid = b.id', 'left');
    $this->db->join('specials AS s', 's.busid = b.id', 'left');
    $this->db->join('category As c', 'b.category = c.id', 'left');
    return $this->db->get();

A: if you don't care about the photos themselves, or which one it grabs, you can try adding a on GROUP BY b.id

A: A join will multiply the number of rows if there is more than one match. If this is not what you want then you should either start with getting a count and then query each table individually for the actual rows, or you should do grouping in code based on when the business values change.


text:
Q: Proof verification: The Cohen algebra of Borel modulo meagre sets is complete. I asked this a while back and got no replies. I think I have a proof now but I'm a bit suspicious of how easy it is (or perhaps I was overthinking it from the start). In any case, I would appreciate some verification.
Let $\mathbb{B}$ be the Borel algebra of borel mod meagre sets in $\omega^\omega$ (i.e, $A \sim B$ if $A \Delta B$ is meagre where $A, B$ are Borel). I want to show this is complete, i.e, every subset $A \subseteq \mathbb{B}$ has a unique upper bound $\sum A$. Let $[B] \in \mathbb{B}$ denote the equivalence class of the Borel set $B$ with respect to the equiv relation above.
First, $\mathbb{B}$ has a countable dense set: $\{ [N_s] : s \in \omega^{<\omega}\}$. From this one can conclude that $\mathbb{B}$ has the ccc- this follows from countable dense subset fairly easily.
Now suppose $[B_\alpha]_{\alpha < \mu}$ be a sequence in $\mathbb{B}$. To show completeness we show that $\sum [B_\alpha]$ exists.
If $\mu \leq \omega_1$, let $A_\alpha = B_\alpha\setminus \cup_{\beta < \alpha} B_\beta$ be the disjointifications. Then by ccc there must be some $\gamma < \omega_1$ such that $[A_\alpha] = [\emptyset]$ for all $\alpha > \gamma$ (since the $[A_\alpha]$ form an antichain). Then simply see that $\sum_{\alpha < \mu}[B_\alpha] = \sum_{\alpha < \mu}[A_\alpha] = \sum_{\alpha < \gamma}[A_\alpha]$ and the last one exists due to ccc.
Next inductively assume we have this for all cardinals below $\mu$. And given $\{[B_\alpha]\}_{\alpha < \mu}$, by inductive hypothesis $[A_\alpha]  = \sum_{\beta < \alpha}[B_\alpha]$ exists for all $\alpha < \mu$. Then I think I can just define $[C_\alpha] = [B_\alpha] - [A_\alpha]$.
Notice that here if $\alpha < \beta$ and $[A_\alpha] < [A_\beta]$ (i.e, $[A_\alpha] \neq [A_\beta]$). Then we would have that $[C_\alpha] \perp [C_\beta] $ as well. In order to keep $\{[C_\alpha] : \alpha < \mu\}$ from being an uncountable antichain then we must then have that the $[A_\alpha]$ only take on countably many different values. This means that $\sum_{\alpha < \mu}[A_\alpha]$ exists and $\sum_{\alpha < \mu} [B_\alpha] = \sum_{\alpha < \mu}[A_\alpha]$.
Does this seem correct? I was pretty cavalier about using ccc and when antichains are formed so I wanted some confirmation. Hopefully I am not making this out to be far tougher than it is.


text:
Q: Rdrobust installation does not work in Stata 13 I tried to install RDrobust with the following command:
net install rdrobust, from(https://sites.google.com/site/rdpackages/rdrobust/stata) replace

I am given an error which recommends checking another website but the instructions are unclear. I know that it properly installs in Stata 14 but I only have access to Stata 13. Would one of the following solutions work to use the rdrobust package in Stata 13?
(1) Manually install the packages in Stata 13 from the files here?
(2) I read that this package had a major upgrade in 2016. Maybe it it possible to find the old link to upload the old package? Does someone know this?
I am using this for a class where the students only have access to a Stata 13 license.
Many thanks!

A: In Stata 15.1 the following is shown by search rdrobust
Search of official help files, FAQs, Examples, SJs, and STBs

SJ-17-2 st0366_1  . .  rdrobust: Software for regression-discontinuity designs
        . . . . .  S. Calonico, M. D. Cattaneo, M. H. Farrell, and R. Titiunik
        (help rdrobust, rdbwselect, rdplot if installed)
        Q2/17   SJ 17(2):372--404
        describes a major upgrade to the Stata (and R) rdrobust package,
        which provides a wide array of estimation, inference, and
        falsification methods for the analysis and interpretation of
        regression-discontinuity designs

SJ-14-4 st0366  . .  Robust data-driven inference in reg.-discontinuity design
        . . . . . . . . . . . . . S. Calonico, M. D. Cattaneo, and R. Titiunik
        (help rdrobust, rdbwselect, rdplot if installed)
        Q4/14   SJ 14(4):909--946
        conducts robust data-driven statistical inference in
        regression-discontinuity designs

That's how to find the files. In Stata 13, you may need
search rdrobust, all

Then follow the latest link st0366_1 to install.
Trying to install from elsewhere is all too likely to lead to partial installs and/or installs in the wrong places, unless a user has a sound understanding of packages and adopath.
I have not checked on whether rdrobust will run in Stata 13.

A: rdrobust works on Stata 13.1 or higher, due to some new functions they added in Mata.


text:
Q: Getting post created by an user I want to display all posts created from an user.the problem is that i dont know what to write in kwargs as i do use slug to display user urls.
models
class Post(models.Model):
body_text=models.TextField()
title=models.CharField(max_length=50)
created_on=models.DateField(auto_now_add=True)
slug=models.SlugField(max_length=50,unique=True)
author=models.ForeignKey(
    get_user_model(),
    on_delete=models.CASCADE,
)

def __str__(self):
    return self.title

def get_absolute_url(self):
    return reverse('post_detail', kwargs={'slug': self.slug})

def save(self, *args, **kwargs):
    self.slug = slugify(self.title, allow_unicode=True)
    return super(Post, self).save(*args, **kwargs)

views.py
class ProfilPostView(ListView):
model=Post
template_name='profile.html'

def get_queryset(self):
     return Post.objects.filter(author=self.kwargs['']).order_by('created_on')
    #return Post.objects.filter(author=self.request.user).order_by('created_on')

urls.py
 path('post/<slug:slug>/profile', ProfilPostView.as_view(), name='profile'),

A: Try
return Post.objects.filter(author_id=int(self.kwargs['slug'])).order_by('created_on')

If the slug is the user id then that should work.
If the slug is instead the name of the author then you can use the username slug provided by the url conf but you need to compare it to Author names in the database. Depending on the Author model you could use something like:
return Post.objects.filter(author__name=self.kwargs['slug']).order_by('created_on')


text:
Q: Implementing Comparable with a generic doubly linked list I'm writing a doubly linked list that as objects extended from my class "Furniture" are added, sorts them using a compareTo method.
My list and node codes:
class Node<E extends Comparable<E>> { ....... }

class DList<E extends Comparable<E>>
{

[..]

    public void add(E c)
    {
        Node<E> finger = head;
        while (finger != null && ((finger.value().compareTo(c)) > 0))
            finger = finger.Next();

    }
}

My compareTo method(s) are located in subclasses of my Furniture class, for example:
class Chair extends Furniture
{

[.....]

    public int compareTo(Chair c)
    {
    if(this.getStyle().equals(c.getStyle()))
        return this.getColor().compareToIgnoreCase(c.getColor());
    return this.getStyle().compareToIgnoreCase(c.getStyle());
    }

}

I then try to make my list by
    DList<Furniture> DD = new DList<Furniture>();

and I receive the error: Type argument furniture is not within type variable E

A: Make sure that Furniture implements Comparable<Furniture>

A: Maybe your Forniture class does not implement Comparable<Forniture>.

A: Your Furniture class should be abstract and should extend Comparable, your Chair class should implement your Furniture class.
An alternative is to make your Furniture class implement Comparable.

A: <E extends Comparable<E>> means E must be extending Comparable<E>, so make sure that Furniture extends Comparable.


text:
Q: How gcc linker works in including files This is really a newbie question. I'm learning C, and I don't understand how to link together
different files.
I have a header like
/* file2.h */

int increment(int x);

and a C file
/* file2.c */

#include "file2.h"

int increment(int x)
{
    return x+1;
}

Now I want to include the header in file1.c in order to use the function increment.
From what I have understood I have to do something like:
/* file1.c*/

#include "file2.h"

int main()
{
    int y = increment(1);
    return 0;
}

But when I try to compile the whole thing, using
gcc -o program file1.c

I get an error message like
/tmp/ccDdiWyO.o: In function `main':
file1.c:(.text+0xe): undefined reference to `increment'
collect2: ld returned 1 exit status

However if I include also file2.c
/* file1.c*/

#include "file2.h"
#include "file2.c"  /* <--- here it is! */

int main()
{
    int y = increment(1);
    return 0;
}

Everything works as expected.
But if I have understood only the header file (with only declarations in it) has to be included. So how can I inform gcc that the definition of function increment declared in file2.h is in file2.c?

A: The easiest way is to compile them both directly:
$ gcc -o program file1.c file2.c

But for more complicated systems you might want to do it in steps.  Here's a simple command line recipe:
$ gcc -c file1.c
$ gcc -c file2.c
$ gcc -o program file1.o file2.o

Even better for something complicated like this would be to use make, though.
Aside from your specific problem, why are you using GCC?  You could use clang and get better error messages, faster compiling, and feel like you're living in the future!

A: gcc -o program file2.c file1.c
this will compile file1.c and file2.c and link them together.


text:
Q: How to read mat file and store in a variable I have two .mat files. And I want to read these data of two mat files and store in variables A and B. This is my code, but I think it is not good. Can you help me store it without using matArray in matlab? (Varibale matArray is born when you call load function)
    load input1.mat;
    A=matArray;
    load input2.mat;
    B=matArray

Thank you so much

A: You had it right. The variable name that you have when you save the file is the name that will appear in the workspace when you load the file again.  Best you can do:
load('input1.mat');
A=matArray;
load('input2.mat');
B=matArray;
clear matArray

At least you'll get the space back at the end. There is, to my knowledge, no "rename" function in Matlab...
Of course if you know what you want to name the variable when you read it in, you should save it as such:
A = matArray;
save('input1.mat', 'A');

etc

A: Use an output argument with the load function.
A = load('input1.mat');
B = load('input2.mat');

The two arrays will now be fields of the structures A and B:
size(A.matArray);
plot(B.matArray);

If you choose to copy these into simpler variables, or stick with your current copying approach, you should know that the copy operation is extremely efficient.  When you do A = matArray; A shares the data of matArray until one of them is modified.  Therefore, if you delete matArray before modifying A, no extra memory is consumed by the copy.


text:
Q: Which Kubernetes client-go methods are safe for concurrent calls? The Kubernetes client-go package includes a nice example of creating a single deployment using the client-go api.
I want to create and destroy many kubernetes resources without waiting for each http request to complete.
Is it possible to use the client-go api asynchronously?
Are methods like the ones below safe for concurrent calls from multiple goroutines?
resultPod, err := clientset.CoreV1().Pods("default").Create(desiredPod)

A: The k8s client uses http.Client internally which is safe to call concurrently. But it is probably wise to limit the number of concurrent API calls to a reasonable upper limit (I'd start with 4; anything above that is probably not going to improve performance much).


text:
Q: Reveal animation starts before view is clipped to outline I am using a FAB button from the Android Samples(1).
If I understand it correctyl, the constuctor of the extended FrameLayout implementing the FAB clipps the outline to the view making it oval wheneever the view is instantiated.
 public FloatingActionButton(Context context, AttributeSet attrs, int defStyleAttr,
                            int defStyleRes) {
    super(context, attrs, defStyleAttr);

    setClickable(true);

    // Set the outline provider for this view. The provider is given the outline which it can
    // then modify as needed. In this case we set the outline to be an oval fitting the height
    // and width.
    setOutlineProvider(new ViewOutlineProvider() {
        @Override
        public void getOutline(View view, Outline outline) {
            outline.setOval(0, 0, getWidth(), getHeight());
        }
    });

    // Finally, enable clipping to the outline, using the provider we set above
    setClipToOutline(true);
}

I want ot reveal the button wheneever the activity is started:
I apply the reveal effect on it in the onWindowFocusChanged activity method and what happens is that the animation starts and only after it finishs the outline of the view is clipped.
final View fabContainer = findViewById(R.id.create_new_workout_fab);

                Animation anim = AnimationUtils.loadAnimation(YourWorkouts.this, R.anim.reveal_fab);
                fabContainer.setVisibility(View.VISIBLE);

                Animator animator = ViewAnimationUtils.createCircularReveal(
                        fabContainer, // view to reveal
                        fabContainer.getWidth()/2, // start X coordinate of reveal
                        fabContainer.getHeight()/2, // start Y coordinate of reveal
                        0, // start radius. In most cases - 0
                        Math.max(fabContainer.getWidth(), fabContainer.getHeight()) // end radius
                );

                // Set a natural ease-in/ease-out interpolator.
                animator.setInterpolator(new AccelerateDecelerateInterpolator());
                fabContainer.setClipToOutline(true);
                // Finally start the animation
                animator.start();

So while the reveal animation runs the view is not oval and becomes oval after the reveal animation ends.
As seen in the code I also tried to set the clipping manually before starting the animation, but it wouldnt help.
Can anybody help me out?

A: I regret you can't do both things at the same time:

Only a single non-rectangular clip can be applied on a View at any time. Views clipped by a circular reveal animation take priority over View Outline clipping.

https://developer.android.com/reference/android/view/ViewAnimationUtils.html
I'd try to fake it by adding a shape background drawable.


text:
Q: switch on a long wire end causing microcontroller to shutdown i've a push button connected to micro-controller using a 100m 18ga wire that cause the micro-controller to shutdown after few times of working properly
the circuit is fully functional with a short wire, i use 5v, both CN2/3 has lamp/bell load and sw1 wire is the 100m wire

A: At 100 meters of 18awg cable, i think it the wire starts to have enough inductance to have the system start experiencing inductive kick backs when the switch opens up. A small capacitor across the SW1 can be an effective snubber. Also add some decoupling capacitors across V+ and V- of your MCU.

A: Add some series resistors to the PIC inputs (pins 4 and 5)- something like 10K is fine.
And do as @Andrew says and make sure you have adequate bypass capacitors on the chip (something like 0.1uF ceramic in parallel with 10uF electrolytic is good- the 0.1uF close to the micro - within 5-10mm).
I doubt putting anything across the switch will make any positive improvement.


text:
Q: Contour vs elevation semantics I accept I am being a pedant here, but feel the semantics are important..
If I were to drawn a path representing a 'route' between 3 random points on the earth's surface, then establish the nearest elevation points, say every 20m along that path, would you consider that set of triples to be the:

*

*The 'Route Elevation'

*The 'Route Contour'

*Something else

The definition seems to be used interchangeably, and I'm not sure which one is (more) correct.
The definition of 'Contour' - as I understand it, has a specific meaning of equivalence ie. the line is of constant value along its length, which a path containing various elevations wouldn't be.
Yet the definition of 'Elevation' is a height above a specific datum point, rather than a collection of triples describing it.
The reason this data is an array of triples not just an array of elevation values is the route can be explicitly declared as a pair of lat/longs, however my elevation data may not fall exactly along that path, and so will be an array of triples separate from the route data.

A: I would call it a "route profile".
An elevation reading at a particular point will always be an estimate based on available data.  It could be worth stating explicitly how you are making that estimate, either by interpolation or in your case taking the nearest known elevation.


text:
Q: Does accessing values in a foreach loop by reference work with custom Iterators, too? If I write a class implementing Iterator, does this feature of foreach still work?

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

Perhaps more to the point, do I have to put '&' in my Iterator's declaration of current()?

A: You can't. On PHP 5.3.2, I get

Fatal error: An iterator cannot be used with foreach by reference in [file] on line [N]


text:
Q: Why am I getting 4.5 VDC output?
With this simple op-amp circuit R1 = 3.6k ohms and R2 = 4.7k ohms. With my input at zero (grounded) I am getting an output of 4.5 VDC.  I am trying to get a near zero output with 0 VDC input. Do I need to run the 741 on a split supply ? Should I choose a different opamp?                  The gain should be about 2.3.  With a 5 VDC input the output is near 12VDC as planned.  Can anyone tell me why I am getting 4.5 VDC output with a 0 VDC input?

A: You need a negative power rail if you expects inputs and outputs to get anywhere near zero volts.
The 741 opamp is not a "rail to rail" device: -

A: You are misusing your op amp. A 741 is not designed to operate with either input or output near the power supply voltages. For that you need what is called a rail-to-rail op amp.
The "simplest" fix is to provide another 12 volt supply, and connect -12 volts to pin 4, with the two supplies tied together at ground.

A: The 741 doesn't can't handle input voltage close to either power rail and can't drive the output close to either rail. Apparently when you tie the input to the negative rail it shuts off.
Two options:

*

*Give it a negative voltage on pin 4.

*Replace with a device that will accept input voltages down to negative rail.

The second option is usually the easier.

A: Because you are attempting to operate a crappy op-amp at near the V- rail. You will need to consider providing a -12V supply to the V- pin.

A: The short answer is that yes, you do need to add in a negative supply in order to amplify voltages down to 0 volts.  The data sheet for the part recommends supply voltages from +/-20V down to +/-5V.  Thus the +12V/0V single-ended configuration barely meets the 10V minimum power supply span. However the circuit as shown has the op amp driven too close to the supply voltage rails.
This 741 part was a significant innovation in its day but there are "modern" innovations that it does not have. Among these are rail-to-rail inputs and rail-to-rail outputs.  A glance at the part schematic shown in the TI spec for the National LM741, for example shows that the outputs can only attain voltages within about a base-emitter forward biased junction (.65-.7) of the negative (or positive) rail because of the common-emitter transistors used for output.
On the input side, the stack of differential pairs used for amplification, bias and offset voltage compensation mean that the inverting and non-inverting inputs (at the top of the stack) probably can't be driven closer to ground than about 2V common mode without some kind of adverse performance.  [In fact some differential amps will stop being inverting amplifiers and become non-inverting amplifiers whenever the inputs are driven more negative than the negative rail (e.g. LM139 comparator).]    In the data sheet, due to these contributions from the inputs and output,  the  output voltage swing is not guaranteed to get any closer to the rails than 3V at 10K load or even 5V at 2K load, although typical values are 1V and 2V, respectively.
The voltage follower configuration you have shown implements the nominal relation Vi=Vo Ri/(Ri+Rf) (Ri=3.6K and Rf=4.7K), assuming that no current flows into the 741 input pin and that the op amp drives its output so that the inverting input follows very closely to the non-inverting input. This simply expresses the voltage divider relationship of gain-setting resistor Ri and feedback resistor Rf.  Thus when we get to the 2V limit of the inverting input from ground, the non-inverting input will also be at about 2V but the output pin will be at Vo=Vi (Ri+Rf)/Ri = 2V (3.6K+4.7K)/3.6K = 4.61V.  A simulation of the 741 schematic from TI, using generic transistors, in fact showed the output clamping at 4.83V on its trajectory towards ground, and the inverting input clamping at 2.1V, at exactly the divider ratio.  This goes along with what you are seeing as well.
Changing the return for the voltage divider to one half of the supply range doesn't correct the situation because you are still driving the inputs too close to the rails.  Only by changing the negative rail to provide some cushion for the inputs can you attain the bottom of the output range you want; even 2.2V would be enough.


text:
Q: Securing API key in Android Scenario :
Say you have an Android Application that uses some API on the server.
The application doesn't have a login funcionality (there is no need for it as the user doesn't have any personal data on the server)
In order to send a request to the server, you create an OAuth2 functionality on your server. You make a request to the server and it returns an Auth Token.
But this request can be easily taken if a user monitors network requests. So you create a secret key to be sent with the POST body of the Auth request.
The problem starts here :
This Secret Key that you created has to stay in the application, and any code in the application can be broken down (decompiled) and the secret would be accessable.
The key can't be on the server, or it will take a request to acquire it, and thus it can be monitored.
You can't encode it in any way, as the decoding functionality will have to be on the Android side, and thus can be decompiled.
The question :
Is there any way that is possible to at least make the Secret Key much harder to decode?
P.S : Using R8 or Proguard only obscures the code. If the hacker or attacker tries, they can easily see the entire code of the application, and can follow along to understand the flow of encoding or decoding, or find the key inside the code.

A: SCENARIO

In order to send a request to the server, you create an OAuth2 functionality on your server. You make a request to the server and it returns an Auth Token.

Here you are exposing yourself to Trust on First Use(TOFU) of the application, meaning that the API server would have to accept that the request comes indeed from what you trust to be your genuine and untampered mobile app.

But this request can be easily taken if a user monitors network requests. So you create a secret key to be sent with the POST body of the Auth request.

This is as easy as doing a Man in the Middle(MitM) attack with a tool like mitmproxy or wireshark, and it's all it takes for the attacker to learn how to do the request as if he was what you think as being your genuine mobile app, therefore without the need to stole the secret key in the POST body of the Auth request he MitM attacking.
TOFU:

Trust on first use (TOFU), or trust upon first use (TUFU), is a security model used by client software which needs to establish a trust relationship with an unknown or not-yet-trusted endpoint.

MitM:

An interactive TLS-capable intercepting HTTP proxy for penetration testers and software developers.

Wireshark

Wireshark is a network traffic analyzer, or "sniffer", for Linux, macOS, *BSD and other Unix and Unix-like operating systems and for Windows.

THE PROBLEM STARTS HERE

This Secret Key that you created has to stay in the application, and any code in the application can be broken down (decompiled) and the secret would be accessable.

Yes this is indeed a huge issue, and even when you hide the secret in native C code, like I show in this repo, you can still use tools for static analysis on the binary of your mobile app, like the MobSF, to extract any secrets on it or to find logic that deals with them.

You can't encode it in any way, as the decoding functionality will have to be on the Android side, and thus can be decompiled.

Once more you are correct, and all it takes is to use the already mentioned MobSF, or go more advanced by hooking an instrumentation framework to the code at runtime, that will allow to extract dynamically the secret key, and/or to modify any behavior of your code. A good example of such tool is Frida
MobSF:

Mobile Security Framework (MobSF) is an automated, all-in-one mobile application (Android/iOS/Windows) pen-testing, malware analysis and security assessment framework capable of performing static and dynamic analysis.

Frida:

Inject your own scripts into black box processes. Hook any function, spy on crypto APIs or trace private application code, no source code needed. Edit, hit save, and instantly see the results. All without compilation steps or program restarts.

THE QUESTION

Is there any way that is possible to at least make the Secret Key much harder to decode?

As I already mention, Frida can be used to modify the behavior of your code during the runtime, thus the attacker would find the code doing this and hook on it's return to extract the already decoded secret key.
Possible Solution
Better than hardening the secret is to not have a secret at all in the mobile app code, be it static or dynamically generated by the mobile app itself at runtime. To achieve this you will need to look into the Mobile App Attestation concept.
The Role of Mobile App Attestation
This will be a solution that will allow your API server to know that what is making the request is indeed the genuine mobile app you have uploaded to the Google Play store, not an automated script, a Postman request, or any other form of impersonation. It will consist of an attestation layer running on the cloud that will challenge the mobile app, and based on the measures returned it will issue short lived JWT tokens for the mobile app to pass down in each request to the API server, that will verify them for a valid signature and expire time. I go in more detail on this section of my article:

Before we dive into the role of a Mobile App Attestation service, we first need to understand the difference between what and who is accessing the API server. This is discussed in more detail in this article, where we can read:

The what is the thing making the request to the API server. Is it really a genuine instance of your mobile app, or is it a bot, an automated script or an attacker manually poking around your API server with a tool like Postman?
The who is the user of the mobile app that we can authenticate, authorize and identify in several ways, like using OpenID Connect or OAUTH2 flows.

The role of a Mobile App Attestation service is to authenticate what is sending the requests, thus only responding to requests coming from genuine mobile app instances and rejecting all other requests from unauthorized sources.
In order to know what is sending the requests to the API server, a Mobile App Attestation service, at run-time, will identify with high confidence that your mobile app is present, has not been tampered/repackaged, is not running in a rooted device, has not been hooked into by an instrumentation framework(Frida, xPosed, Cydia, etc.), and is not the object of a Man in the Middle Attack (MitM). This is achieved by running an SDK in the background that will communicate with a service running in the cloud to attest the integrity of the mobile app and device it is running on.
On a successful attestation of the mobile app integrity, a short time lived JWT token is issued and signed with a secret that only the API server and the Mobile App Attestation service in the cloud know. In the case that attestation fails the JWT token is signed with an incorrect secret. Since the secret used by the Mobile App Attestation service is not known by the mobile app, it is not possible to reverse engineer it at run-time even when the app has been tampered with, is running in a rooted device or communicating over a connection that is the target of a MitM attack.
The mobile app must send the JWT token in the header of every API request. This allows the API server to only serve requests when it can verify that the JWT token was signed with the shared secret and that it has not expired. All other requests will be refused. In other words a valid JWT token tells the API server that what is making the request is the genuine mobile app uploaded to the Google or Apple store, while an invalid or missing JWT token means that what is making the request is not authorized to do so, because it may be a bot, a repackaged app or an attacker making a MitM attack.
A great benefit of using a Mobile App Attestation service is its proactive and positive authentication model, which does not create false positives, and thus does not block legitimate users while it keeps the bad guys at bay.

SUMMARY
Defending API servers and mobile apps from being attacked is a very hard job has you already know, judging by the content of your question, and that I tried to make more explicit for anyone reading this answer, by providing more context and tools used to do it so.
In the end of the day is all about security in depth, and you should apply as many layers of defense as you can afford, are required by law to your use case, and that you judge adequate for the value of the data your are trying to protect.
GOING FOR THE EXTRA MILE
In any security questions I reply, I always like to finish by recommending the excellent work from OWASP, specially this one:
The Mobile Security Testing Guide

The Mobile Security Testing Guide (MSTG) is a comprehensive manual for mobile app security development, testing and reverse engineering.

A: Assuming you need to keep a secret key on the app side, you can harden the application against key lifting, reverse engineering, and tampering.
If you are already familiar with Proguard/R8, then you may find DexGuard to be a good fit for your use case.
Alternatively, you can also think of changing your application logic so that storing of a secret key on the app side is not required.
In your decision making you will need to balance:

*

*Security vs. Usability. For example, you may decide to require registration and authentication from your users instead of working without authentication.

*Risk vs. Cost. Depending on the risk associated with your API key exposure, you may decide to invest in a commercial solution or use free/DIY solutions.


text:
Q: SE Podcasts - wrong and dead link, strange filenames, missing date in filenames At https://blog.stackoverflow.com/category/podcasts/page/7/ there's the link to the SE Podcast #01 titled Stack Exchange Podcast – Episode #88 which is

*

*wrong as this is the first episode of new SE Podcast series

*dead (Oops, looks like we can't find that page!)

Also what does number "7" do in the link to the SE Podcast #02 - http://soundcloud.com/stack-exchange/stack-exchange-podcast-7/s-Fk90d ?
Additionaly

*

*the name of mp3 file for SE Podcast #01 is Edited Podcast - 192 MP3 and for SE Podcast #02 is 2011-04-26 - Edited - MP3 VBR 3.mp3. They are not in line with the rest of the series.

*names of some mp3 files (e.g., of podcasts #08, #09, #10, #11) instead of date of the podcast have some meaningless (internal?) terms like Publish or Rendered.

What a mess...

A: The links should be fixed.
The bizarre names are subtle insights into the history of the podcast. I won't spoil all the surprises for you, but SO Podcast #88 was SE Podcast #01 - the decision to renumber was made during / after that episode.
I recommend finding a good bit of software to handle downloading and listening to them. Podcast feeds were sorta designed for that...


text:
Q: SignalR working on Localhost, BUT not working on Server win server 2019 with IIS I have project with SignalR + MVC, this not working on Server win server 2019 with IIS.
I Got errors:
signalr/negotiate?clientProtocol=2.1&connectionData=%5B%7B"name"%3A"feedbackhub"%7D%5D&_=1646730379815

Can anybody help me?
This all my Code:
https://github.com/duc14s/SignalRFeedbackSample

A: Have you enabled websockets on the server?

*

*On the taskbar, click Server Manager.

*In Server Manager, click the Manage menu, and then click Add Roles and Features.

*In the Add Roles and Features wizard, click Next. …

*On the Server Roles page, expand Web Server (IIS), expand Web Server, expand - Application Development, and then select WebSocket Protocol.


text:
Q: symphony datasource error When creating a data source that pulls from any of my sections and pressing "create data source", I get the following error:
Forbidden

You don't have permission to access /symph-page/symphony/blueprints/datasources/new/ on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

Strangely, if I pull from the system or provide custom xml, the data source is created fine and I don't get the previous message. Running symphony 2.3 on server that should be meeting the technical requirements. I have run Symphony before and never encountered this sort of issue.

A: It sounds like you need to change the workspace/data-sources directory file permissions so that the web server user can write files into it.
For example, on a Linux server (777 may not be necessary and depends on your webserver's configuration):
chmod 777 /symph-page/symphony/blueprints/datasources

If you access the server via FTP, your FTP client will probably let you do this.
Edit: Re-reading your question, I think I was mistaken in saying this is a workspace writing permissions issue. I don't recognise the "blueprints" directory path. Does this directory exist within your installation, and does your webserver have read permissions?

A: You might also want to make sure that you .htaccess file is present.


text:
Q: Is git-merge output correct? I'm trying to analyze the history of merges in ANTLR4 repository of Github (https://github.com/antlr/antlr4). However, there is an output that does not make sense for me when I try to replay the merge fe1d61d9dba9f202982da85606cbb7493ce7bae8. So I wonder if somebody can help me.
The merge fe1d61d9dba9f202982da85606cbb7493ce7bae8 has two parents: 103dc662c  and 31d21ff4d. Thus, to replay the merge I execute the following steps:

*

*git checkout 103dc662c; and

*git merge 31d21ff4d.

In this case, there are some conflicting files. However, the file "repository path"/runtime/Go/src/antlr/ErrorStrategy.go show the following conflict:
// @param recognizer the parser instance
// @param e the recognition exception
//
<<<<<<< HEAD:runtime/Go/src/antlr/ErrorStrategy.go
func (d *DefaultErrorStrategy) ReportInputMisMatch(recognizer Parser, e *InputMisMatchException) {
        var msg = "mismatched input " + d.GetTokenErrorDisplay(e.offendingToken) +
=======
func (this *DefaultErrorStrategy) ReportInputMisMatch(recognizer Parser, e *InputMisMatchException) {
        var msg = "mismatched input " + this.GetTokenErrorDisplay(e.offendingToken) +
>>>>>>> 31d21ff:runtime/Go/src/antlr4/ErrorStrategy.go
                " expecting " + e.getExpectedTokens().StringVerbose(recognizer.GetLiteralNames(), recognizer.GetSymbolicNames(), false)
        recognizer.NotifyErrorListeners(msg, e.offendingToken, e)
}

When I try to open the original files in the parent's versions, the file in the left version (103dc662c) <<<<<<< HEAD:runtime/Go/src/antlr/ErrorStrategy.go exists, but the file in the right version (31d21ff4d) does not exists >>>>>>> 31d21ff:runtime/Go/src/antlr4/ErrorStrategy.go. After investigate, I could realize that the file in the right version also is in the path runtime/Go/src/antlr/ErrorStrategy.go.
Am I misinterpreting something?
Thanks in advance,
Gleiph

A: Let's repeat the setup:
$ git clone https://github.com/antlr/antlr4
Cloning into 'antlr4'...
remote: Enumerating objects: 2, done.
remote: Counting objects: 100% (2/2), done.
remote: Compressing objects: 100% (2/2), done.
^Rceiving objects:  21% (24258/115511), 16.64 MiB | 3.15 MiB/s    /s
remote: Total 115511 (delta 0), reused 0 (delta 0), pack-reused 115509
Receiving objects: 100% (115511/115511), 61.89 MiB | 3.13 MiB/s, done.
Resolving deltas: 100% (67916/67916), done.
$ git checkout -b tmp 103dc662c

All OK so far.  Now we'll get the merge conflict along with a lot of messages we should pay attention to:
$ git merge 31d21ff4d
Auto-merging tool/resources/org/antlr/v4/tool/templates/codegen/Go/Go.stg
CONFLICT (content): Merge conflict in tool/resources/org/antlr/v4/tool/templates/codegen/Go/Go.stg
Auto-merging runtime/Go/src/antlr/Utils.go
Auto-merging runtime/Go/src/antlr/Trees.go
Auto-merging runtime/Go/src/antlr/Tree.go
Auto-merging runtime/Go/src/antlr/Transition.go
CONFLICT (rename/delete): runtime/Go/src/antlr4/TraceListener.go deleted in HEAD and renamed to runtime/Go/src/antlr/TraceListener.go in 31d21ff4d. Version 31d21ff4d of runtime/Go/src/antlr/TraceListener.go left in tree.
Auto-merging runtime/Go/src/antlr/TokenStream.go
Auto-merging runtime/Go/src/antlr/TokenSource.go
Auto-merging runtime/Go/src/antlr/Token.go
Auto-merging runtime/Go/src/antlr/SemanticContext.go
Auto-merging runtime/Go/src/antlr/RuleContext.go
Auto-merging runtime/Go/src/antlr/Recognizer.go
Auto-merging runtime/Go/src/antlr/PredictionMode.go
Auto-merging runtime/Go/src/antlr/PredictionContext.go
Auto-merging runtime/Go/src/antlr/ParserRuleContext.go
Auto-merging runtime/Go/src/antlr/ParserATNSimulator.go
Auto-merging runtime/Go/src/antlr/Parser.go
Auto-merging runtime/Go/src/antlr/LexerActionExecutor.go
Auto-merging runtime/Go/src/antlr/LexerAction.go
Auto-merging runtime/Go/src/antlr/LexerATNSimulator.go
Auto-merging runtime/Go/src/antlr/Lexer.go
Auto-merging runtime/Go/src/antlr/LL1Analyzer.go
Auto-merging runtime/Go/src/antlr/IntervalSet.go
Auto-merging runtime/Go/src/antlr/IntStream.go
Auto-merging runtime/Go/src/antlr/InputStream.go
Auto-merging runtime/Go/src/antlr/FileStream.go
Auto-merging runtime/Go/src/antlr/Errors.go
Auto-merging runtime/Go/src/antlr/ErrorStrategy.go
CONFLICT (content): Merge conflict in runtime/Go/src/antlr/ErrorStrategy.go
Auto-merging runtime/Go/src/antlr/ErrorListener.go
Auto-merging runtime/Go/src/antlr/DiagnosticErrorListener.go
Auto-merging runtime/Go/src/antlr/DFAState.go
Auto-merging runtime/Go/src/antlr/DFASerializer.go
Auto-merging runtime/Go/src/antlr/DFA.go
Auto-merging runtime/Go/src/antlr/CommonTokenStream.go
Auto-merging runtime/Go/src/antlr/CommonTokenFactory.go
Auto-merging runtime/Go/src/antlr/CharStream.go
Auto-merging runtime/Go/src/antlr/ATNType.go
Auto-merging runtime/Go/src/antlr/ATNState.go
Auto-merging runtime/Go/src/antlr/ATNSimulator.go
Auto-merging runtime/Go/src/antlr/ATNDeserializer.go
Auto-merging runtime/Go/src/antlr/ATNDeserializationOptions.go
Auto-merging runtime/Go/src/antlr/ATNConfigSet.go
Auto-merging runtime/Go/src/antlr/ATNConfig.go
Auto-merging runtime/Go/src/antlr/ATN.go
Removing pb/src/parser/T.g4
Removing pb/src/parser/T.g
Removing pb/src/parser/S.g4
Removing pb/src/parser/M.g4
Removing pb/src/parser/JSON.g4
Removing pb/src/parser/Expr.g4
Removing pb/src/parser/Arithmetic.g4
Removing pb/src/parser/.gitignore
Removing pb/src/input
Removing pb/src/Test.go
Removing antlr.go
Automatic merge failed; fix conflicts and then commit the result.

Note the rename/delete conflict mentioned early on:

CONFLICT (rename/delete): runtime/Go/src/antlr4/TraceListener.go deleted in HEAD
and renamed to runtime/Go/src/antlr/TraceListener.go in 31d21ff4d. Version
31d21ff4d of runtime/Go/src/antlr/TraceListener.go left in tree.

(line-breaks added by me).

When I try to open the original files in the parent's versions, the file in the left version ... exists,

That's fine, but as it's clear that at least one side renamed at least some files, we should expect that these files might have different names in the three input commits.

... the file in the right version ... is in the path runtime/Go/src/antlr/ErrorStrategy.go.

I find this one in runtime/Go/src/antlr/ErrorStrategy.go, in MERGE_HEAD aka 31d21ff4db8ddcf76bae1b865cd568621bfd5b4d.
However, in the merge base commit:
$ git merge-base --all HEAD MERGE_HEAD
3406acabe51e89c57fc26aca02aeb7cbc30119bd

the repository has it in runtime/Go/src/antlr4/ErrorStrategy.go:
git ls-tree -r 3406acabe51e89c57fc26aca02aeb7cbc30119bd | grep ErrorStrategy.go
100644 blob aed0ef94b5409f8035897496610446a5cbb52ef2    runtime/Go/src/antlr4/ErrorStrategy.go

In other words, it appears that both of the two merge input commits have followed the same rename pattern here.  The diff from merge base to HEAD, and the diff from merge base to 31d21ff4d, both renamed the antl4 subdirectory to antlr.
This is all perfectly normal.  If you are doing manual merge resolution, you might find it helpful to set merge.conflictStyle to diff3.  If you prefer to have Git find the files for you, consider using git mergetool to extract the input files: it is supposed to automatically find the merge-base, HEAD, and MERGE_HEAD files for you.

A: Torek,
Thanks a lot. However, in the Git merge documentation (https://git-scm.com/docs/git-merge), there is the following example:
Here are lines that are either unchanged from the common
ancestor, or cleanly resolved because only one side changed.
<<<<<<< yours:sample.txt
Conflict resolution is hard;
let's go shopping.
=======
Git makes conflict resolution easy.
>>>>>>> theirs:sample.txt
And here is another line that is cleanly resolved or unmodified.

So I would expect something like:
// @param recognizer the parser instance
// @param e the recognition exception
//
<<<<<<< HEAD:runtime/Go/src/antlr/ErrorStrategy.go
func (d *DefaultErrorStrategy) ReportInputMisMatch(recognizer Parser, e *InputMisMatchException) {
        var msg = "mismatched input " + d.GetTokenErrorDisplay(e.offendingToken) +
=======
func (this *DefaultErrorStrategy) ReportInputMisMatch(recognizer Parser, e *InputMisMatchException) {
        var msg = "mismatched input " + this.GetTokenErrorDisplay(e.offendingToken) +
>>>>>>> 31d21ff:runtime/Go/src/antlr/ErrorStrategy.go
                " expecting " + e.getExpectedTokens().StringVerbose(recognizer.GetLiteralNames(), recognizer.GetSymbolicNames(), false)
        recognizer.NotifyErrorListeners(msg, e.offendingToken, e)
}

In this case both branches are renamed. However, the line >>>>>>> 31d21ff:runtime/Go/src/antlr/ErrorStrategy.go is >>>>>>> 31d21ff:runtime/Go/src/antlr4/ErrorStrategy.go in the real example. Does it make sense to you?
Thanks,
Gleiph


text:
Q: In Vim, how to find out what a key combination does I accidentally press a shorcut key, and I know that vim has done something but I don't know what.
How can I find out what that shortcut key does?

A: There are two potential sources for information.  First of all, if it's a built in shortcut, it is normally in the help documentation.  For instance, if you do :help CTRL-I, it'll take you to a help entry about moving around your jump list.
It is possible, however, that you have a custom mapping from one of your .vimrc files or an underdocumented plugin.  In that case, try using :map which will list all custom keyboard mappings that are currently active.  That will give you three columns:

*

*the mode the mapping applies to

*the keyboard shortcut

*the command that is run

You can then use :help to further investigate the command that is run.

A: You might check out the answers at In Vim can I find out what keys I just typed? (If this is what you're looking for).

A: Just doing :map will show you lots of mappings, but if your mapping is F2 or ShiftEnter or CtrlP then the second column (which should show the keyboard shortcut) will be empty.
However you can ask map to tell you what a particular key combination is. Some examples that line up with the above examples:
:map <F2>
:map <S-CR>
:map <C-P>


text:
Q: txt file parsing c++ in to vector more efficiently My program uses ifstream() and getline() to parse a text file in to objects that are two vectors deep. i.e vector inside vector. The inner vector contains over 250000 string objects once the text file is finished loading.
this is painfully slow. Is there an STD alternative that is more efficient than using ifstream() and getline() ?
Thanks
UPDATE:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <regex>

using namespace std;

class Word
{
private:
    string moniker = "";
    vector <string> definition;
    string type = "";

public:
    void setMoniker(string m) { this->moniker = m; }
    void setDefinition(string d) { this->definition.push_back(d); }
    void setType(string t) { this->type = t; }
    int getDefinitionSize() { return this->definition.size(); }

    string getMoniker() { return this->moniker; }
    void printDefinition()
    {
        for (int i = 0; i < definition.size(); i++)
        {
            cout << definition[i] << endl;
        }

    }

    string getType() { return this->type; }
};

class Dictionary
{
private:
    vector<Word> Words;

public:
    void addWord(Word w) { this->Words.push_back(w); }
    Word getWord(int i) { return this->Words[i]; }
    int getTotalNumberOfWords() { return this->Words.size(); }
    void loadDictionary(string f)
    {
        const regex _IS_DEF("[\.]|[\ ]"),
            _IS_TYPE("^misc$|^n$|^adj$|^v$|^adv$|^prep$|^pn$|^n_and_v$"),
            _IS_NEWLINE("\n");

        string line;

        ifstream dict(f);

        string m, t, d = "";

        while (dict.is_open())
        {
            while (getline(dict, line))
            {
                if (regex_search(line, _IS_DEF))
                {
                    d = line;
                }
                else if (regex_search(line, _IS_TYPE))
                {
                    t = line;
                }
                else if (!(line == ""))
                {
                    m = line;
                }
                else
                {
                    Word w;
                    w.setMoniker(m);
                    w.setType(t);
                    w.setDefinition(d);
                    this->addWord(w);
                }
            }
            dict.close();
        }
    }
};

int main()
{
    Dictionary dictionary;
    dictionary.loadDictionary("dictionary.txt");
    return 0;
}

A: You should reduce your memory allocations.  Having a vector of vectors is usually not a good idea, because every inner vector does its own new and delete.
You should reserve() the approximate number of elements you need in the vector at the start.
You should use fgets() if you don't actually need to extract std::string to get your work done.  For example if the objects can be parsed from char arrays, do that.  Make sure to read into the same string buffer every time, rather than creating new buffers.
And most important of all, use a profiler.


text:
Q: Check if NSAnimationContext runAnimationGroup cancelled or succeeded I'm animating a view (by revealing it) after which I need to post a notification (once the animation completes). However the way the app's designed, there's another notification sent out when the view is hidden (via animation). So essentially I have a 'showView' and a 'hideView' method. Each do something like so:
    [NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) {
      [context setDuration: 0.25];

      [[myView animator] setAlphaValue: 0];
    } completionHandler:^{
       // post notification now
    }];

The problem is that in another thread in the background, I have a periodic timer which performs a 'sanity check' to see if the view needs to be hidden if it's not needed. It's an aggressive approach but necessary as many components of the app respond to different events and scenarios. Due to this I at times get a 'race condition' where the user has clicked to 'showView' but at the same time one of our threads feel the view should be immediately hidden.
When both post a notification on the main thread, the app hangs indefinitely in a SpinLock. I could completely avoid this situation if I was able to figure out if the animation block above was 'cancelled' (i.e. another animation block executed on the same view). In such situations I would not post the notification, which would then not force a check.
Long story short: I need to be able to check if the 'completionHandler' was called after animation successfully ended or if it was cancelled. I know in iOS this is possible but I can't find any way to do this in OS X. Please help.

A: I encountered a similar problem. I solved it by using a currentAnimationUUID instance variable.
NSUUID *animationUUID = [[NSUUID alloc] init];
self.currentAnimationUUID = animationUUID;

[NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) {
    // set properties to animate
} completionHandler:^{
    BOOL isCancelled = ![self.currentAnimationUUID isEqual:animationUUID];
    if (isCancelled) {
        return;
    }

    self.currentAnimationUUID = nil;

    // do stuff
}];

Swift version:
let animationUUID = UUID()
currentAnimationUUID = animationUUID

NSAnimationContext.runAnimationGroup({ context in
    // set properties to animate
}, completionHandler: {
    let isCancelled = self.currentAnimationUUID != animationUUID
    guard !isCancelled else {
        return
    }

    self.currentAnimationUUID = nil

    // do stuff
})


text:
Q: .hover Works, On Click doesn't So this has caused me a lot of headace.
I am making a "pulldown accordion submenu" (for the lack of a better name).
My script works, but only on HOVER. If I try to use .click, .on("click"), .on("click", "li") etc. nothing works. The script only works when using .hover.
NOTE!
It's only the "#TopMenu" that is supposed to have the on click event. The sub-menu ("#accordion") is going to be hover.
Any ideas ?
Working:
$(document).ready(function () {

    $('#accordion li').hover(function () {
        $(this).find('ul').stop(true, true).slideDown()
    }, function () {
        $(this).find('ul').stop(true, true).slideUp()
    }).find('ul').hide()

$('#TopMenu li').hover(function() {

        $(this).find('li').stop(true, true).slideDown()
    }, function () {
        $(this).find('li').stop(true, true).slideUp()
    }).find('li').hide()

});

Changing "#TopMenu" to CLICK is NOT WORKING:
$(document).ready(function () {

    $('#accordion li').hover(function () {
        $(this).find('ul').stop(true, true).slideDown()
    }, function () {
        $(this).find('ul').stop(true, true).slideUp()
    }).find('ul').hide()

$('#TopMenu li').on('click', function() {

        $(this).find('li').stop(true, true).slideDown()
    }, function () {
        $(this).find('li').stop(true, true).slideUp()
    }).find('li').hide()

});

I have a working test here: http://jsbin.com/nidazuq/3/embed?html,js,output
I'm going nuts over this, I've searched high and low for a solution. please help.

A: ID should be unique and single for a page. You used twice in the page. Added fiddle with some changes.

$('#TopMenu li').on('click', function() {
  $(this).children('ul').slideToggle();
});
$("#TopMenu li ul li > a").hover(function(){
  $(this).next('ul').slideToggle();
})
#TopMenu li ul, .firstStep ul ul, .firstStep ul{display:none}

CLICK ME

 HISTORY

Link One

Link Two

Link Three

Link Four

Link Five

 GEOGRAPHY

Link One

Link Two

Link Three

Link Four

Link Five

A: First of all you are using same Ids for multiple elements. This is wrong. You should use class for selection.Change id='TopMenu' to class='TopMenu' . Second, the 'click' function not triggered with 'li' element. You should listen 'a' element's click function.
$('.TopMenu li a').on('click', function() {});

I am not familiar with slideDown and slideUp functions but you can continue from there. And don't forget that $(this) element refers to CLICK ME for this click function.


text:
Q: Windows Phone 7: All I get is System.MethodAccessException This is my first time to develop apps in Windows Phone 7 and I was not that welcome. LOL.
Anyways, my problem is this MethodAccessException and am not sure why it keeps throwing me that exception.
Here's what I was trying to do.

*

*Getting Application StartUp Path by:
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase
System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName
API:
[DllImport("coredll.dll", SetLastError = true)]
public static extern int GetModuleFileName(IntPtr hModule, StringBuilder lpFilename, int nSize);

*Try to just enumerate some files
int c = Directory.GetFiles(@"\").Length;
System.Diagnostics.Debug.WriteLine("total files: " + c);
and am not sure what else since I just started coding. I have a big app in mind, and it will cover Registry IO, File IOs, and Database. But if this MethodAccessException keeps blocking my way, I'd rather be dead.
Am using Windows Phone 7.0
6176.WM7 RC1Escrow(buildlab).20100406 1457

A: You cannot use Reflection or P/Invokes in Phone 7.
For File I/O you should be using IsolatedStorageFile for dealing with files.  See this example (among many on the web).
There is no Registry access (maybe explaining why you think you need it can lead us to providing alternatives).
For Database access, there are lots of options.  Depends on where you want the database (local/remote/cloud), what engine you want, ORM preferences, etc.


text:
Q: How to add styles(css) and js to handlebar files? I want to add styles and js to my handlebar files. I tried looking for different places but still not able to find a solution. I tried using partials to store the stylesheet tags then adding those partials to handlebar but that too didn't worked.
(Or if there is any other templating engine that provides much better css support, that too will work for me)
Please Help!
styles.hbs (partial file)
<link rel="stylesheet" href="./../css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="./../css/main.css">

server.js
const express = require('express');
const hbs = require('hbs');

var app = express();

app.set('view engine', 'hbs');
hbs.registerPartials(__dirname + '/views/partials');

app.get('/', (req, res) => {
    res.render('index.hbs');
});

app.listen(3000, ()=>{
    console.log('Server is up at port 3000');
});

index.hbs
<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Home Page</title>

    {{> styles}}
  </head>
  <body>
   ...
  </body>
</html>

A: This is an old question but still confusing. Here is the most effective way to use different css file in your views:
main.hbs (Your base layout)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="mainstyle.css">
    <!-- mainstyle.css will be effective in all pages-->
    {{{customstyle}}}
    <title>{{title}}</title>
</head>
<body>
    {{body}}
</body>
</html>

Please pay attention {{{customstyle}}} line in main.hbs
app.js
...
app.use((req, res) => {
    res.status(404).render("404page", {title:"404 not found",
    customstyle: `<link rel="stylesheet" href="/css/customstyle.css">`});
});
...

Thats it. As you know, {{{ }}} renders as html code, but {{ }} renders as only text in handlebars. customstyle passes as an argument to main.hbs layout file. We used three curly brackets in main.hbs file, because of we wanted to process the argument we send as html code. In this way, customsytle.css file added only when 404page viewed.


text:
Q: How to fix the error in python pybliometrics.scopus.exception.Scopus401Error? I'm new to pybliometrics. I opened the python pybliometrics documentation and ran this example:
from pybliometrics.scopus import AffiliationSearch
query = "AFFIL(Max Planck Institute for Innovation and Competition Munich)"
s = AffiliationSearch(query)
print(s)

But it throws a pybliometrics.scopus.exception.Scopus401Error error.
Traceback (most recent call last):
  File "C:/Users/Professional/PycharmProjects/firstScopus/main.py", line 3, in <module>
    s = AffiliationSearch(query)
  File "C:\Users\Professional\PycharmProjects\firstScopus\venv\lib\site-packages\pybliometrics\scopus\affiliation_search.py", line 106, in __init__
    Search.__init__(self, query=query, api="AffiliationSearch",
  File "C:\Users\Professional\PycharmProjects\firstScopus\venv\lib\site-packages\pybliometrics\scopus\superclasses\search.py", line 76, in __init__
    Base.__init__(self, qfile, refresh, params=params, url=SEARCH_URL[api],
  File "C:\Users\Professional\PycharmProjects\firstScopus\venv\lib\site-packages\pybliometrics\scopus\superclasses\base.py", line 70, in __init__
    resp = get_content(url, params, *args, **kwds)
  File "C:\Users\Professional\PycharmProjects\firstScopus\venv\lib\site-packages\pybliometrics\scopus\utils\get_content.py", line 88, in get_content
    raise errors[resp.status_code](reason)
pybliometrics.scopus.exception.Scopus401Error

Process finished with exit code 1

As I understand it, I need to specify the API keys. How to do it?

A: You're right, according to https://pybliometrics.readthedocs.io/en/stable/access.html#error-messages 401 is most likely due to a missing key.
As the documentation on the configuration states, pybliometrics starts a process in the beginning to create the config. It asks for the API keys, and more. It seems you skipped this.
To manually create the config, go to your home directory (~/ on *nix systems) and create the folder .scopus (the dot is important). In there, create the file config.ini with a normal text editor. It needs to have at least those two sections, Directories and Authentication as shown on the documentation on the configuration.
Or simply reinstall pybliometrics and don't skip the set-up prompt in the beginning.


text:
Q: kafka message distribution between consumers I have very simple kafka use case where I am facing issue with message distribution among 2 partitions.
I have 2 partitions on topic and I have 2 consumers for each. I can see more messages went to specific partition and only one consumer is getting messages to process and other one which is subscribed to partition having less messages is sitting idle forever. both consumers are having same group id. I am not able to achieve horizontal scaling with this issue.
Below are key configs I am putting.
kafka.session.timeout.ms=10000
kafka.auto.commit=false
kafka.maxpoll.interval.ms=50000
kafka.request.timeout.ms=15000
kafka.maxpoll.records=100

**PS:**names are from my prop file and not exactly matching with real kafka property names.
I need large max poll interval so as to process big chunk in one go. Any guess as what I need to add in config or change it?

A: As mentioned in other answer kafka uses hash of key to decide the partition. It could be that your key are not evenly distributed .In such cases you can define your own  strategy to select partition by producer while producing records.
Create a custom partitoner class and implement partition method of it as following.
import org.apache.kafka.clients.producer.Partitioner;
import org.apache.kafka.common.Cluster;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.record.InvalidRecordException;

public class CustomPartitioner implements Partitioner {

    public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster) {
        List<PartitionInfo> partitions = cluster.partitionsForTopic(topic);
        int numPartitions = partitions.size();
        if ((keyBytes == null) || (!(key instanceof String)))
            throw new InvalidRecordException("We expect all messages to have a key");
        // Your logic to decide partition based on key
        return 0;// Here return thr partition decided based on key
    }

    public void close() {
    }

    public void configure(Map<String, ?> configs) {
        // TODO Auto-generated method stub

    }
}

On producer configuration add following
properties.put(ProducerConfig.PARTITIONER_CLASS_CONFIG, CustomPartitioner.class.getCanonicalName());
property

A: Kafka Producer : producers send records to a partition based on the record's key. The default partitioner for Java uses a hash of the record's key to choose the partition or uses a round-robin strategy if the record has no key. So to be more scalable always use unique key for message

Producers publish data to the topics of their choice. The producer is responsible for choosing which record to assign to which partition within the topic. This can be done in a round-robin fashion simply to balance load or it can be done according to some semantic partition function (say based on some key in the record). More on the use of partitioning in a second!

If records have same key then they will end in same partition
You can also send record to particular partition
public ProducerRecord(String topic,
          Integer partition,
          K key,
          V value)

Creates a record to be sent to a specified topic and partition


text:
Q: How to test the side effects of a subscription in an Angular component I have an Angular component, MyComponent, which calls a method returning an Observable and subscribes to it, something like
export class MyComponent {
  someProperty;
  constructor(service: MyService) {}
  someButtonClicked() {
    this.service.doStuffAsync().subscribe(
      resp => this.someProperty = resp;
    );
  }
}

@Injectable()
export MyService {
  doStuffAsync() {
    // returns an Observable which notifies asychronously, e.g. like HttoClient.get(url)
  }
}

I want to test the method someButtonClicked() and therefore I create a MyServiceMock class which I inject in the test
export class MyServiceMock {
  doStuffAsync() {
    return of({// some object}).pipe(observeOn(asyncScheduler));
  }
}

For whatever reason I want doStuffAsync() of MyServiceMock to be asynchronous so observeOn(asyncScheduler) is used.
At this point though I do not know how to test someButtonClicked(). I have tried different strategies, e.g. the following
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      providers: [
        { provide: MyService, useClass: MyServiceMock },
      ]
    }).compileComponents();
  }));

  let fixture: ComponentFixture<MyComponent>;
  let component: MyComponent;

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });
  it('test someButtonClicked', async(() => {
    component.someButtonClicked();
    fixture.whenStable().then(() => {
      expect(component.someProperty).toBeDefined();
    });
  }));

but this fails since doStuffAsync() of MyServiceMock asynchronous.
So my question is which is the best strategy to test the side effects (i.e. someProperty being set correctly) induced by a method which subscribes to an asynchronous Observable.

A:  // All code should be synchronous within this it block
    it('test someButtonClicked', async(() => {
      // sync - button clicks are synchronous
      component.someButtonClicked();

      // but after btn clicks, we need to let some async code to finish
      // like rxjs subscriptions etc.
      await fixture.whenStable();
      // and then continue

      expect(component.someProperty).toBeDefined();
    }));

Don't use then fixture.whenStable().then()

A: I use a helper function called emitted
export const emitted = obs$ => new Promise(function(resolve, reject) {
  const emitted$ = new Subject();
  obs$.pipe(takeUntil(emitted$)).subscribe(
    _ => {
      emitted$.next();
      emitted$.complete();
      resolve(true);
    },
    _ => {
      emitted$.next();
      emitted$.complete();
      reject('An error occurred');
    }
  )
});

If your mock services shared the same instance of the observable with the component
export class MyServiceMock {
  private obs$ = of({// some object}).pipe(observeOn(asyncScheduler));

  doStuffAsync() {
    return obs$;
  }
}

inside your spec you can await it to have emitted
it('test someButtonClicked', async(async () => {
  component.someButtonClicked();
  const service = TestBed.get(MyService);
  await emitted(service.doStuffAsync());
  expect(component.someProperty).toBeDefined();
}));

Seeing you subscribed to the same instance of the observable as the component you know the component has run it's observer function as well as you subscribed after the component did.


text: Q: Intermittent wifi on Macbook Pro Mid 2010 Experiencing connectivity issues on my Macbook Pro 2010... ping works flawlessly however every 2 minutes or so while browsing the internet (with both safari and chrome), I will run into a timeout and nothing loads for another minute, after which the cycle repeats. Any idea how to fix this issue?


text:
Q: Linking two repositories in git We have a set of git repositories where our product is developed. These repositories are managed in bitbucket or gitlab and hosted on-prem or cloud. Changes done to these repo's need to be propagated periodically (say once a month) to a set of public repo's hosted in github. This requirement is there to support our beta program where we test out changes before making it public (making it GA). Are there any standard patterns that can be used for this purpose?

A: Clone the Bitbucket repository to your local machine:
$ git clone --mirror ssh://git@bitbucket.org:your_name/your_repo.git

Then you basically have to run these two commands every month:
$ git remote update --prune
$ git push --mirror git@github.com:your_name/your_repo.git

Linux and Cron
If you have a Linux machine/Linux server/WSL edit your crontabs:
$ crontab -e

Add this crontab:
@monthly git -C <local_repo_path> remote update --prune && git -C <local_repo_path> push --mirror git@github.com:your_name/your_repo.git

macOS and Cron
Automating tasks using Cron is very similar to the way it's done in Linux, follow this guide to get started.
Windows and Scheduled Task
I am not very familiar with Schtasks, but I this is how you would automate the task:
> schtasks /create /tn git-mirror /tr git -C <local_repo_path> remote update --prune && git -C <local_repo_path> push --mirror git@github.com:your_name/your_repo.git /sc weekly /d MON /ru "System"


text:
Q: operator Overloading and mutex I want to create mutex(boost) inside the operator (=)
the code below is thread safe?
ub_int & operator=(const int x)
{
    mutex::scoped_lock mylock(MX_ub, defer_lock);
    mylock.lock();
        this->v=x;
    mylock.unlock();
    return *this;
}

A: The code seems to be correct, but

*

*as described in the comments, you should not use the defer_lock parameter

*At least in the example you probably don't need a mutex at all, as a write to an int is usually an atomic operation


text:
Q: CSS layout problem If I have two 3in divs (a and b) and a 4in div (c). In a ten inch wide outer div. I want this layout
1234567890 # ruler
---------- # header
aaaccccbbb # the divs in question

But if that outer div becomes 8 inches I want this layout
12345678
--------
aaa  bbb
  cccc

Can that be done without JavaScript? I would do a-float:left b-float:right and c-margin:0 auto but then the elements overlap... (X is the overlap)
12345678
--------
aaXccXbb

A: This is the solution you want. No javascript needed, just the magic of overflow: hidden which gives the center-div respect to the flow :)
See the effect by making the output screen wider and smaller!
CSS solution

A:

1 2 3 4 5 6 7 8 9 0

- - - - - - - - - -

a a a

 b b b

c c c c

Media Queries to the rescue!
(Works great in FF3.6)

A: var mydiv = document.getElementById("mydiv");
var curr_width = mydiv.style.width;

// Will likely need to do the pixel-inches conversion here.
if (curr_width >= 8in)
{
   mydiv.class = other_class
}

This is a general implementation idea, in Javascript.
Related article here.
-Brian J. Stinar-

A: First of all, I don't see how you measure the width of the divs in inches. Anyway, the solution would be to have the div marked as "aaaa" float left, the div marked "bbbb" float right and the div marked "cccc" float left with a margin 0 auto on it. Still, your question is a little bit confusing to me so here's a basic markup and css that you could test. Please note I didn't test this in the browser and it might not give the expected results. Still, it should give you some pointers:

cccccc

aaaaaa

bbbbbb

Also, even if this or another solution works, it isn't ideal. IF you could give more details, I'm sure that there's a better option out there. Having div's moving around the page like this looks more like broken design to me, sorry to tell you that buddy.
Cheers!

A: Float the "a" and "b" divs left and right respectively, and apply a 4-inch width to both of them.  Then place the "c" div below them.