text:
Q: Why does the fact that $f$ and $g$ have the same Fourier coefficients imply that $f=g\text{ a.e.} $ I am self-learning Rudin's RCA and I encountered a puzzle that struggled me for a long time. Here is the related text from RCA and my question.

Suppose now that $f\in L^1(T)$, that $\{c_n\}$ is given by $ c_n = \frac{1}{2\pi} \int_{-\pi}^\pi f(x)e^{-inx} \, dx$, and that $\sum_{-\infty}^\infty |c_n|<\infty$. Put $g(x)=\sum_{-\infty}^\infty c_n e^{inx}$.
We can get that the series $g(x)$ converges uniformly by  $\sum_{-\infty}^\infty |c_n|<\infty$ (hence $g$ is continuous), and the Fourier coefficients of $g$ are easily computed. Through the computation, we know that $f$ and $g$ have the same Fourier coefficients. This implies $f=g\text{ a.e.}$, so the Fourier series of $f$ converges to $f(x)\text{ a.e.}$

My question is in the very last line: why the fact that the Fourier coefficients of $f$ and $g$ are equal implies that $f=g\text{ a.e.}$?
Guess 1: I am aware that if $f$ and $g$ are continuous, then this implication can follow. So, we may use that $C(T)$ is dense in $L^1(T)$ to try to solve this question. But I am stuck with the $\epsilon$ thing.
Guess 2: Is it true that if a function's Fourier series converges pointwise, then the series must converge (pointwise a.e.) to the original function? If yes, then we can say that the Fourier series of $f$ converges pointwise to $g$, and $g$ is equal to $f\ a.e.$ by the above guess.

A: I would break the proof into several steps.
Step 1: if $f \in C(T)$, then the Fourier series of $f$ is uniformly Cesaro summable to $f$
The $N$ th-Cesaro sum of the Fourier series is defined as
$$
\sigma_N f := \frac{1}{N} \sum_{n = 0}^{N-1} S_N f
\quad \text{where} \quad
S_N f = \sum_{n = -N}^N \hat{f}(n) e^{inx}
$$
It is a routine exercise to prove $\sigma_N f = f * F_N$, where $F_N$ is the Fejer kernel:
$$
F_N(x) = \frac{ \sin^2 (Nx/2) }{ N \sin^2 (x/2) }
$$
The sequence of Fejer kernels $\{F_N\}_{N=1}^\infty$ is an approximate identity in the sense that:

*

*$ \int_T F_N(x) dx = 1 $ for all $N$

*$ \sup_N ||F_N||_{L^1} < \infty $

*for any $\delta > 0$, we have $$ \lim_{N \to \infty} \int_{T \setminus \{|x| < \delta\} } |F_N(x)| dx = 0 $$
It is a well-known theorem in Fourier analysis that if $f \in C(T)$ and $\{F_N\}_{N=1}^\infty$ is an approximate identity, then $f * F_N$ converges to $f$ uniformly. Thus, the Fourier series of $f$ is uniformly Cesaro summable to $f$.
Step 2: The trigonometric polynomials are dense in $C(T)$
It is another routine exercise to prove the following identity:
$$
\sigma_N f  = \sum_{n=-N}^N \left( 1 - \frac{|n|}{N} \right) \hat{f}(n) e^{inx}
$$
which implies $ \sigma_N f \in \operatorname{span}\{e^{inx} : n \in \mathbb{Z}\}$. But by step 1, $\sigma_N f$ converges to $f$ uniformly for any $f \in C(T)$. Thus, the subspace $ \operatorname{span}\{e^{inx} : n \in \mathbb{Z}\} $ is dense in $C(T)$ in the uniform norm.
Step 3: if $f \in C(T)$ and $\hat{f}(n) = 0$ for all $n$, then $f = 0$
The assumption $\hat{f}(n) = 0$ for all $n$ implies
$$ \int_T \overline{f(x)} e^{inx} dx = 0 \quad \forall n $$
which further implies $ \int_T \overline{f(x)} p(x) dx = 0 $ for any trigonometric polynomials $p$.
Let $f \in C(T)$ and $\epsilon > 0$. By step 2, there exists a trigonometric polynomials $p_\epsilon$ such that $ ||f - p_\epsilon||_\infty < \epsilon $. Thus,
\begin{align*}
\int_T |f(x)|^2 dx
&= \int_T \left( \overline{f(x)} (f(x) - p_\epsilon(x)) + \overline{f(x)} p_\epsilon(x) \right) dx \\
&= \int_T \overline{f(x)} (f(x) - p_\epsilon(x)) dx \\
&\leq \int_T |\overline{f(x)}| ||f - p_\epsilon||_\infty dx \\
&\leq \epsilon ||f||_{L^1}
\end{align*}
Since $||f||_{L^1} < \infty$ and $\epsilon > 0$ is arbitrary, $ \int_T |f(x)|^2 dx = 0$. By continuity, we have $f = 0$.
Step 4: if $f \in L^1(T)$ and $\hat{f}(n) = 0$ for all $n$, then $f = 0$ a.e.
In this case, define $ F(x) = \int_{-\pi}^x f(t) dt $ for $ -\pi \leq x \leq \pi $. Clearly, we have
$$ \int_T \int_{-\pi}^x |f(t) e^{-inx}| dt dx
= \frac{1}{2\pi} \int_{-\pi}^\pi \int_{-\pi}^x |f(t)| dt dx < \infty $$
This allows us to use Fubini theorem to compute
\begin{align*}
\hat{F}(n) &= \frac{1}{2\pi} \int_{-\pi}^\pi \left( \int_{-\pi}^x f(t)dt \right) e^{-inx} dx \\
&= \frac{1}{2\pi} \int_{-\pi}^\pi \int_t^\pi f(t) e^{-inx} dx dt \\
&= \frac{1}{2\pi} \int_{-\pi}^\pi f(t) \frac{e^{-int} - (-1)^n}{in} dt \\
&= \frac{\hat{f}(n) - (-1)^n \hat{f}(0)}{2\pi in} = 0
\end{align*}
Since $F$ is absolutely continuous, we have $F = 0$ by step 3. Finally, by Lebesgue differentiation theorem, $f = F' = 0$ a.e.

A: From the comments and the other answer there is a consensus that Cesàro summability of Fourier series is a  good way to think about this situation.
Here is another way to express this (without a detour through continuous functions).  It is standard and what is used in the reference [1] (a general real analysis text)  as well as many specialized textbooks on Fourier series.

*

*Definition.   A point $x_0$ is said to be a Lebesgue point of a Lebesgue integrable function $f$ if
$$ \lim_{h\to 0} \frac1h \int_{x_0}^{x_0+h} |f(x)-f(x_0)|\,dx = 0.$$
[see Definition 7.40 in [1].]

*Theorem.  Almost every point is a Lebesgue point of an integrable function. [See Theorem 7.41 in [1]]

*Theorem. The Cesàro means of the Fourier series for any Lebesgue integrable function converge to the value of that function at every point that is a Lebesgue point for the function. [See Theorem 15.5 in [1]]

*Corollary.  If the Fourier series of an integrable function happens to converge almost  everywhere it must converge almost everywhere to that function.
This is because convergence of any series implies convergence of the Cesàro means to the same value.

*Theorem.  If two integrable functions $f$ and $g$ have the same Fourier coefficients then $f=g$ a.e.

Proof.  The function $h=f-g$ has every Fourier coefficient zero and the Fourier series for $h$ must have its Cesàro means converging to zero at every Lebesgue point of $h$.  Consequently $h=0$ a.e. and so $f=g$ a.e.
[See Theorem 15.8 in [1]]

*Cautionary example:  There is an abundance of Lebesgue integrable functions whose Fourier series diverge at every point.

This is due to Kolmogorov [2].  For a follow-up to this, if you are interested, make sure to read Olevskiĭ's [3] tribute to Kolmogorov.

REFERENCES:
[1]  http://classicalrealanalysis.info/documents/BBT-AlllChapters-Landscape.pdf
[2]  Kolmogorov, A. N.: Une série de Fourier-Lebesgue divergente partout, Comptes Rendus, 183, 1327-1328 (1926).
[3] Olevskiĭ, A.  Kolmogorov's theorems in Fourier analysis. Geometric aspects of functional analysis.  199–218. Oper. Theory Adv. Appl., 77, Birkhäuser, Basel, 1995.

A: The hypothesis $\sum |\widehat{f}(n)|<\infty$ implies $\sum |\widehat{f}(n)|^2<\infty$, and we can think in terms of the Parseval theorem that $\int_0^{2\pi}|f(t)|^2\,dt=\sum |\widehat{f}(n)|^2$ (up to a normalizing constant).
Applying this to $f-g$ gives $\int_0^{2\pi}|f(t)-g(t)|^2\,dt=0$. From definitional properties of integrals, this entails that $f-g$ is $0$ almost everywhere.


text:
Q: Select partitions of rows where columns have equal value I have data grouped (column_2) and I want to select only the rows where for each group (same column_2 value) all the values at another column (column_3) is equal.
There are more columns with no distinct values (such as column_1) but we don't care about their values.
For example, for this table:
| column_1   | column_2 | column_3 |
----------------------------------
|'irrelevant'|    1     |    5     |
|'irrelevant'|    1     |    5     |
|'irrelevant'|    1     |    5     |
|'irrelevant'|    2     |    3     |
|'irrelevant'|    2     |    5     |
|'irrelevant'|    2     |    5     |
|'irrelevant'|    3     |    7     |
|'irrelevant'|    3     |    7     |
|'irrelevant'|    4     |    8     |
|'irrelevant'|    4     |    9     |
|'irrelevant'|    4     |    2     |
|'irrelevant'|    5     |    6     |
|'irrelevant'|    6     |    2     |
|'irrelevant'|    7     |    1     |
|'irrelevant'|    7     |    1     |
|'irrelevant'|    7     |    1     |

I'd get:
| column_1   | column_2 | column_3 |
----------------------------------
|'irrelevant'|    1     |    5     |
|'irrelevant'|    1     |    5     |
|'irrelevant'|    1     |    5     |
|'irrelevant'|    3     |    7     |
|'irrelevant'|    3     |    7     |
|'irrelevant'|    5     |    6     |
|'irrelevant'|    6     |    2     |
|'irrelevant'|    7     |    1     |
|'irrelevant'|    7     |    1     |
|'irrelevant'|    7     |    1     |

The rows are skipped where, for the same column_2 value, the column_3 is not the same across them.

A: You can use COUNT(DISTINCT <expr>) to find out how many different values are there per group.
For example:
select *
from t
where column_2 in (
  select column_2
  from t
  group by column_2
  having count(distinct column_3) = 1
)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Triming a paragraph Hi I'm trying to trim a paragraph. What I would like is to have 2 lines of text and when you click on the trimed content it expands and the rest of the content is shown.
This is my code
$str.='

        '.$this->title.'

';
$str.='

';

    foreach($this->boxes as $box){

        if($htag > 6){
        $htag=6;
        }
        $str.='
';
        $str.='
';
        if( $box->image ) $str.= 'image.'" />';
            if( $box->title ){
            $str.= '<h'.$htag.'>'.$box->title.'</h'.$htag.'>';
            }

            if( $box->content ){
                if (stristr($box->content,'
')){
                    $str.= $box->content;
                }else{
                    $str.= '
'.$box->content.'
';
                }
            }
            $str.= '

';
        $str.='
';

        $htag++;
        $str.='
';
    }

    $str.='
';
$str.='
';
$str.='

A: I think you're using the wrong tool for the job.
Instead, do this on the client-side, which is pretty easy.
For example:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue.

CSS
.block {
    max-height: 3em;
    width: 20em;
    border: 1px solid red;
    overflow: hidden;
    transition: all 2s linear;
    -o-transition: all 2s linear;
    -moz-transition: all 2s linear;
    -webkit-transition: all 2s linear;

}

.block.open {
    max-height: 100em;
}

JS
$('.block').on('click', function(e) {
    $(this).toggleClass('open')
})

This should even give you a fancy animated effect ...


text:
Q: Trying to run tests after a code change throws type loading exception in MsTest After code changes when trying to run unit tests all tests fail with and error

Unit Test Adapter threw exception:  Unable to load one or more of the
  requested types. Retrieve the LoaderExceptions property for more
  information..

If I just run them once under debugger, they all pass and until a change is done to "code under test" I can run them without any issue.
If I change the code I have to "debug" them first in order to run.
Using VS2010 SP1 under win7.
Any ideas how to get rid of this?


text:
Q: anyone know how to add command line args in vs2008 i have a program that runs like so:
a.out 23421232
now if i use a.out it will tell me check params and gives an example and closes.
I am curious if there is a way to add command line args when executing my code in vs2008?

A: Right click the project in Visual Studio.  Click Properties.  On the Debugging page, there is a Command Arguments property.

A: Besides using the VS IDE to add parameters for running the program in the IDE, you can also open a command prompt window (Start | Run | cmd) and run the program the same as in Linux, except the .exe extension is optional:
 C:\Windows> cd "\Documents and Settings\Administrator\Applications\MyProject"
 C:\Documents and Settings\Administrator\Applications\MyProject> myprogram 23421232

A: Go into the Project Properties window for your executable project.
Under the "Debug" section, you can specify your command line arguments.  These will be used when debugging.

A: VS doesn't normally produce an executable named a.out like most Unix compilers do. Instead, given an input XXX.cpp, it'll produce an executable named XXX.exe.
Adding command line arguments is done by bringing up the project properties (Alt+F7), selecting "Debugging" and then entering the argument(s) in the "Command Arguments" control. There, you'll add JUST the argument "23421232" (or whatever).


text:
Q: Control what mouseenter does depending on element color I have made a nav bar that is originally white, but when the user scrolls down, it becomes transparent. When the nav bar is white at the top of the page, if the user hovers, it becomes transparent, and when his cursor leaves it returns to white. Now, logically, the same should happen when scrolled down, and it does. I don't want that to happen, instead I want the nav bar to stay transparent. So I've written the following code, but it is not working.
var color = $('.nav a').css("color")
    if (color == rgb (0,0,249) ) {
        $(".nav a").mouseenter(function(){
            $(".nav a").stop( true ).animate({
                backgroundColor: 'transparent',
            });

            $(".nav").stop( true ).animate({
                backgroundColor: 'transparent',
            });
        });

        $(".nav a").mouseleave(function () {
            $(".nav a").stop( true ).delay(300).animate({
                backgroundColor: 'white',
            });

            $(".nav").stop( true ).animate({
                backgroundColor: 'white',
            });
        });
    } else {

        $(".nav a").mouseenter(function(){
            $(".nav a").stop( true ).animate({
                backgroundColor: 'transparent',
            });

            $(".nav").stop( true ).animate({
                backgroundColor: 'transparent',
            });
        });

        $(".nav a").mouseleave(function () {
            $(".nav a").stop( true ).delay(300).animate({
                backgroundColor: 'transparent',
            });

            $(".nav").stop( true ).animate({
                backgroundColor: 'transparent',
            });
        });
    }

A: Taking a cue from here:
https://stackoverflow.com/a/7317489/3485669
I present to you a jsFiddle which toggles some classes based on the scroll position of the overall body element (obviously, your selectors will be specific to you):
https://jsfiddle.net/vyxhxq94/1/
The code snippet below does not, for some reason, render the CSS transitions. However, the jsFiddle does. (Edit: seems the rendered code snippet isn't recognizing the :hover CSS class when the mouse enters it)

$("div.body").on("scroll", function(e) {
 if ($("div.body").scrollTop() > 60) {
   $("div.nav").addClass("notAtTop").removeClass("atTop");
  } else {
   $("div.nav").addClass("atTop").removeClass("notAtTop");
  }
});
div.nav {
  position: fixed;
  width: 100%;
  top: 0%;
  left: 0%;
  z-index: 9999;
  -webkit-transition: all 0.3s ease;
  -moz-transition: all 0.3s ease;
  -o-transition: all 0.3s ease;
  transition: all 0.3s ease;
}

.atTop {
  background-color: white;
}
.atTop:hover {
  background-color: transparent;
}

.notAtTop {
  background-color: transparent;
}
.notAtTop:hover {
  background-color: transparent;
}

div.body {
  position: relative;
  background-color: green;
  margin-top: 60px;
  height: 100vh;
  overflow: scroll;
}
div.innerBody {
  height: 4000px;
}

  This is your nav bar.
  0

  This is the rest of your body.

  Some lengthy content...

A: Ok, I've found an answer using colors.
var trans=false;
// Navigation function
    $(".nav").mouseenter(function(){
        var colore="rgba(255, 255, 255, 0)";
        if($(".nav").css('background-color')==colore){
            trans=true;
        }else{
            trans=false;
        }
        $(".nav a").stop( true ).animate({
            backgroundColor: 'transparent',
        });

        $(".nav").stop( true ).animate({
            backgroundColor: 'transparent',
        });
    });

    $(".nav").mouseleave(function () {
        if(trans==false){
        $(".nav a").stop( true ).delay(300).animate({
            backgroundColor: 'white',
        });

        $(".nav").stop( true ).animate({
            backgroundColor: 'white',
        });
        }
    });


text:
Q: Awstats: awstats_buildstaticpages.pl only builds 1 report, not full reports I remember running this command before and it used to build all the pages, but now that I use it again it only builds the main page.
(new lines for readability)
/usr/share/awstats/tools/awstats_buildstaticpages.pl
-update
-config=mydomain.com
-dir=/var/www/awstats/mydomain.com/
-awstatsprog=/usr/lib/cgi-bin/awstats.pl

This is my awstats.mydomain.com.conf:
LogFile="/etc/nginx/logs/mydomain.com.log"
LogFormat=1
SiteDomain="mydomain.com"
DNSLookup=0
DirData="/var/lib/awstats/mydomain.com/"
HostAliases="mydomain.com"

The only file I get is awstats.mydomain.com.html
Does anyone know what is causing this? or am I missing something else?
I'm using Debian Squeeze x86

A: It seems that awstats_buildstaticpages.pl script doesn't replace Show* config options with its default values. So in order to all statistic files could be formed, you must determine (or uncomment default) values for options in awstats config file.
These are:

ShowSummary=UVPHB
ShowMonthStats=UVPHB
ShowDaysOfMonthStats=VPHB
ShowDaysOfWeekStats=PHB
ShowHoursStats=PHB
ShowDomainsStats=PHB
ShowHostsStats=PHBL
ShowRobotsStats=HBL
ShowSessionsStats=1
ShowPagesStats=PBEX
ShowFileTypesStats=HB
ShowOSStats=1
ShowBrowsersStats=1
ShowOriginStats=PH
ShowKeyphrasesStats=1
ShowKeywordsStats=1
ShowMiscStats=a
ShowHTTPErrorsStats=1
ShowFlagLinks=""
ShowLinksOnUrl=1


text:
Q: VB.NET to C++/CLI: How do I import a VB.NET DLL file into C++/CLI? I would like to import a VB.NET DLL file into C++/CLI. I am having trouble referencing my DLL file. I have tried to find tutorials but with no luck, in particular, I usually find how to import managed libraries directly into native code through COM. I would like to import an existing VB.NET DLL file into my C++/CLI project.
Do I require a header file or a declaration file to import and use my VB.NET DLL file?
Foo.vb
Public Module Foo
    Public Function Bar(ByVal a As Integer, ByVal b As Integer) As Boolean
        Return a > b
    End Function
End Module

Mixed.cpp
#include "stdafx.h"
#using "..\Foo\bin\Debug\Foo.dll"
using namespace System;

int main(array<System::String ^> ^args)
{
    bool i = Foo::Bar(10,1);
    Console::WriteLine(i);
    return 0;
}

A: Try looking at the discussion in Unmanaged C++ to C# interop (replacing CCW), especially Kuldeep_s last post. It's about accessing a C# DLL file from unmanaged C++ via managed C++. If you skip the umanaged C++ bit it would match your scenario (calling a C# DLL vs a VB.NET DLL shouldn't make any difference).


text:
Q: EMF figure has white spaces when screen resolution is 150% I am on Windows 7, tried Mathematica v9 and v11, both have the same issue when screen resolution is set to 150%:

EMF exported from a graph will come with white spaces on the bottom and right hand sides, like screen shot below. Other image types (PNG, JPG, BMP, PDF) are exported fine though. How do I work around this?
g = Plot[{Sin[x], Cos[x]}, {x, 0, 2 Pi},
  PlotStyle -> {Thickness[0.0], Thickness[0.01]}]
Export["g-150.emf", g]

A: Update: The problem is solved!
Apart from the three alternative resolutions 100%, 125% and 150% suggested on the right pane, there is the "Set custom text size (DPI)" item on the left pane:

When clicking on this item you get the following dialog:

Notice the "Use Windows XP style DPI scaling" checkbox - it is the key! But what it does? Citing this article (emphasis is mine),

Un-checking this checkbox causes Windows to use the desktop composition engine to perform DPI scaling for all applications that don't explicitly mark themselves as DPI aware via manifest. In this case, the composition engine will use your graphics hardware to scale the bitmap output of the window to a larger size, and apply an input transform to any mouse-clicks on the window to route them back to the right place in "real coordinates" for the application. The OS will also virtualize the system DPI for that application, so that it thinks it is running at 96DPI. This applies to most traditional Win32, GDI based applications.

This checkbox is checked by default when you select resolution 100% or 125% on the right, but it is un-checked when you select resolution 150%. Moreover, if you manually check this checkbox for resolution 150%, it will be un-checked automatically! But it will be kept checked if you enter, for example, resolution 160% in the "Scale to this percentage of normal size" combo box of the second dialog. After changing the resolution you need to log off the user and log on the user again for the changes to take effect, and you'll see that the problem with Export to EMF disappeared!

*

*A side note: according to the above citation, this checkbox shouldn't have effect on applications which correctly mark themselves as DPI aware via manifest. Therefore Mathematica version 11.0.1 either still isn't DPI aware or has a bug in how it marks itself as DPI aware...

So now we have at least a workaround. But what if you really need resolution exactly 150%? It is possible! By monitoring the system registry I've found that the "Use Windows XP style DPI scaling" checkbox in the second dialog corresponds to the "UseDpiScaling" DWORD key in HKEY_CURRENT_USER\Software\Microsoft\Windows\DWM. The value 0 corresponds to the checkbox being checked, and the value 1 corresponds to the un-checked checkbox.
A word of warning: modifying the system registry is a potentially dangerous operation which may damage your system. It is recommended to backup important data before you proceed.
For changing the value of this key, open the Windows Registry Editor and select HKEY_CURRENT_USER\Software\Microsoft\Windows\DWM key on le left:

Double click on the "UseDpiScaling" DWORD key on the right, enter 0 and press Enter. You'll see the following:

Now you need to log off the user and then log on the user again for the changes to take effect. Then check Export to EMF: now generated EMF figure has no white borders when pasted in MS Word:

Voilà!
P.S. Related articles:

*

*TechNet: Tip: Optimize Display Scaling and Fix Scaling Issues on Windows 7

*MSDN: Writing DPI-Aware Desktop and Win32 Applications

*SuperUser: High DPI screen & Windows: how to make programs behave as on low-res screens?

*Blurred frontend text in Mathematica 10, Windows, High-DPI Display

Original answer
I confirm this problem with Mathematica versions 5.2 (Export as WMF because this version doesn't support EMF export), 8.0.4, 10.4.1 and 11.0.1 on Windows 7 x64 when the system-wide screen resolution is set to 150% on the OS level. I've checked all the ways to produce a metafile (Export, Save Selection As…, Save Graphic As…, FrontEndTokenExecute[EvaluationNotebook[], "SelectionConvert", "Metafile"]) and got identical results: exported metafile has 50% white margin added at the right and at the bottom. Changing FrontEnd option FontProperties -> {"ScreenResolution" -> 72} doesn't affect this behavior. The problem doesn't appear when the system-wide screen resolution is set to 100% or 125%.
As a workaround I can suggest Exporting your plot as SVG or PDF and then using third-party utility like Inkscape (command line solution) for converting it into EMF. Note also that most versions of MS Office support EPS, hence another workaround is to switch to EPS instead of EMF.
I have found that it is possible to cure the exported EMF file using free EMFexplorer utility, but this method works only when the system-wide screen resolution is set to 100% or 125%. This observation indicates that we have a bug not in Mathematica, but in Windows 7 itself. It would be interesting to find out whether the bug is present in other versions of Windows.
Here is the procedure:

*

*Export your EMF (system-wide screen resolution is set to 150%):
g = Plot[{Sin[x], Cos[x]}, {x, 0, 2 Pi}, PlotStyle -> Thickness /@ {0, .01}];
Export["i.emf", g]

When pasted in MS Word the EMF file has white borders:

*On a computer with system-wide screen resolution 100% or 125% open the file in EMFexplorer, go to Document ► More Settings… menu item, set zero margins, and save as EMF again using the File ► Save Page As… menu item:

*Now paste new EMF file in MS Word:

The figure has no margins!


text:
Q: Custom Xcode Simulator Device / Size (e.g. 20x5) Ideally I would want to define my own Device for in the Simulator. Let's say 2000w x 500h.
Anybody know of any way to accomplish this?
You might be wondering, "why does he want to do that?" It's for prototyping, a non standard sized screen.
Some directions, but not sure if they can work:

*

*unlocking the aspect ratio of window resizing

*creating an own device

*changing the sizes of one of the existing devices


text:
Q: How to show a legend for a bar chart in Ruby on Rails? I am trying to show a simple bar chart, through canvas using jquery.
My code in the html.erb in my views is the following:

I use variables from the controller to import my labels and my data.
I would like to show a legend using this chart.
I tried many things:
the legend template in options
 legendTemplate:  "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%>
<span style=\"background-color:<%=datasets[i].strokeColor%>\"><%if(datasets[i].label){%><%=datasets[i].label%><%}%>
<%}%>
"

However I got syntax errors for unexpected "(" or "{" etc.
I also tried the chartjs-ror, however again I can not display the legend.
Can anyone help me to fix this problem?
Thanks in advance

A: Try this:
legendTemplate: <%= %Q{

        #{for (var i=0; i < datasets.length; i++)}
          #{if (datasets[i].label)}

              #{ datasets[i].label }

          #{end}
        #{end}

  } %>

or even better by using each:
legendTemplate: <%= %Q{

        #{datasets.each do |dataset|}
          #{if (dataset.label)}

              #{ dataset.label }

          #{end}
        #{end}

  } %>

A: paste the following code in yours
HTML

JS

   document.getElementById('js-legend').innerHTML = myChart.generateLegend();
CSS

.chart-legend li span{
    display: inline-block;
    width: 12px;
    height: 12px;
    margin-right: 5px;
}


text:
Q: Use a static variable or method for a constant array in Java I'm wondering if it is better to use a final static variable or method to provide a constant array in Java.
Say we have:
public class myColor {
    public final static String[] COLOR_NAMES = new String[] {"red", "green"};
    public final static String[] colorNames() {return new String[] {"red", "green"};}
}

To me, the second one has the disadvantage that each time it's called a new String array is created. But the first one has the disadvantage, that anyone could do COLOR_NAMES[0] = "blue".
To clarify: I specifically want to provide a list of color names for a subsequent match with regular expressions.
Is there any established way how this is typically solved?

A: You can use enum
public enum Color{

  RED("red"), GREEN("green");
   final String color;

  Color(String color) {
    this.color=color;
  }

  public String getColor() {
    return color;
  }
 }

A: This question is fall for using Enum. Personally I wont be using any method for that. But weather static array is good solution for that? It is better to solve it using java enums.

A: To initialise an array at construction time you can specify a list values in curly braces:
private static final String[] STRING_ARRAY = {"red", "green", "blue"};

In my example I have assumed that you won't want to change the instance of array and so have declared it final. You still would be able to update individual entries like so:
 array[0] = "1";

But you won't be able to replace the array with a different one completely. If the values are going to change a lot - especially if the number of values are going to change - then it may be worth considering using List instead.

A: If you can go with a list, one option would be:
public final static List<String> COLOR_NAMES = Collections.unmodifiableList(
                                                   Arrays.asList("red", "green"));

You can always get an array if needed:
String[] array = COLOR_NAMES.toArray(new String[0]);

Otherwise your second option is fine although I would write it:
private final String[] COLOR_NAMES = {"red", "green"};
public static String[] getColorNames() { return COLOR_NAMES.clone(); }


text:
Q: Static Field is not initialized (remains null) when being retrieved I have a class declared as follows:
public class Eq
{
    public bool Equals(ValI x, ValI y)
    {
        return nilnul.num.ord.Eq.Singleton.Equals( x , y);
        //throw new NotImplementedException();
    }

    public int GetHashCode(ValI obj)
    {
        return nilnul.num.ord.Eq.Singleton.GetHashCode(obj);
        throw new NotImplementedException();
    }

    static public  Eq Singleton=SingletonByDefault<Eq>.Instance;
}

while the SingletonByDefault looks like:
public class SingletonByDefault<YourClass>
    where YourClass:new()
    //where YourClass:class
{

    static protected  YourClass _Instance= new YourClass();
    static public YourClass Instance
    {
        get
        {
            return _Instance;
        }
    }

    protected SingletonByDefault() {

    }

}

In most cases when I access Eq.Singleton members, It's fine.
But on one occasion or another, I got a null reference exception which says Eq.Singleton is null.
when I change the static "Singleton" field of class Eq to follows:
//...
static public Eq Singleton{
    get{
         return SingletonByDefault<Eq>.Instance;
    }
}
//....

The exception is gone - at least for now.
I suspect the error is due to the sequence of static field initialization. For now my understanding is that:
1) Eq.Singleton and SingletonByDefault._Instance is initialized to null.
2) when I access Eq.Singleton, Eq.Singleton is intialized to SingletonByDefault.Instance, but
2.1) since now I'm accessing SingletonByDefault.Instance (which in turn accesses SingletonByDefault._Instance), SingletonByDefault._Instance is initialized to new Eq().
3) Eq.Singleton shall now return the "new-ed Eq()". but
3.1) why it's null?
So my understanding must go wrong some where. Anyone would give me some light?

A: Microsoft's own System.Lazy<> class provides the singleton pattern you need as follows.
public static class MySingletons
{
  private static Lazy<Eq> _eq = new Lazy<Eq>( CreateEq );

  private static Eq CreateEq()
  {
    return new Eq();
  }
  static public Eq Eq { get{ return _eq.Value; }}
}

// usage
var eq = MySingletons.Eq

Update: Here is a further level of generic wrapping as requested by the questioner. This eliminates some repetitive code where the singleton class supports a basic parameter less constructor.
public static class MySingletons
{
    static SingletonByLazy<Eq> _eq = new SingletonByLazy<Eq>();

    static public Eq Eq
    {
        get
        {
            return _eq.Singlton;
        }
    }
}
public class SingletonByLazy<T> where T: new()
{
    Lazy<T> _singltonWrapped = new Lazy<T>( CreateSingleton );

    static T CreateSingleton()
    {
        return new T();
    }
    public T Singlton
    {
        get
        {
            return _singltonWrapped.Value;
        }
    }
}


text:
Q: Thread vs CompletableFuture What is the advantage of passing code directly to thread vs using  CompletableFuture instead?
Thread thread = new Thread(() -> {do something});
thread.start();

VS
CompletableFuture<Void> cf1 =
     CompletableFuture.runAsync(() -> {do something});

A: @Gerald Mücke already mentioned the important difference:

CompletableFuture.runAsync(...) runs the Runnable in the forkJoin-Pool which is managed, while new Thread() creates a new thread which you have to manage.

CompletableFuture will use threads managed by a ThreadPool (default or customized).
However, I think the following two points are also should be considered.
First
CompletableFuture has so many easily understandable methods to chain different asynchronous computations together, making it much easier to introduce asynchrony than directly using Thread.
CompletableFuture[] futures = IntStream.rangeClosed(0, LEN).boxed()
            .map(i -> CompletableFuture.supplyAsync(() -> runStage1(i), EXECUTOR_SERVICE))
            .map(future -> future.thenCompose(i -> CompletableFuture.supplyAsync(() -> runStage2(i), EXECUTOR_SERVICE)))
            .toArray(size -> new CompletableFuture[size]);
CompletableFuture.allOf(futures).join();

Second
You should never forget to handle exceptions; with CompletableFuture, you can directly handle them like this:
completableFuture.handle((s, e) -> e.toString()).join()

or take advantage of them this way to interrupt the computation:
completableFuture.completeExceptionally(new RuntimeException("Calculation failed!"));

while you will easily encounter some serious problems using Thread.

A: CompletableFuture.runAsync(...) runs the Runnable in the forkJoin-Pool which is managed, while new Thread() creates a new thread which you have to manage.
What does "is managed" mean, it's pre-allocated and the threads are shared in the JVM. When the runnable is completed, the thread can be reused for other runnables. This makes better usage of resources, especially as thread instantiation is an expensive operation - not only the object, but also some extra non-heap memory - the thread stack - has to be allocated.

A: CompletableFuture is a promise which uses default ForkJoinPool (thread pool of size equal to number of CPU's) unless provided with another ThreadPool. A thread pool will contain n or more number of Thread.


text:
Q: Negative Lookahead for word I have been banging my head against the wall on this one, I am fairly new to regex and am a bit out of my depth. I am working with this network compliance software that doesn't allow for matching multiple criteria in a field however does accept regular expressions.
!(?!.*FastEthernet[0-24].[0-24]\.[0-250])

The software parses all information until it matches the expressed criteria. So in my case I want it to match ! unless it is followed by a sub interface FastEthernet#/#.# where # is any number.
Here is my data
interface FastEthernet0/0
shutdown
!
interface FastEthernet0/0.100
ip address 192.168.1.100
!
interface FastEthernet0/1
shutdown
!

A: This should do it:
!(?!\s*interface FastEthernet\d/\d\.\d)

See this running on rubular

A: I would use this:
!(?!(.|\n|\r)*FastEthernet\d\d?\/\d\d?\.\d{1,3})

It seems to work for me.


text:
Q: Stack In C - incompatible type 'int' I have this code right here. I'm trying to implement but I got and error and I've not idea how I can get rid of it. It's a stack. I gotta call the function to insert the values in it but the compiler keeps showing this error and don't let me do anything else.
Passing 'pilha' to parameter of incompatible type 'int'
pilha * cria_pilha(){
    pilha *pi;
    pi = malloc(sizeof(pilha));

    if (!pi) {
        pi -> topo = 0;
    }
    return pi;

}

and I'm trying to call it here.
int main (int argc, const char * argv[]){
    //Cria vetor de struct preenchido com a quantidade MAX_ELEMENTOS
    pilha * pi = cria_pilha();
    pilha p[MAX_ELEMENTOS] = {1, 2, 3, 4, 5,
                             6, 7, 8, 9, 10};

    //Call the function Stack, then pass by argument p[]
    //stacking the values MAX_ELEMENTS times.

    for (int i = 0; i < MAX_ELEMENTOS; i++) {
        //The error happens here. I already identified the cause but
        //I've got no idea how to solve it. Any help please?
        empilha(pi, p[i]);  --  Passing 'pilha' to parameter of incompatible type 'int'
    }

    for (int i = 0; i < MAX_ELEMENTOS; i++) {
        desempilha(pi);
    }
}

I'm calling the function int empilha(pilha *pi, int p); which, by my understanding has pilha *pi that is no compatible with the type of int. How can I solve this issue?
Here's my whole code.
#include <stdio.h>
#include <stdlib.h>
#define MAX_ELEMENTOS 10

typedef struct {
    int elementos[MAX_ELEMENTOS];
    int topo;
} pilha;

pilha * cria_pilha(){
    pilha *pi;
    pi = malloc(sizeof(pilha));

    if (!pi) {
        pi -> topo = 0;
    }
    return pi;

}

int empilha(pilha *pi, int p);
int desempilha(pilha *pi);
int tamanho (pilha *pi);
void destroi(pilha *pi);

int main (int argc, const char * argv[]){
    //Cria vetor de struct preenchido com a quantidade MAX_ELEMENTOS
    pilha * pi = cria_pilha();
    pilha p[MAX_ELEMENTOS] = {1, 2, 3, 4, 5,
                             6, 7, 8, 9, 10};

    //Chama função empilhar, passa por argumento o velho p[]
    //para função empilha MAX_ELEMENTOS vezes.
    for (int i = 0; i < MAX_ELEMENTOS; i++) {
        empilha(pi, p[i]);
    }

    for (int i = 0; i < MAX_ELEMENTOS; i++) {
        desempilha(pi);
    }

}

int empilha(pilha *pi, int p){
    if (pi == NULL || pi -> elementos == ((int*)MAX_ELEMENTOS)) {
        printf("Erro, pilha cheia.\n");
        return 0;
    }

    pi -> elementos[pi->topo] = p;
    pi -> topo = pi -> topo + 1;
    return 1;
}

int desempilha(pilha *pi){
    if (pi == NULL || pi -> elementos[0] == 0) {
        return 0;
    }

    pi -> topo = pi -> topo -1;
    return pi -> elementos[pi->topo];
}

int tamanho(pilha *pi){
    return pi -> topo;
}

void destroi(pilha *pi){
    free(pi);
}

A: In this call
empilha(pi, p[i]);

the second argument has the type pilha due to this declaration
pilha p[MAX_ELEMENTOS] = {1, 2, 3, 4, 5,
                         6, 7, 8, 9, 10};

but the function expects an argument of the type int
int empilha(pilha *pi, int p);

Pay attention to that it is a bad idea to name identifiers using non-English words. The code in such a case is unreadable.
Also using initializers without braces to initialize aggregates makes the code error-prone and unclear.

A: regarding:
pilha *pi;
pi = malloc(sizeof(pilha));

if (!pi) {
    pi -> topo = 0;
}

when the if() is true, then the call to malloc() failed and pi contains NULL.
when the call to malloc() fails, then pi -> topo = 0; is trying to write to an address just above address 0x00.
This results in undefined behavior and the assignment should result in a seg fault event.
regarding:
for (int i = 0; i < MAX_ELEMENTOS; i++) {
    empilha(pi, p[i]);
}

this code block and the function: empilha() can be replaced with:
memcpy( pi->elementos, p, MAX_ELEMENTOS * sizeof( int ));

OT: in function: empilha(), this:
if (pi == NULL || pi -> elementos == ((int*)MAX_ELEMENTOS)) {
    printf("Erro, pilha cheia.\n");
    return 0;
}

should already have been checked before calling this function.
OT: regarding:
printf("Erro, pilha cheia.\n");

error messages should be output to stderr, not stdout. Suggest:
fprintf( stderr, "Erro, pilha cheia.\n");

regarding the expression:
((int*)MAX_ELEMENTOS)

this is the same as:
int *10;

Definitely not what you want and this verifies nothing


text:
Q: I can't underestand how move semantics work to std::string explicit Foo(std::string p_str) : m_str(std::move(p_str)) { ... }

Full source code
I've made a constructor takes argument with move semantics. (p_str -> m_str) For a closer look, I opened the library header file basic_string.h but there is one thing that I can't understand.
basic_string(basic_string&& __str) noexcept :
         _M_dataplus(_M_local_data(), std::move(__str._M_get_allocator())) {
     if (__str._M_is_local()) {
         traits_type::copy(_M_local_buf, __str._M_local_buf, _S_local_capacity + 1);
     } else {
         _M_data(__str._M_data());
         _M_capacity(__str._M_allocated_capacity);
     }

     _M_length(__str.length());
     __str._M_data(__str._M_local_data());  // (#)
     __str._M_set_length(0);
 }

This is move constructor of basic_string class. After (#) is executed, p_str turns to ".\000\000\000\000\000\000\000...". As I know, basic_string stores strings in the array _M_local_buf and method _M_local_data() returns its address.
Then, why __str._M_data(__str._M_local_data()); changes p_str to zero-filled string? Isn't p_str(__str) still having the original strings?

A: What you're seeing is short string optimization.
libstdc++'s std::string implementation has two places it can store string data.  It stores long strings in a dynamically allocated array of chars.  To avoid the overhead of allocating that array, it can also store short strings in the space it usually uses to track the size of that dynamically allocated array.  That's _M_local_data.
_M_dataplus._M_p holds a pointer to the first element of whicherver buffer is currently in use.  That's the pointer that _M_data() returns, and the pointer that _M_data(pointer) sets.
So putting that together, doing
__str._M_data(__str._M_local_data());
__str._M_set_length(0);

is telling the moved-from string "Forget about any buffer you were previously managing, start using your local buffer for storage, and assume you hold no data".

Then, why __str._M_data(__str._M_local_data()); changes p_str to zero-filled string?

It doesn't.  It changes p_str's data pointer to point to the memory that previously held the size of its externally-allocated array.  What you're seeing are the leftovers of that capacity (Did p_str have a capacity of 46 by chance?  That's the ASCII code point for '.').  For the moment between those two lines, p_str is in an inconsistent state.  Its size is still set to its previous size, but the buffer it now points to doesn't hold that number of characters.  That gets rectified on the next line when the move constructor sets its length to 0.

A: Your std::string stores its contents in one of two ways:

*

*If the string is short, it is stored directly in _M_local_buf, which is presumably an array member of std::string (and also accessible via _M_local_data()).

*If the string is long, a char array is allocated separately and a pointer to it is stored in _M_p (which is also accessible via _M_data()).

The if statement deals with the two possible representations:

*

*If the contents are stored directly in the std::string object (__str._M_is_local()), we copy the data into our own _M_local_buf array.

*Otherwise we simply copy the pointer (as returned by _M_data()) and capacity.
Right now our objects are in an inconsistent state: Both this->_M_data() and __str._M_data() point to the same allocated storage; they both "own" it. To resolve this situation, we need to reset __str so it won't try to free our string data out from under us when it is destroyed. We'll do that in a second.
_M_length(__str.length()); copies over the length value from __str.
__str._M_data(__str._M_local_data()); makes _M_p point to the internal array that is part of the __str object. If __str wasn't a short string to begin with, this array contains garbage. But that doesn't matter, because:
__str._M_set_length(0) resets the length of __str to 0. The contents of __str._M_local_buf don't matter because 0 of them are "valid", i.e. part of the string.
In short: This move constructor copies the member variables of __str into our new object, then makes __str an empty string. (The string contents have been "moved" from __str into *this, so now __str is empty.)
This is a general principle: Moving from a variable destroys its contents. It will be a valid object (a valid std::string in this case), but you cannot rely on any data still being there.


text:
Q: Reversed Positional Parameters I'd like to use positional parameters for a PowerShell script I'm writing, but I want the parameters to be entered from right to left (with one being mandatory and one named). Here's an example of what it'd look like:
command [-namedParams andTheirValues] [[param3] param2] param1

Or for each use case separately:
command [-namedParams andTheirValues] param1
command [-namedParams andTheirValues] param2 param1
command [-namedParam andItsValue] param3 param2 param1

I attempted to use [parameter(Position=n)] with negative indexes (since what I really want is to bind parameters based on their position to the end) but that didn't work:
param (
    [String]$namedParam,
    [parameter(Position=-3)][String]$param3,
    [parameter(Position=-2)][String]$param2,
    [parameter(Mandatory=$True,Position=-1)][String]$param1
)

Any ideas? If I need to I'll just process the arguments in code, but I'm hoping for syntactical sugar to do this for me.

A: Interesting question......As you have discovered you cannot use negative values for defining positional arguments. Closest I found for a reference for this was from about_Functions_Advanced_Parameters:

The value of the Position argument is specified as an integer. A position
          value of 0 represents the first position in the command, a position
          value of 1 represents the second position in the command, and so on.

That would be the best support for the lack of negative values. Documentation could be wrong but as you experimented it does not work.
However, I think I figured out an easy way to deal with this. Consider the following function which contains both named and "positional"ish parameters. We use the advanced function parameter ValueFromRemainingArguments. Note that I used quotes several times in this answer around "positional" since they are not true positional parameters.
function Das-Bagel{
    param (
        [String]$namedParam,
        [parameter(Mandatory=$true,
                      ValueFromRemainingArguments=$true)]
        [String[]]$remainingArguments
    )

    $param1 = $remainingArguments[-1]
    $param2 = $remainingArguments[-2]
    $param3 = $remainingArguments[-3]

    Get-Variable -Name param* | select name, value
}

All it will do is display the param# variables and their values. That being said lets look at the output from these 2 different commands. First with only the one "positional" parameter.
PS C:\Users\Cameron> Das-Bagel -namedParam This First

Name   Value
----   -----
param1 First
param2
param3

Now we run with 3 "positional" parameters
PS C:\Users\Cameron> Das-Bagel -namedParam This First Second Third

Name   Value
----   -----
param1 Third
param2 Second
param3 First

The first has only the one other parameter beyond the named therefore it goes in the first position. In the second example it becomes the third parameter. Parameters not present will show as nulls for their respective variables. PowerShell is nice in that way in that it will not cause an error (be default). You would need to account for that possibility in your code but I imagine you have that covered.
Also since we made it mandatory the function call would fail if we omitted the "positional" parameters.


text:
Q: Http 404 Not Found error I have created a number of controllers and each of them returns a number of views.
The views get displayed successfully on the browser upon entering the url, for example:
/localhost:21419/Accounting/Index
There is no problem with displaying views for any of the controller views except one(named OrderController)
For this OrderController, I get a 404 error when I enter the url on the browser. for example: /localhost:21419/Order/Index.
The only time I get a page display is when I enter /localhost:21419/Order (the Index page gets displayed).
But when I enter /localhost:21419/Order/Index, I get the same error. I tried creating a new action method and a view corresponding to it, but none of the views under this controller are getting rendered. What might be the problem?
My Global.asax.cs :
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        RouteTable.Routes.MapHubs();
        AreaRegistration.RegisterAllAreas();
        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}

My RouteConfig.cs (I added namespaces as well)
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    namespaces: new[] {"RRRPropPres.WebUI.Controllers"}
    );
}

What might be the reason it doesn't work for one controller alone?
I tried
return View();

and
return View("name of View");

Nothing seems to help.

A: It's all about your route config.
This is a basic default route :
routes.MapRoute(
            "SomeName", // Route name
            "/{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

I suggest to remove namespaces: new[] {"RRRPropPres.WebUI.Controllers"}.
also you it's better to define defaults like this: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
if id is optional and you don't send it in some requests id = UrlParameter.Optional is necessary.
if you are working with Areas, it's better to disable UseNamespaceFallback like this :
routes.MapRoute(
        ...
    ).DataTokens["UseNamespaceFallback"] = false;

A: If the route works fine for other controllers, it will not be a problem with routes.  You are getting a 404 and I doubt you do not have Index view under Order section.  Click on the views->Order and see if Index is present.  If no, we have to create one or we need to go further with your controller code.  I could help further if you paste your controller code.  The code snippets you pasted look all right.  Right clicking on the controller and creating views might have placed your view in a different folder.


text:
Q: heroku static resources nodejs I hosted my nodejs project on heroku and it deployed successfully,but i am unable to load any static resources from public or node_modules folder.Tried some hacks of putting some lines of code in app.js and other but nothing works.Tried process.cwd() approach too ,but failed. I have done this for the first time.Please Help.
    var createError = require('http-errors');
    var express = require('express');
    var path = require('path');
    var cookieParser = require('cookie-parser');
    var logger = require('morgan');
    var fs = require('fs');
    var cookieParser = require('cookie-parser');
    var bodyParser = require('body-parser');
    var indexRouter = require('./routes/index');
    var usersRouter = require('./routes/users');
    var app = express();
    var http = require('http').Server(app);
    process.env.PWD = process.cwd();
    // view engine setup
    app.use('/scripts', express.static(path.join(process.env.PWD, 'node_modules')));
    app.use('/jsonfiles', express.static(path.join(process.env.PWD, 'jsonfiles')));
    app.set('views', path.join(process.env.PWD, 'views'));
    app.use(express.static(path.join(process.env.PWD, 'public')));

    app.set('view engine', 'ejs');

    app.use(logger('dev'));
    app.use(express.json());
    app.use(express.urlencoded({ extended: false }));
    app.use(cookieParser());

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(cookieParser());

    app.use('/', indexRouter);
    app.use('/users', usersRouter);

    // catch 404 and forward to error handler
    app.use(function(req, res, next) {
      next(createError(404));
    });
    http.listen(process.env.PORT || 8000, function() {
        console.log('listening on *:8000');
    });

    // error handler
    app.use(function(err, req, res, next) {
      // set locals, only providing error in development
      res.locals.message = err.message;
      res.locals.error = req.app.get('env') === 'development' ? err : {};

      // render the error page
      res.status(err.status || 500);
      res.render('error');
    });

    module.exports = app;


text:
Q: Editing size of image without loosing its quality and dimensions I have a image with size of 5760 x 3840px with size of 1.14mb. But I would like to reduce its size to 200 kb by not changing the dimensions of the image. How Could I do this using photoshop? Please help me

A: This answer is based on a large format file size that has a resolution of 300 dpi. If the image is 5760 x 3840, your canvas size will be 19.2 x 12.8. in order to not "reduce" the dimension (printable area) you are going o have to reduce the image size [ALT + CTRL/CMD + I] and then reduce the resolution from there.
At 300 DPI:

At 72 DPI:

This reduction in resolution can decrease the file size dramatically, There is a chance of artifacts, but as you are starting at a high resolution the compression algorithms will smooth it out to almost non-existent.
NOW... If you are starting at 72dpi and you are looking for a good way to generate a lower file size for the web, your best bet may be to do a Safe for web option [ALT + CTRL/CMD + SHIFT + S] and generat a .jpg, .gif or a .png based on the final needs of the file. If it is an photograph with a lot of colors, I would go .jpg. If you have a lot of areas of solid color (logo perhaps) I would go with .png or .gif.

The Save for Web option allows you to see, side by side, the results of the export BEFORE going through the save process. it also allows you to alter the settings of the save process to dial in your results. best of all, it gives you a pretty good preview of the expected file size.
Either way this should help you save that larger file size for future use.


text:
Q: Authorization failed. doesn't raise exception? I created a server-side blazor application with Windows authentication. It works fine and returns the data from the database when running using IIS Express in Visual Studio 2019.
try
{
    var filtered = _context.Trades
        .Where(.....)
        .ToListAsync(cancellationToken)
        .ConfigureAwait(false);
    // ....
}
catch (Exception ex)
{
    // .... will display the exception message
}

Then I changed it to Kestrel. I expected to raise exception because I haven't do anything to make Kestrel to work with Windows authentication.
However, it doesn't raise any exception. The following information can be found in the output window.

Microsoft.AspNetCore.Authorization.DefaultAuthorizationService: Information: Authorization failed.

How to make sure it raises the exception?
BTW, how to make Kestrel works with Windows authentication?

Startup.cs updated for the answer.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using BlazorApp1.Data;
using Microsoft.AspNetCore.Authentication.Negotiate;

namespace BlazorApp1
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddAuthentication(NegotiateDefaults.AuthenticationScheme).AddNegotiate();

            services.AddSingleton<WeatherForecastService>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
            });
        }
    }
}

A:
How to make sure it raises the exception?

If you enabled the windows auth for the IIS, the request will not come to your codes, the IIS will refuse the request, so you will not get any exception message. To check this, you should check the IIS logs.

BTW, how to make Kestrel works with Windows authentication?

According to your description, I guess you just enabled the windows auth for the IIS not the Kestrel. So if you directly run the application form the Kestrel, it will not use windows auth.
To solve this issue, I suggest you could follow below steps to enable the windows auth for your asp.net core application.
1.Install the Microsoft.AspNetCore.Authentication.Negotiate package

*Add below codes into the Startup.cs ConfigureServices method
     services.AddAuthentication(NegotiateDefaults.AuthenticationScheme).AddNegotiate();

*Add below codes into the Startup.cs Configure method
    app.UseAuthentication();
    app.UseAuthorization();

4.Then you could use dotnet run to test your application. You will find the windows auth will be enabled for your application.

If you used the Windows authentication in the  Kestrel, you need to force the page to allow only login in user. To achieve this, I suggest you could add the  Authorize attribute in the _Host.cshtml.
Details, you could refer to below _Host.cshtml.
@page "/"
@using Microsoft.AspNetCore.Authorization
@attribute [Authorize]
@namespace BlazorWindowsAuth.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>BlazorWindowsAuth</title>
    <base href="~/" />
    <link rel="stylesheet" href="css/bootstrap/bootstrap.min.css" />
    <link href="css/site.css" rel="stylesheet" />
</head>
<body>
    <app>
        @(await Html.RenderComponentAsync<App>(RenderMode.ServerPrerendered))
    </app>

    <script src="_framework/blazor.server.js"></script>
</body>
</html>


text:
Q: PHP, how to create count down timer? How to do this:
"you will be redirected to domain.com in 5..(4,3,2,1) seconds"
in php???

A: You should use javascript to visualize a countdown, in php you can set a timer for the redirection like this:
header('refresh: 5; url=http://www.stackoverflow.com');

where refresh: x set the time in seconds to wait for the redirection.

A: Short answer: You can't.
Long answer: PHP is serverside and as such as soon as the page is sent PHP has nothing to do with it. What you're looking for is possible in a number of ways. You can either use javascript (which allows you to do the 'visual' countdown) or set the meta refresh tag in the  element of your document, as such: <meta http-equiv="refresh" content="5;url=http://yoursite.com">

A: You can implement a Javascript countdown with the setInterval() function, called every second for 5 seconds to create a timer function to count down the time. When the time has elapsed, then you can use the document's location.href property to redirect the user to the page; it would also be beneficial to create a hard link to direct them to the page, in case Javascript is turned off, for instance.
For example:
var timeLeft, id;

function startCountDown()
{
    timeLeft = 5;
    id = setInterval(countDown, 1000);
}

function countDown()
{
    timeLeft -= 1;

    //Update the text which states how much time is remaining until the
    //user is redirected here..

    if(timeLeft==0)
    {
        clearInterval(id);

        //Redirect to the desired URL
        document.location.href = "http://domain.com";
    }
}

A: I'm pretty sure javascript is your best option. The only other way to do it would be to redirect to a new URL every second, which is overkill in my opinion.
Here's full source code for a sample countdown:

    <meta http-equiv="refresh" content="5;url=http://example.com" />
    <title>Countdown Sample</title>

    you will be redirected to example.com in 5.

Edit
Here's an improved version with Alnitak's advice:
I've changed the JavaScript to redirect users and prevent the countdown from going below 1 and I've added a  tag around the <meta> for users without JavaScript.

      <meta http-equiv="refresh" content="5;url=http://example.com" />

    <title>Countdown Sample</title>

    you will be redirected to example.com in 5.

A: This is best not done in PHP, because it would require the web server to keep the connection to the client open while the count down runs.
This would (IMHO) be far better done in Javascript with setInterval().

A:

        Thank you for your feedback

                function timer(stamp)
                {
                    var temp=stamp;
                    temp=temp-1;
                    document.getElementById('mylbl').innerHTML = temp;
                    if(temp<=0)
                    {
                        window.location = "http://www.tasolglobal.com"
                        exit();
                    }
                    setTimeout("timer("+temp+")",1000);
                }

    </script>

    <?php
        //$sec=5;
        $to=$_REQUEST['from'];          //Set your email address where you want to get feedback
        $from=$_REQUEST['from'];        //This will be the senders email add
        $message=$_REQUEST['mesg'];     //This contains message from feed fackback form
        $subject=$_REQUEST['subject'];      //This contains subject of Feedback form. You can also set value as                                     feedback so you can find feedback mail easily
        $header="From: $from";          //Header of the feedback mail
        mail($to,$subject,$message,$header);

        echo "

Thank You For Your Feedback...

Your Will Be Redirected To HOME PAGE... Within ";
            echo "" ;
        echo " Seconds";
    ?>

A: You can mix javascript and php, when you enter page you get a date you need to countdown to from database through php and then count it down with javascript. Something like that is used by http://free-countdown.co.nr/


text:
Q: Under what situation would muting an  element also affect its srcObject's connected nodes? I realize that the title may be a little confusing, so let me give some context.
I'm writing an extension to do some audio manipulation with Google Meet, and, after studying its behavior, I found a weird issue that I can't seem to wrap my head around.
Google Meet seems to use three <audio> elements to play audio, with each one having their own MediaStreams. Through some testing, it seems that:

*

*Muting the <audio> element stops Google Meet's audio visualizations as to who is talking.

*Swapping the .srcObject properties of two audio elements and then calling .play() on them does not affect Google Meet's audio visualizations.

These seem to point to Google Meet connecting the source MediaStream into its audio processing graph to create the visualizations rather than capturing the <audio> element, since I can swap MediaStreams without affecting the visualizations.
However, one more thing that I noticed seem to make no sense considering the past information:

*

*Adding a new MediaStreamAudioSourceNode from the .srcObject of the <audio> element and connecting it to an AnalyserNode showed that, even when I mute the <audio> element, I can still analyse the audio being played through the MediaStream.

Here's some example code and outputs done through the browser console:
ac = new AudioContext();
an = ac.createAnalyser()
sn = ac.createMediaStreamSource(document.querySelectorAll("audio")[0].srcObject)
sn.connect(an)
function analyse(aNode) {
  const ret = new Float32Array(aNode.frequencyBinCount);
  aNode.getFloatTimeDomainData(ret);
  return ret;
}

analyse(an)
// > Float32Array(1024) [ 0.342987060546875, 0.36688232421875, 0.37115478515625, 0.362457275390625, 0.35150146484375, 0.3402099609375, 0.321075439453125, 0.308746337890625, 0.29779052734375, 0.272552490234375, … ]

document.querySelectorAll("audio")[0].muted = true
analyse(an)
// > Float32Array(1024) [ -0.203582763671875, -0.258026123046875, -0.31134033203125, -0.34375, -0.372802734375, -0.396484375, -0.3919677734375, -0.36328125, -0.31689453125, -0.247650146484375, … ]

// Here, I mute the microphone on *my end* through Google Meet.

analyse(an)
// > Float32Array(1024) [ -0.000030517578125, 0, 0, -0.000030517578125, -0.000091552734375, -0.000091552734375, -0.000091552734375, -0.00006103515625, 0, 0.000030517578125, … ]
// The values here are much closer to zero.

As you can see, when the audio element is muted, the AnalyserNode can still pick up on the audio, but Meet's visualizations break. That is what I don't understand. How can that be?
How can a connected AnalyserNode not break when the <audio> element is muted, but something else is, without using .captureStream()?
Another weird thing is that it only happens on Chrome. On Firefox, Meet's visualizations work fine even if the audio element is muted. I think this might be related to a known Chrome issue where MediaStreams require a playing <audio> element to output anything to the audio graph (https://stackoverflow.com/a/55644983), but I can't see how that would affect a muted <audio> element.

A: It's a bit confusing but the behavior of AudioElement.captureStream() is actually different from using a MediaElementAudioSourceNode.
new MediaStreamAudioSourceNode(audioContext, audioElement.captureStream());

// is not equal to

new MediaElementAudioSourceNode(audioContext, audioElement);

The stream obtained by calling AudioElement.captureStream() is not affected by any volume changes on the audio element. Calling AudioElement.captureStream() will also not change the volume of the audio element itself.
However using a MediaElementAudioSourceNode will re-route the audio of an audio element into an AudioContext. The audio will be affected by any volume changes that are made to the audio element. Which means muting the audio element will result in muting the audio that gets piped into the AudioContext.
On top of that using a MediaElementAudioSourceNode will make the audio element itself silent.
I assume Google Meet uses a MediaElementAudioSourceNode for each audio element to process the audio.


text:
Q: PHP code isn't submitting into mysql database I'm trying to create a login for a website. So far whenever I post to my database doesn't show the submitted information, the only things which are posted is a hashed password.
<form method="post" action="submit.php">

                            Email:
                            <input type="email" class="form-control" id="email">

                            Username:
                            <input type="text" class="form-control" id="username">

                            Password:
                            <input type="password" class="form-control" id="password">

                            Re-Password
                            <input type="password" class="form-control" id="pwd2">

                            <input type="submit" class="form-control" id="submit">

                    </form>

To submit into this php block
<?php
    $servername = "localhost";
    $username = "root";
   $password = "Password";
   $dbname = "DBNAME";

   $email = NULL;
   $user = NULL;
   $pass1 = NULL;

   if (isset($_POST['email'])){
   $email = $_POST['email'];
    }
   if (isset($_POST['username'])){
   $user = $_POST['username'];
   }

    if (isset($_POST['password'])){
   $pass1 = $_POST['password'];
   }
  $hash = password_hash($pass1, PASSWORD_BCRYPT);

   $conn = new mysqli($servername, $username, $password, $dbname);

   if ($conn->connect_error) {
   die("Connection failed: " . $conn->connect_error);
   }

   $sql = "INSERT INTO Users (email, username, password )
   VALUES ('$email', '$user', '$hash')";

   if ($conn->query($sql) === TRUE) {
   echo "New record created successfully";
   } else {
   echo "Error: " . $sql . "
" . $conn->error;
    }

  $conn->close();
  ?>

A: Your form fields lack name attributes. Without them no values are sent your your script. This is easily testable by doing var_export($_POST).
<form method="post" action="submit.php">

        Email:
        <input type="email" class="form-control" name="email" id="email">

        Username:
        <input type="text" class="form-control" name="username" id="username">

        Password:
        <input type="password" class="form-control" name="password" id="password">

        Re-Password
        <input type="password" class="form-control" name="pwd2" id="pwd2">

        <input type="submit" class="form-control" id="submit">

</form>

FYI, you are wide open to SQL injections


text:
Q: syntax error missing operator in query expression "Username = and level like '%instructor%' this code below"" is working if its in "search button" but I would like to use this in "Load form" that when i run it should automatically display data into datagridview which giving error on the above mentioned. any suggestion would be appreciated.
 Private Sub Search_Record()
    Dim conn As New OleDbConnection
    Dim cmd As New OleDbCommand
    Dim da As New OleDbDataAdapter
    Dim dt As New DataTable
    Dim sSQL As String = String.Empty
    Try
        conn = New OleDbConnection(Get_Constring)
        conn.Open()
        cmd.Connection = conn
        cmd.CommandType = CommandType.Text
        sSQL = "SELECT Username, lname + ', ' + fname + ' ' + mname as name, password FROM Instructor"
        If Me.cboSearchBy.Text = "Name" Then
            sSQL = sSQL & " where lname + ', ' + fname + ' ' + mname like '%" & Me.txtSearch.Text & "%'"
            sSQL = sSQL & " and  level like '%instructor%'"
        Else
            sSQL = sSQL & " where Username =" & Me.txtSearch.Text
            sSQL = sSQL & " and  level like '%instructor%'"
        End If
        cmd.CommandText = sSQL
        da.SelectCommand = cmd
        da.Fill(dt)
        Me.dtgResult.DataSource = dt
        If dt.Rows.Count = 0 Then
            MsgBox("No record found!")
        End If
    Catch ex As Exception
        MsgBox(ErrorToString)
    Finally
        conn.Close()
    End Try
End Sub

A: When the form starts and there is no text in the txtSearch textbox your query becomes syntactically wrong. If you had used a parameterized query you would have avoided this error.
(Not to mention the famigerate Sql Injection problem)
Using conn = New OleDbConnection(Get_Constring)
Using cmd = new OleDbComman()
    conn.Open()
    cmd.Connection = conn
    sSQL = "SELECT Username, lname + ', ' + fname + ' ' + mname as name, password FROM Instructor"
    If Me.cboSearchBy.Text = "Name" Then
       sSQL = sSQL & " where lname + ', ' + fname + ' ' + mname like ? and  level like ?"
    Else
       sSQL = sSQL & " where Username = ? and  level like ?"
    End If
    cmd.CommandText = sSQL
    cmd.Parameters.AddWithValue("@1", "%" & txtSearch.Text & "%")
    cmd.Parameters.AddWithValue("@2", "%instructor%")
    Using da = new OleDbDataAdapter(cmd)
       da.Fill(dt)
       Me.dtgResult.DataSource = dt
       If dt.Rows.Count = 0 Then
           MsgBox("No record found!")
       End If
    End Using
End Using

Also, if you are using an MS-Access database keep in mind that PASSWORD is a reserved keyword and you need to encapsulate it between square brackets when used in query like the one above.
SELECT ......., [Password] ........


text:
Q: Controller/actuator to perform database actions by URL, loop never-ending I'm writing a simple AJAX/jquery CMS for a website i'm building. To simplify everything, I want to simply make requests to URLs to perform actions (much like what Magento has - but I have my reasons not to use Magento/other existing options)
The problem is that the while loop doesn't end (and at the time of writing the PHP docs are timing out where I am so I can't access them).
<?php
$query = explode('/',parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
$qs = array();
foreach ($query as $key=>$value) $qs[$key] = urldecode(htmlspecialchars($value));

# /action/{$class-name}/{$action}/{$field1}/{$param1}/{$field2}/{$param2}/.../{$fieldN}/{$paramN}
# e.g.
# /action/QuickOverview/get/internal_name/value
# /action/QuickOverview/update/internal_name/value1/title/value2/

$params = array();
array_shift($qs);
switch ($val = array_shift($qs)) {
    case "action":
        $className = array_shift($qs);
        $action = array_shift($qs);
        $field = true;
        while ($val=array_shift($qs)!==false) {
            if ($field) $params[-1] = $val;
            else $params[$params[-1]] = $val;
            $field = !$field;
        }
        unset($params[-1]);
        break;
    default:
        var_dump("Unknown value: ".$val);
        break;
}

var_dump($params);
?>

The page times out (probably looping forever), how can I end this while loop correctly?

A: = is an assignment operator and shouldn't be used for a condition check, this case in the while loop.
Try:
switch ($val = array_shift($qs)) {
case "action":
    $className = array_shift($qs);
    $action = array_shift($qs);
    $field = true;
    while ($val == array_shift($qs)) {
        if ($field) $params[-1] = $val;
        else $params[$params[-1]] = $val;
        $field = !$field;
    }
    unset($params[-1]);
    break;
default:
    var_dump("Unknown value: ".$val);
    break;
}


text:
Q: Subcategory IDs in relation to parent category ID switch case I would like to switch ads tags in my footer depending on which category it displays at the moment. Code from below works fine for custom category pages and category pages that are included in the switch case. My code looking for ID, the problem is I have a lot of subcategories which are children of my main categories so the ID of those categories are different from parent IDs.
How do I address this issue without writing a case for each children categories?
<?php
 $footer_ads='';
 if(is_single())
    {
global $post;
$category = get_the_category($post->ID);
$cat_id_gum="";
if(($category[0]->parent)!='0')
{
    $cat_id_gum=$category[0]->cat_ID;
}
elseif(($category[1]->parent)!='0')
{
    $cat_id_gum=$category[1]->cat_ID;
}
elseif(($category[2]->parent)!='0')
{
    $cat_id_gum=$category[2]->cat_ID;
}
else
{
    $cat_id_gum=$category[3]->cat_ID;
}

}
elseif(is_page())
{

global $post;
$cat_id_gum = get_the_ID();
switch ($cat_id_gum)
{
    //GumGum tag - NFN/Sports
    case '216044': $footer_ads.='<script type="text/javascript">ggv2id=\'75803baa\';</script> <script type="text/javascript" src="http://g2.gumgum.com/javascripts/ggv2.js"></script>';break;
    //GumGum tag - NFN/Tech
    case '216042' : $footer_ads.='<script type="text/javascript">ggv2id=\'b737914c\';</script> <script type="text/javascript" src="http://g2.gumgum.com/javascripts/ggv2.js"></script>';break;
    //GumGum tag - NFN/Lifestyle
    case '216039' : $footer_ads.='<script type="text/javascript">ggv2id=\'8ba59d8a\';</script> <script type="text/javascript" src="http://g2.gumgum.com/javascripts/ggv2.js"></script>';break;
    //GumGum tag - NFN/Business
    case '216026' : $footer_ads.='<script type="text/javascript">ggv2id=\'5e3d4a16\';</script> <script type="text/javascript" src="http://g2.gumgum.com/javascripts/ggv2.js"></script>';break;
    //GumGum tag - NFN/Entertainment
    case '216036' : $footer_ads.='<script type="text/javascript">ggv2id=\'5c8180ad\';</script> <script type="text/javascript" src="http://g2.gumgum.com/javascripts/ggv2.js"></script>';break;
    default : $footer_ads.='<script type="text/javascript">ggv2id=\'c975bbec\';</script><script src="//g2.gumgum.com/javascripts/ggv2.js"></script>';break;

}
}
 elseif(is_category() ) {
global $post;
$category = get_category(get_query_var('cat'));
$cat_id_gum = $category->cat_ID;
switch ($cat_id_gum) {
    //GumGum tag - NFN/Sports
    case '57':
        $footer_ads .= '<script type="text/javascript">ggv2id=\'75803baa\';</script> <script type="text/javascript" src="http://g2.gumgum.com/javascripts/ggv2.js"></script>';
        break;
    //GumGum tag - NFN/Tech
    case '71' :
        $footer_ads .= '<script type="text/javascript">ggv2id=\'b737914c\';</script> <script type="text/javascript" src="http://g2.gumgum.com/javascripts/ggv2.js"></script>';
        break;
    //GumGum tag - NFN/Lifestyle
    case '76' :
        $footer_ads .= '<script type="text/javascript">ggv2id=\'8ba59d8a\';</script> <script type="text/javascript" src="http://g2.gumgum.com/javascripts/ggv2.js"></script>';
        break;
    //GumGum tag - NFN/Business
    case '19' :
        $footer_ads .= '<script type="text/javascript">ggv2id=\'5e3d4a16\';</script> <script type="text/javascript" src="http://g2.gumgum.com/javascripts/ggv2.js"></script>';
        break;
    //GumGum tag - NFN/Entertainment
    case '85' :
        $footer_ads .= '<script type="text/javascript">ggv2id=\'5c8180ad\';</script> <script type="text/javascript" src="http://g2.gumgum.com/javascripts/ggv2.js"></script>';
        break;
    default :
        $footer_ads .= '<script type="text/javascript">ggv2id=\'c975bbec\';</script><script src="//g2.gumgum.com/javascripts/ggv2.js"></script>';
        break;

}
}
 elseif(is_single() ) {
global $post;
$cat_id_gum = get_the_ID();
switch ($cat_id_gum) {
    //GumGum tag - NFN/Sports
    case '57':
        $footer_ads .= '<script type="text/javascript">ggv2id=\'75803baa\';</script> <script type="text/javascript" src="http://g2.gumgum.com/javascripts/ggv2.js"></script>';
        break;
    //GumGum tag - NFN/Tech
    case '71' :
        $footer_ads .= '<script type="text/javascript">ggv2id=\'b737914c\';</script> <script type="text/javascript" src="http://g2.gumgum.com/javascripts/ggv2.js"></script>';
        break;
    //GumGum tag - NFN/Lifestyle
    case '76' :
        $footer_ads .= '<script type="text/javascript">ggv2id=\'8ba59d8a\';</script> <script type="text/javascript" src="http://g2.gumgum.com/javascripts/ggv2.js"></script>';
        break;
    //GumGum tag - NFN/Business
    case '19' :
        $footer_ads .= '<script type="text/javascript">ggv2id=\'5e3d4a16\';</script> <script type="text/javascript" src="http://g2.gumgum.com/javascripts/ggv2.js"></script>';
        break;
    //GumGum tag - NFN/Entertainment
    case '85' :
        $footer_ads .= '<script type="text/javascript">ggv2id=\'5c8180ad\';</script> <script type="text/javascript" src="http://g2.gumgum.com/javascripts/ggv2.js"></script>';
        break;
    default :
        $footer_ads .= '<script type="text/javascript">ggv2id=\'c975bbec\';</script><script src="//g2.gumgum.com/javascripts/ggv2.js"></script>';
        break;

}
}
 echo $cat_id_gum;
 echo $footer_ads;

?>

A: Ok. This code:
$cat_id_gum="";
if(($category[0]->parent)!='0')
{
    $cat_id_gum=$category[0]->cat_ID;
}
elseif(($category[1]->parent)!='0')
{
    $cat_id_gum=$category[1]->cat_ID;
}
elseif(($category[2]->parent)!='0')
{
    $cat_id_gum=$category[2]->cat_ID;
}
else
{
    $cat_id_gum=$category[3]->cat_ID;
}

Is not really necessary. I'll show you what I mean in a bit. Later, however, you then set $cat_id_gum to the current post ID...
$cat_id_gum = get_the_ID();

... which doesn't make any sense and makes all of the preceding code pointless. You do a couple of other things which don't really make sense to me. I am going to ignore that and try to address the basic question of simplifying the code and dealing with child categories.
First, lets associate the categories and the codes:
// the key is the category
// the value is the gum code
$gum_codes = array(
  '1' => '75803baa',
  '2' => 'b737914c'
);

Now you can echo a script like:
printf($script,$gum_codes[1]);

Now, you need to convert your category to its topmost parent:
$category = get_the_category($post->ID);
$cat_id_gum = $category[0]->cat_ID;
$cat_id_gum = get_ancestors($cat_id_gum,'category');
array_shift($cat_id_gum);
$cat_id_gum = $cat_id_gum[0];
// $cat_id_gum is now your parent category

Put that all together:
$category = get_the_category($post->ID);
$cat_id_gum = $category[0]->cat_ID;
$cat_id_gum = get_ancestors($cat_id_gum,'category');
array_shift($cat_id_gum);
$cat_id_gum = $cat_id_gum[0];
// $cat_id_gum is now your parent category

$script = '<script type="text/javascript">ggv2id=\'%s\';</script> <script type="text/javascript" src="http://g2.gumgum.com/javascripts/ggv2.js"></script>';

// the key is the category
// the value is the gum code
$gum_codes = array(
  '1' => '75803baa',
  '34' => 'b737914c'
);

printf($script,$gum_codes[$cat_id_gum]);


text:
Q: Django urls.py: passing dynamic url parameter into include() I found in Django docs (https://docs.djangoproject.com/en/3.0/topics/http/urls/#passing-extra-options-to-include) that I can pass any constant into include() statement. Here in docs' example we are passing blog_id=3.
from django.urls import include, path

urlpatterns = [
    path('blog/', include('inner'), {'blog_id': 3}),
]

But what if I want to pass dynamic url parameter into include()? I mean something like this:
from django.urls import include, path

urlpatterns = [
    path('blog/<int:blog_id>/', include('inner'), {'blog_id': ???}),
]

Is it possible?

A: You do not specify the kwargs, so you write:
from django.urls import include, path

urlpatterns = [
    # no { 'blog_id': … }
    path('blog/<int:blog_id>/', include('inner')),
]
The url parameter will be passed to the kwargs of the included views.
This is to some extent discussed in the documentation on Including other URLconfs where it says:

(…) For example, consider this URLconf:
from django.urls import path
from . import views

urlpatterns = [
    path('<page_slug>-<page_id>/history/', views.history),
    path('<page_slug>-<page_id>/edit/', views.edit),
    path('<page_slug>-<page_id>/discuss/', views.discuss),
    path('<page_slug>-<page_id>/permissions/', views.permissions),
]

We can improve this by stating the common path prefix only once and
  grouping the suffixes that differ:
from django.urls import include, path
from . import views

urlpatterns = [
    path('<page_slug>-<page_id>/', include([
        path('history/', views.history),
        path('edit/', views.edit),
        path('discuss/', views.discuss),
        path('permissions/', views.permissions),
    ])),
]


text:
Q: Modal fade in bootstrap auto add padding-left 15px. Can't change When there is little data, no scroll bar appears, everything is normal. But when I add more data, modal auto add style="display: block; padding-left: 15px;":
<div class="modal fade in" id="tags_modal" role="dialog" style="display: block; padding-left: 15px;">

I try change it but I can't.
My code: https://jsbin.com/fusinoc/1/edit?html,css,output
Photo my layout

Please help me. Thanks


text:
Q: Can I run Git commands in Visual Studio? I am using Visual Studio Team Explorer with git integration for source control. It works pretty well but sometimes I need to run some more advanced git commands so I am going to file explorer and opening git bash. Can I run git commands inside Visual Studio?
Using Visual Studio 19.

A: The Git integration in Visual Studio does not offer any terminal or ability to manually run Git commands.  Using other means to obtain a terminal (ex: Package Manager Console as mentioned above) is a workaround for some Git commands.
You will run into some issues, though.  For example, commands that present paged output (ex: Press key to continue) often do not work properly in the Package Manager Console.  They may scroll all the way to the end of their results rather than breaking on page boundaries since they can't tell the size of the Package Manager Console tool window.  There are some other little annoyances that you may encounter as well.

A: Git became the default revision control system with the update of Visual Studio 2019 to version 16.8 in November 2020. I'm aware of two main ways to start a git command prompt using 16.8 or newer:

*

*Right click the solution and choose Open in Terminal. This starts a PowerShell instance which docks (by default) at the bottom of Visual Studio and can be used to invoke system git.

*Git -> Open Repository in -> Command Prompt from the main menu (the top level Git menu is between the View and Project menus) opens a cmd.exe instance which also uses the system git installation.

Other methods of access include the options under Tools -> Command Line in the main menu. Starting a git command prompt through Team Explorer was removed Visual Studio 16.8. A functionality moved message is displayed instead.
As of 16.9.1, Visual Studio does not check that a system git installation is present (in C:\Program Files\Git by default). If no system git has been installed by the Git for Windows Visual Studio component or some other tool neither of the pathways described here will work. Thus, this part of Visual Studio's functionality can potentially be broken out of the box.

A: Update: Visual Studio 2022

*

*Open Visual Studio 2022

*Find git options from top left 4

*Click Open in command prompt
Basically it opens a cmd command prompt but it will work as git. Check git --version if you have already installed any version of git or not.
NB: Before using this feature, you should have installed any version of git

A: Visual Studio 2013 Update 1 through Visual Studio 2019 version 16.7 have a git client built into Team Explorer. To locate the feature, open a project that's controlled by Git (or just git init an existing project), and select View->Team Explorer from the menu. You'll see the "Connect" view, which looks a bit like this:

You can read more about it here: https://devblogs.microsoft.com/devops/use-the-git-command-prompt-to-supplement-visual-studio/

A: You can use the Package Manager Console (in the bottom tab in VS) to run Git commands. see here


text:
Q: Error : subclasses of BaseDatabaseOperations may require a datetime_extract_sql() method... in Django date filtering I'm using Django 2.2.12.
In models.py, I have a model of name Webregister having field
created_on = models.DateTimeField(null=True, blank=True) that returns data in the format 2020-09-04 22:17:00+00:00
Inorder to filter the date, I wrote this query
Webregister.objects.filter(created_on__date=date.today())
and it returns the following error,
NotImplementedError: subclasses of BaseDatabaseOperations may require a datetime_extract_sql() method
However, it's working fine If I use __year and hit the following query,
Webregister.objects.filter(created_on__year="2020")
PLease let me know what's the issue ?

A: you can just use normal filter with datetime or date objects as long as they are comparable :
class Model(models.Model):
    created_on = models.DateTimeField(null=True, blank=True)

data = Model.objects.filter(created_on__exact=datetime.now())

Your error is probably the comparaison between your DateTimeField() (which is a datetime object) and date.now() (which is a date object)
You can also use lt, gt but the two data need to be comparable


text:
Q: Web Scraping, How to extract data from two same tags using bs4 in python I am using bs4 with python and trying to fetch data from a web page. Link I used inspect element over the info i want, but both have same tag,class.

             Information Technology

             % Price Change

             +0.05%

             Industry

             Software & Services

             % Price Change

             -0.04%

I am doing it this way:
sect= soup.find("a",{"data-tracker-label":"information_technology.01"})
print sect.text
sect_per= soup.find("div",{"data-type":"worse"or"better"})
print sect_per.text
ind=soup.find("a",{"data-tracker-label":"information_technology.02"})
print ind.text
ind_per=soup.find("div",{"div",{"data-type":"worse"or"better"})
print ind_per

both print ind_per and print ind_per are giving me same result because of same class and tag
i need to extract +0.05% and -0.04% respectively.
Please suggest me way to do it.

A: soup = BeautifulSoup(example, "html.parser")

for cell in soup.find_all("div", class_="cell"):
    name = ""
    namecell = cell.find("a", class_="cell__value", text=True)
    if namecell is not None:
         name = namecell.get_text(strip=True)
    price_chage = cell.find("div", class_="cell__value").get_text(strip=True)
    print ( "%s: Price Change:  %s" % (name, price_chage))

Which outputs:

Information Technology: Price Change:  +0.05%
Software & Services: Price Change:  -0.04%

You can save that values for further processing.

A: or returns the left operand if the left operand is truth value (non-empty string for string):
>>> "worse" or "better"
'worse'

So, the following line:
ind_per = soup.find("div",{"div",{"data-type":"worse" or "better"})

is basically doing same with:
ind_per = soup.find("div",{"div",{"data-type":"worse"})

You need to query them separately:
ind_per = soup.find("div",{"div",{"data-type": "worse"})
print ind_per
ind_per = soup.find("div",{"div",{"data-type": "better"})
print ind_per

or using for loop:
for data_type in ('worse', 'better'):
    ind_per = soup.find("div",{"div",{"data-type": data_type})
    print ind_per

A:

Votes:
**2,333,089**
| Gross:
**$28.34M**

"I want to get a voting count and gross for movies
but both have the same name is "nv" so we use indexing for these"
 vote_mov=container.findAll("span",{"name":"nv"})
    vote=vote_mov[0].text

    gross_mov=container.findAll("span",{"name":"nv"})
    gross=gross_mov[1].text

"Here it 1st get voting and then grossenter image description here


text:
Q: htmx three dependent selects immediate population of child elements on change Consider this HTML page using the HTML Javascript package

        <title>Test</title>

Prova

        <select name="brand" hx-get="/models" hx-target="#models" hx-trigger="change">
            <option value='325i'>325i</option>
            <option value='325ix'>325ix</option>
            <option value='X5'>X5</option>
        </select>

        <select name="model" id="models" hx-get="/models2" hx-target="#numbers" hx-trigger="change">

        </select>

        <select name="number" id="numbers">

        </select>

Consider that endpoints models and models2 return a bunch of options depending on the value of the select being changed.
The response is something like:
<option value='325i'>325i</option>
<option value='325ix'>325ix</option>
<option value='X5'>X5</option>

I wonder how I can make that whenever I change the select brand, that triggers the HTMX GET Request associated with the model select, which itself will populate the numbers select.
What I see happening, right now, is that the change to the brand dropdown triggers the population of the model dropdown.
I would expect the same to happen for the number dropdown as a consequence of the model dropdown value being changed but that is not happening. Can you elucidate me why that is not happening? And in that case how I can fix that using standard HTMX?

A: Swapping the new content into the models element does not actually trigger the change event on the models element. You'd need to define an additional trigger event to get the models element to issue its hx-get request when the brand changes and therefore the models options are updated. You could do this purely on the client side in HTMX with a delay so that your models selected value is sent. Or  you could have a combination of client custom trigger event and a HX-Response Header sent to the client to trigger that event.
Here is an example of a client event. Added a long 3 second delay to illustrate how the trigger from brand needs to wait until the swap has finished. If you just had the from:brand trigger without delay, it would fire instantaneously (before the models content was populated) so that post would not include the preselected model option. Essentially a race condition. Also went ahead and included the brands element in the models2 request. Maybe you didn't want models2 server side logic have to worry about the brand... but if two different brands had the same model name, then you may not know which set of numbers are supposed to be returned... For the following to work correctly, please add id='brand' to your brand select element.
<select name="model" id="models" hx-get="/models2"
  hx-target="#numbers" hx-include="#brand"
  hx-trigger="change, change from:#brand delay:3s">
</select>

The other way to do this would be to add a custom event into the model hx-trigger and then trigger that client event from the server in a Response Header. Added a short 5 millisecond delay so that HTMX has time to finish the swap before making the call to models2 .. Again, so that the preselected model is included in the request to models2.
Clientside:
<select name="model" id="models" hx-get="?handler=models2"
  hx-target="#numbers" hx-include="#brand"
  hx-trigger="change, get-numbers from:body delay:5ms">
</select>

Server Side ASP.NET here (your server may need different syntax for adding Response Header)
Response.Headers.Add("HX-Trigger", "get-numbers");


text:
Q: Deleting unused textures in opengl while browsing here I noticed something strange.
After loading a compressed texture and getting the ID to the shaders uniform
    GLuint Texture = loadDDS("uvtemplate.DDS");

    // Get a handle for our "myTextureSampler" uniform
    GLuint TextureID  = glGetUniformLocation(programID, "myTextureSampler");

He deleted the texture using the ID he got from glGetUniformLocation
    glDeleteTextures(1, &TextureID);

Shouldn't he use this instead?
    glDeleteTextures(1, &Texture );

A: Yes, that is correct.
Some OpenGL implementations (like AMD and nVidia drivers) tend to return ascending resource ID's, starting from 1. If this is the first texture the code allocates and the sampler is the first uniform in the shader program, then IDs will match, and the code accidentally works. However, it will likely break on other platforms (like Intel drivers), or when more resources are used.


text:
Q: SQL Server,query to get values between todays date and tomorrow date plus adding 14 hours to both the dates I have to get the values from table and display gridview of selected values between today and tomorrow date,my hosting company is 14 hours behind my time,so i have to add 14 hours to my code.I wrote the query and it is executing but doesnt give any values
Here is the query below
SELECT * FROM [customerdetails]
where date between dateadd(hh, 14, convert(datetime, convert(date, dateadd(d, 1, getdate()))))
  and dateadd(hh, 14, convert(datetime, convert(date, getdate())))

Can anyone please help me out,thanks

A: I could be wrong, because I don't have access to SQL Server right now.  But it looks like your query is looking "between tomorrow and today".  Try switching the order so the query is looking "between today and tomorrow".  According to the MSDN, it looks like the order matters.

A: Between operator expects BETWEEN Lower_End AND Upper_End
You have your query written as BETWEEN  Upper_End AND Lower_End , hence no results are coming back.
SELECT * FROM [customerdetails]
where date between dateadd(hh, 14, convert(datetime, convert(date, getdate())))
 and  dateadd(hh, 14, convert(datetime, convert(date, dateadd(d, 1, getdate()))))

or Even better option would be
SELECT * FROM [customerdetails]
where [date] >= dateadd(hh, 14, convert(datetime, convert(date, getdate())))
 and  [date] <= dateadd(hh, 14, convert(datetime, convert(date, dateadd(d, 1, getdate()))))

A: I think you should try this
date between
dateadd(hh,14,cast(getdate() as date))
and dateadd(hh,14,dateadd(d,1,cast(getdate() as date))


text:
Q: SQL query that works only on number not text I am working on a table in Teradata which supports sql query.
I've got table which has marks column and values as.
Marks8090fail7040fail
I am trying to build a query that will give me percentage of this marks out of total 150 like 80/150*100
but I want to skip column which contains texts like "fail".Select CAST(marks as float)/150*100this gives error of text in the marks column How can I do it without introducing new column which contains only integer values?


text:
Q: Multi line text box in asp.net I have a multi line text box like :
<asp:TextBox CssClass="txtform" ID="txtWhom" runat="server" Height="78px"
     Rows="10" TextMode="MultiLine"></asp:TextBox>

say I write the following text in that text box :

Dear Sir,
  General Manager,
  HSBC.

when I take that text in a variable in the vb.net code behind... and send it to a crystal report to show ... only ... the first line is shown... in that case only "Dear Sir," is shown ... but I want all the text ....
What Can I do ?

A: I wonder if your entered string includes carriage return & line feed chars that Crystal is not dealing with properly. You may need to strip those out or replace them with correct characters that Crystal expects.

A: Use "Can Grow" option for that text object in Crystal report.

=>Right Click -> Text Object
=>Select Format Object
=>Use Can grow option in the dialog box.
It enables for variable length fields to grow vertically in the report and word wrap automatically. A maximum number of lines can be set with this option to control rogue or large data elements.