text:
Q: Error when ViewController is implementing UITextFieldDelegate When implementing the UITextFieldDelegate in my ViewController class, the following error is thrown when entering the first character in the text field:
-[MyViewController respondsToSelector:]: message sent to deallocated instance...
So, I tried creating a separate class (inheriting only NSObject) and implementing UITextFieldDelegate. Guess what, it worked perfectly. However, that introduces some other problems as I have to do a lot of ugly cross-class-communication that I'd like to avoid. Here's the relevant parts of my app delegate code:
@interface RMSAppDelegate : NSObject <UIApplicationDelegate,
                                      UITabBarControllerDelegate>

@property (nonatomic, retain) UIViewController* myViewController;

@end

@implementation MyAppDelegate

@synthesize myViewController;

- (BOOL)application:(UIApplication *)application
            didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    myViewController = [[MyViewController alloc]
                         initWithNibName:@"MyView" bundle:nil];
    [self.window setRootViewController:myViewController];
    [self.window makeKeyAndVisible];
    return YES;
}

@end

.. and here's what is being displayed:
@interface MyViewController : UIViewController <UITextFieldDelegate>

@property (nonatomic, retain) IBOutlet UITextField* pinTextField;
- (void)viewDidLoad;

@end

@implementation MyViewController

@synthesize pinTextField;

- (void)viewDidLoad {
    // DOES NOT WORK (WHY?)
    //[pinTextField setDelegate:self];

    // WORKS, BUT I'D LIKE TO AVOID
    [pinTextField setDelegate:[[[MyTextFieldDelegate alloc] init] autorelease];

    [pinTextField becomeFirstResponder];
    [super viewDidLoad];
}

@end

And please, if you see any code (even off topic) that I could be doing better, leave a comment.

A: Since you asked for off-topic code comments: You forget to call [super viewDidLoad]. You also don't need to redeclare the prototype in order to override it. And the @synthesize textFieldDelegate is not valid, as you have no property in the class named textFieldDelegate. And your dealloc method is releasing an ivar named tfd which doesn't seem to actually exist in the class.
Your real problem is that you are not properly retaining the view controller at whatever point you allocate it. It may be that the view controller is being instantiated in a nib and associated with an ivar rather than a property declared retain, or is not being associated with anything. Or it could be that you are allocating it in code, adding its view as a subview of something, and then releasing it without ever retaining the view controller itself. Or it could just be that you are just releasing it when you shouldn't.
Your other class works specifically because you are leaking the object, so it never gets deallocated. The better solution, were you to go with this method, would be to store the object in an ivar when you allocate it and then release it (and set the ivar to nil) in both dealloc and viewDidUnload.

A: Okay, I finally solved this on my own. I have not changed the code. My NIB (.xib) was the culprit!
I thought that nested UIViewControllers was OK, and I still think they are in some cases (and maybe using another programmatic method). Anyway, I was initializing my class MyViewController with a NIB that in the Objects panel had a UIViewController as the first object.
I solved this by having the UIView as the first object in the Objects panel, and setting the File's Owner to be the UIViewController instead.
Correct code, incorrect NIB. Thank you for your help.


text:
Q: Постинг javascript кода на форуме ввиде ссылки Возможно ли запостить сам javascript в виде ссылки на форум? Дабы при нажатии на которую он выполнялся.
A: link
link

На Хешкоде, по-моему, не прокатит.
A: На форумах все знаки переводятся в их HTML коды на сколько знаю... поэтому и будут выглядеть как &lt и &gt и тому подобное... это будет отображаться как текст а не ссылка.
UPD
Когда серверу приходит запрост, то все символы вроде скобок уже переведены браузером в код.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Groups of the from $gMg$ in a monoid where $g$ is an idempotent Let $(M, \cdot)$ be a finite monoid with identity $e$. It is easy to see that $gMg = \{ gxg : x \in M \}$ forms a monoid with identity $geg = g$ if $g$ is an idempotent. If $gMg$ contains no idempotent other than $g$, it must be a group, since it is finite.
Suppose that $g, h \in M$ are distinct idempotents in $M$ such that both $gMg$ and $hMh$ are groups. Is it true that $gMg$ and $hMh$ are isomorphic?

A: Yes. You do not even need the finiteness of $M$.

Theorem 1. Let $\left(  M,\cdot\right)  $ be a monoid with identity
  $e$. For every idempotent $g\in M$, the set $gMg=\left\{  gxg\mid x\in
M\right\}  $ is a monoid (with respect to the operation $\cdot$) with neutral
  element $geg=gg=g$. Let $g$ and $h$ be two idempotents of $M$ such that the
  monoids $gMg$ and $hMh$ are groups. Then, these groups $gMg$ and $hMh$ are isomorphic.

Let us first show the following simple fact:

Lemma 2. Let $\left(  A,\cdot\right)  $ and $\left(  C,\cdot\right)  $ be
  two groups. Let $\varphi:A\rightarrow C$ be a map. Assume that $\varphi\left(
a\right)  \varphi\left(  b\right)  =\varphi\left(  ab\right)  $ for all $a\in
A$ and $b\in A$. Then, $\varphi$ is a group homomorphism from $\left(
A,\cdot\right)  $ to $\left(  C,\cdot\right)  $.

Proof of Lemma 2. Let $e$ denote the neutral element of any group. We have
assumed that
\begin{equation}
\varphi\left(  a\right)  \varphi\left(  b\right)  =\varphi\left(
ab\right)  \qquad \text{for all $a\in A$ and $b\in A$.}
\label{darij.pf.l2.1}
\tag{1}
\end{equation}
Applying this to $a=e$ and $b=e$, we obtain $\varphi\left(  e\right)
\varphi\left(  e\right)  =\varphi\left(  \underbrace{ee}_{=e}\right)
=\varphi\left(  e\right)  $. Since $C$ is a group, we can cancel
$\varphi\left(  e\right)  $ from this equality, and obtain $\varphi\left(
e\right)  =e$. Combined with our assumption \eqref{darij.pf.l2.1}, this shows that $\varphi$
is a monoid homomorphism from $\left(  A,\cdot\right)  $ to $\left(
C,\cdot\right)  $. Thus, $\varphi$ is also a group homomorphism (since every
monoid homomorphism between groups is a group homomorphism). Lemma 2 is proven. $\blacksquare$
Proof of Theorem 1. The elements $g$ and $h$ are idempotents; thus, we have
$gg=g$ and $hh=h$.
Let $p$ be the inverse of the element $ghg$ in the group $gMg$. Then,
$p\left(  ghg\right)  =\left(  ghg\right)  p=g$ (since $g$ is the neutral
element of the group $gMg$).
Let $q$ be the inverse of the element $hgh$ in the group $hMh$. Then,
$q\left(  hgh\right)  =\left(  hgh\right)  q=h$ (since $h$ is the neutral
element of the group $hMh$).
The element $p$ belongs to the group $gMg$, but $g$ is the neutral element of
this group. Hence, $pg=gp=p$. Similarly, $qh=hq=q$.
We have
\begin{align}
gqhghgp=g\underbrace{q\left(  hgh\right)  }_{=h}gp=ghgp=\left(  ghg\right)
p=g ,
\end{align}
so that
\begin{align}
g
&= gqhghgp
= gqh \underbrace{\left(  ghg\right)  p}_{=g}
= g\underbrace{qh}_{=q}g
\label{darij.pf.thm1.2}
\tag{2}
\\
&= gqg .
\label{darij.pf.thm1.3}
\tag{3}
\end{align}
Similarly,
\begin{equation}
h = hph .
\label{darij.pf.thm1.4}
\tag{4}
\end{equation}
We define a map $\alpha:gMg\rightarrow hMh$ by setting
\begin{align}
\alpha\left(  x\right)  =hxq \qquad \text{ for every $x\in gMg$.}
\end{align}
This is well-defined, because every $x\in gMg$ satisfies $hx\underbrace{q}
_{\in hMh}\in h\underbrace{xhM}_{\subseteq M}h\subseteq hMh$.
We define a map $\beta:hMh\rightarrow gMg$ by setting
\begin{align}
\beta\left(  y\right)  =pyg \qquad \text{ for every $y\in hMh$.}
\end{align}
This is well-defined, because every $y\in hMh$ satisfies $\underbrace{p}_{\in
gMg}yg\in g\underbrace{Mgy}_{\subseteq M}g\subseteq gMg$.
Let us now prove that
\begin{align}
\alpha\left(  a\right)  \alpha\left(  b\right)  =\alpha\left(
ab\right)  \qquad \text{ for all $a\in gMg$ and $b\in gMg$.}
\label{darij.pf.thm1.5}
\tag{5}
\end{align}
[Proof of \eqref{darij.pf.thm1.5}: Let $a\in gMg$ and $b\in gMg$.
We have $a\in gMg$; thus, there exists some $x\in M$ such that $a=gxg$.
Consider this $x$. Thus, $\underbrace{a}_{=gxg}g=gx\underbrace{gg}_{=g}=gxg=a$.
We have $b\in gMg$; thus, there exists some $y\in M$ such that $b=gyg$.
Consider this $y$. Thus, $g\underbrace{b}_{=gyg}=\underbrace{gg}_{=g}yg=gyg=b$.
The definition of $\alpha$ yields $\alpha\left(  a\right)  =h\underbrace{a}
_{=ag}q=hagq$ and $\alpha\left(  b\right)  =h\underbrace{b}_{=gb}q=hgbq$.
Multiplying these two equalities, we obtain
\begin{align}
\alpha\left(  a\right)  \alpha\left(  b\right)  =ha\underbrace{gqhg}
_{\substack{=g\\\text{(by \eqref{darij.pf.thm1.2})}}}bq=h\underbrace{ag}_{=a}bq=habq .
\label{darij.pf.thm1.6}
\tag{6}
\end{align}
On the other hand, the definition of $\alpha$ yields $\alpha\left(  ab\right)
=habq$. Compared with \eqref{darij.pf.thm1.6}, this yields $\alpha\left(  a\right)
\alpha\left(  b\right)  =\alpha\left(  ab\right)  $. Thus, \eqref{darij.pf.thm1.5} is proven.]
Now, Lemma 2 (applied to $A=gMg$, $C=hMh$ and $\varphi=\alpha$) yields that
$\alpha$ is a group homomorphism from $\left(  gMg,\cdot\right)  $ to $\left(
hMh,\cdot\right)  $. We shall now focus on proving that $\alpha$ is invertible.
Indeed, let us first show that $\beta\circ\alpha=\operatorname*{id}$. Indeed,
let $x\in gMg$. Then, $xg=gx=x$ (since $x$ belongs to the group $gMg$, but $g$
is the neutral element of this group). We have
\begin{align}
\left(  \beta\circ\alpha\right)  \left(  x\right)
&=\beta\left(
\underbrace{\alpha\left(  x\right)  }_{=hxq}\right)  =\beta\left(  hxq\right) \\
&=\underbrace{p}_{=pg}h\underbrace{x}_{=xg}qg
\qquad \text{(by the definition of $\beta$)} \\
&=pgh\underbrace{x}_{=gx}\underbrace{gqg}_{\substack{=g\\\text{(by
\eqref{darij.pf.thm1.3})}}}=\underbrace{pghg}_{=p\left(  ghg\right)  =g}\underbrace{xg}
_{=x}=gx=x=\operatorname*{id}\left(  x\right) .
\end{align}
Thus, we have shown that $\left(  \beta\circ\alpha\right)  \left(  x\right)
=\operatorname*{id}\left(  x\right)  $ for every $x\in gMg$. This proves
$\beta\circ\alpha=\operatorname*{id}$.
Now, let us show that $\alpha\circ\beta=\operatorname*{id}$. Indeed, let $y\in
hMh$. Then, $hy=yh=y$ (since $y$ belongs to the group $hMh$, but $h$ is the
neutral element of this group). We have
\begin{align}
\left(  \alpha\circ\beta\right)  \left(  y\right)
&=\alpha\left(
\underbrace{\beta\left(  y\right)  }_{=pyg}\right)  =\alpha\left(  pyg\right) \\
&= hp\underbrace{y}_{=hy}g\underbrace{q}_{=hq}
\qquad \text{(by the definition of $\alpha$)} \\
&=\underbrace{hph}_{\substack{=h\\\text{(by \eqref{darij.pf.thm1.4})}}}\underbrace{y}
_{=yh}ghq=\underbrace{hy}_{=y}\underbrace{hghq}_{=\left(  hgh\right)
q=h}=yh=y=\operatorname*{id}\left(  y\right) .
\end{align}
Thus, we have shown that $\left(  \alpha\circ\beta\right)  \left(  y\right)
=\operatorname*{id}\left(  y\right)  $ for every $y\in hMh$. This proves
$\alpha\circ\beta=\operatorname*{id}$.
The maps $\alpha$ and $\beta$ are mutually inverse (since $\alpha\circ
\beta=\operatorname*{id}$ and $\beta\circ\alpha=\operatorname*{id}$). Thus,
the map $\alpha$ is invertible. Since $\alpha$ is a group homomorphism, this
shows that $\alpha$ is a group isomorphism. Thus, there exists a group
isomorphism $gMg\rightarrow hMh$ (namely, $\alpha$). This proves Theorem 1. $\blacksquare$
This proof was obtained by lots of experimentation and iterative
simplification. Do not ask me for the intuition behind it, for I have none. I
suspect it could still be shortened twice, but I am happy enough that I was
able to dispose of the finiteness condition and at least some of the ugliest
computations. Feel free to improve!

A: This is true for any semigroup (even if it is not a monoid) and is easy to prove if you know about Green's relations.
If $S$ be a semigroup and $e$ is an idempotent of $S$, then $eSe$ is a monoid
(with identity $e = eee$). Suppose that $e$ and $f$ are idempotents such that $eSe$ and $fSf$ are groups. Then in particular, $e \mathrel{\mathcal H} efe$ and $f \mathrel{\mathcal H} fef$, which implies that $e \mathrel{\mathcal R} ef$ and
$ef \mathrel{\mathcal L} f$, whence $e \mathrel{\mathcal D} f$. It follows by Green's Lemma, than the two groups $eSe$ and $fSf$, which are maximal groups of a regular $\mathcal D$-class, are isomorphic.


text:
Q: How to check if time is in the range between two days? I found some nice examples to check, if a time is in a specific range, like this one:
now_time = datetime.datetime.now().time()
start = datetime.time(17, 30)
end = datetime.time(4, 00)
if start <= now_time <= end:

In my case, I want to check, if the current time is between 17:30 and 04 in the morning. How am I able to solve this?

A: 17:30 comes after 4:00, so anything with start <= x <= end will evaluate to false, because it implies that end (4:00) is larger than start (17:30), which is never true.
What you must do instead is check whether it's past 17:30 or it's before 4:00:
import datetime

now_time = datetime.datetime.now().time()
start = datetime.time(17, 30)
end = datetime.time(4, 00)
if now_time >= start or now_time <= end:
    print('true')
else:
    print('false')

A: from datetime import datetime, time

 def time_in_range(start, end, current):
        # during two days
        if (start >= end):
            if(current >= start or current <= end) :
                print("true")
            else:
                print("false")
        # during one day
        if(start <= end):
            if(current >= start and current <= end) :
                print("true")
            else:
                print("false")

time_in_range(time(15,0),time(1,0), datetime.now().time())


text:
Q: could NaN be causing the occasional crash in this core audio iOS app? My first app synthesised music audio from a sine look-up table using methods deprecated since iOS 6. I have just revised it to address warnings about AudioSessionhelped by this blog and the Apple guidelines on AVFoundationFramework. Audio Session warnings have now been addressed and the app produces audio as it did before. It currently runs under iOS 9.
However the app occasionally crashes for no apparent reason. I checked out this SO post but it seems to deal with accessing rather than generating raw audio data, so maybe it is not dealing with a timing issue. I suspect there is a buffering problem but I need to understand what this might be before I change or fine tune anything in the code.
I have a deadline to make the revised app available to users so I'd be most grateful to hear from someone who has dealt a similar issue.
Here is the issue. The app goes into debug on the simulator reporting:
com.apple.coreaudio.AQClient (8):EXC_BAD_ACCESS (code=1, address=0xffffffff10626000)

In the Debug Navigator, Thread 8 (com.apple.coreaudio.AQClient (8)), it reports:
    0 -[Synth fillBuffer:frames:]
    1 -[PlayView audioBufferPlayer:fillBuffer:format:]
    2 playCallback

This line of code in fillBuffer is highlighted
    float sineValue = (1.0f - b)*sine[a] + b*sine[c];

... and so is this line of code in audioBufferPlayer
    int packetsWritten = [synth fillBuffer:buffer->mAudioData frames:packetsPerBuffer];

... and playCallBack
    [player.delegate audioBufferPlayer:player fillBuffer:inBuffer format:player.audioFormat];

Here is the code for audioBufferPlayer (delegate, essentially the same as in the demo referred to above).
    - (void)audioBufferPlayer:(AudioBufferPlayer*)audioBufferPlayer fillBuffer:(AudioQueueBufferRef)buffer format:(AudioStreamBasicDescription)audioFormat
    {
    [synthLock lock];
    int packetsPerBuffer = buffer->mAudioDataBytesCapacity / audioFormat.mBytesPerPacket;
    int packetsWritten = [synth fillBuffer:buffer->mAudioData frames:packetsPerBuffer];
    buffer->mAudioDataByteSize = packetsWritten * audioFormat.mBytesPerPacket;
    [synthLock unlock];

    }

... (initialised in myViewController)
- (id)init
{
    if ((self = [super init])) {
    // The audio buffer is managed (filled up etc.) within its own thread (Audio Queue thread)
    // Since we are also responding to changes from the GUI, we need a lock so both threads
    // do not attempt to change the same value independently.

        synthLock = [[NSLock alloc] init];

    // Synth and the AudioBufferPlayer must use the same sample rate.

        float sampleRate = 44100.0f;

    // Initialise synth to fill the audio buffer with audio samples.

        synth = [[Synth alloc] initWithSampleRate:sampleRate];

    // Initialise note buttons

        buttons = [[NSMutableArray alloc] init];

    // Initialise the audio buffer.

        player = [[AudioBufferPlayer alloc] initWithSampleRate:sampleRate channels:1 bitsPerChannel:16 packetsPerBuffer:1024];
        player.delegate = self;
        player.gain = 0.9f;
        [[AVAudioSession sharedInstance] setActive:YES error:nil];

    }
    return self;
}   // initialisation

... and for playCallback
static void playCallback( void* inUserData, AudioQueueRef inAudioQueue, AudioQueueBufferRef inBuffer)
{
    AudioBufferPlayer* player = (AudioBufferPlayer*) inUserData;
    if (player.playing){
        [player.delegate audioBufferPlayer:player fillBuffer:inBuffer format:player.audioFormat];
        AudioQueueEnqueueBuffer(inAudioQueue, inBuffer, 0, NULL);
    }
}

... and here is the code for fillBuffer where audio is synthesised
- (int)fillBuffer:(void*)buffer frames:(int)frames
{
    SInt16* p = (SInt16*)buffer;

    //  Loop through the frames (or "block size"), then consider each sample for each tone.

    for (int f = 0; f < frames; ++f)
    {
        float m = 0.0f;  // the mixed value for this frame

        for (int n = 0; n < MAX_TONE_EVENTS; ++n)
        {
            if (tones[n].state == STATE_INACTIVE)   // only active tones
                continue;

    // recalculate a 30sec envelope and place in a look-up table
    // Longer notes need to interpolate through the envelope

            int a   = (int)tones[n].envStep;        // integer part  (like a floored float)
            float b = tones[n].envStep - a;         // decimal part  (like doing a modulo)

        // c allows us to calculate if we need to wrap around

            int c = a + 1;                          // (like a ceiling of integer part)
            if (c >= envLength) c = a;              // don't wrap around

    /////////////// LOOK UP ENVELOPE TABLE /////////////////

    //  uses table look-up with interpolation for both level and pitch envelopes
    //  'b' is a value interpolated between 2 successive samples 'a' and 'c')
    //  first, read values for the level envelope

            float envValue = (1.0f - b)*tones[n].levelEnvelope[a] + b*tones[n].levelEnvelope[c];

    //  then the pitch envelope

            float pitchFactorValue = (1.0f - b)*tones[n].pitchEnvelope[a] + b*tones[n].pitchEnvelope[c];

    //  Advance envelope pointer one step

            tones[n].envStep += tones[n].envDelta;

    //  Turn note off at the end of the envelope.
            if (((int)tones[n].envStep) >= envLength){
                tones[n].state = STATE_INACTIVE;
                continue;
            }

        //  Precalculated Sine look-up table
            a = (int)tones[n].phase;                    // integer part
            b = tones[n].phase - a;                     // decimal part
            c = a + 1;
            if (c >= sineLength) c -= sineLength;       // wrap around

    ///////////////// LOOK UP OF SINE TABLE ///////////////////

            float sineValue = (1.0f - b)*sine[a] + b*sine[c];

    // Wrap round when we get to the end of the sine look-up table.

            tones[n].phase += (tones[n].frequency * pitchFactorValue); // calculate frequency for each point in the pitch envelope
            if (((int)tones[n].phase) >= sineLength)
                tones[n].phase -= sineLength;

    ////////////////// RAMP NOTE OFF IF IT HAS BEEN UNPRESSED

            if (tones[n].state == STATE_UNPRESSED) {
                tones[n].gain -= 0.0001;
            if ( tones[n].gain <= 0 ) {
                tones[n].state = STATE_INACTIVE;
                }
            }

    //////////////// FINAL SAMPLE VALUE ///////////////////

            float s = sineValue * envValue * gain * tones[n].gain;

    // Clip the signal, if needed.

            if (s > 1.0f) s = 1.0f;
            else if (s < -1.0f) s = -1.0f;

    // Add the sample to the out-going signal
        m += s;
        }

    // Write the sample mix to the buffer as a 16-bit word.
    p[f] = (SInt16)(m * 0x7FFF);
    }
return frames;
}

I'm not sure whether it is a red herring but I came across NaN in several debug registers. It appears to happen while calculating phase increment for sine lookup in fillBuffer (see above). That calculation is done for up to a dozen partials every sample at a sampling rate of 44.1 kHz and worked in iOS 4 on an iPhone 4. I'm running on simulator of iOS 9. The only changes I made are described in this post!

A: My NaN problem turned out to have nothing directly to do with Core Audio. It was caused by an edge condition introduced by changes in another area of my code. The real problem was a division by zero attempted while calculating the duration of the sound envelope in realtime.
However, in trying to identify the cause of that problem, I am confident my pre-iOS 7 Audio Session has been replaced by a working setup based on AVFoundation. Thanks goes to the source of my initial code Matthijs Hollemans and also to Mario Diana whose blog explained the changes needed.
At first, the sound levels on my iPhone were significantly less than the sound levels on the Simulator, a problem addressed here by foundry. I found it necessary to include these improvements by replacing Mario's
    - (BOOL)setUpAudioSession

with foundry's
    - (void)configureAVAudioSession

Hopefully this might help someone else.


text:
Q: Isometry in a compact space is surjective Let's say we have a compact metric space $(X,d)$ and a function $f: X\to X$ satisfying
$d(f(x),f(y)) = d(x,y)$, $x,y\in X$.
How can we show that this function is sujective in a simple way.

A: Let's suppose there is some element $y \in X - f(X)$, then since $X$ is a compact metric space, there exists a disjoint $\epsilon-$ neighborhood around $y$ that doesn't intersect $f(X)$ (here we've used that $f(X)$ is the continuous image of a compact space).
We're now ready to construct a sequence that has no convergent subsequence (contradicting that $X$ is compact)
We let $x_0 = y$ and then let $x_{n+1} =f(x_{n})$. We first see that $d(x_0, x_i) > \epsilon$ for all $i >0$ since $x_i \in f(X)$. Also, by our construction, for all $m > n >0$ we have that $$
d(x_m,x_n) =d(f(x_{m-1}),f(x_{n-1}) = d(x_{m-1},x_{n-1}) \cdots = d(x_{m-n},x_0) > \epsilon$$ where the first equality is from the definition of the sequence, the second equality is from the fact that $f$ is an isometry, and then we just continue in this pattern to get the final inequality. Thus, this sequence can have no convergent subsequence, contradicting that $X$ is compact. Thus $f$ must be surjective.

A: If $\{x_i\}$ is a $2\delta$-maximal packing, i.e.
$d(x_i,x_j)>2\delta$, then $f(\{x_i\})$ is $2\delta$-maximal
packing.
If $d(x_i,x)>2\delta $, then $\{ x_i\}$ is not maximal. Hence
$\{x_i\}$ is $2\delta$-net, i.e. for any $x\in X$, there is $x_i$
s.t. $d(x_i,x)\leq 2\delta$.
Hence for $x\in X$, we have $d(f(x_i),x)\leq 2\delta$. That is, $x$
is a limit point of $f(X)$. Since $X$ is compact, then $x\in f(X)$.


text:
Q: Equivalent term of integration Let $f:[0,3]\to\mathbb R$ given, such that $\int_0^3 f(x)\,dx $ exists.

Give a function g and a constant C such that $\int_0^3 f(x)dx=C\int_a^b g(x)dx$ while $g$ is only depending on $f$ and $C$ is only depending on $a$ and $b$ .

How does one handle this problem? This task was an old exam question.

A: One way to do this is to switch the $a\to b$ integral to one on $0\to 3$. So let's try
$$\int_a^bg(x)~dx=\int_0^3 g(u)~du$$
Now we need to find the substitution for $u$. When $x=a$ in the first integral we need $u=0$, and when $x=b$ we need $u=3$. So try $u=\frac{3}{b-a}(x-a)$. So we can reverse this to obtain $g$ in terms of $f$. Then the constant $C$ will be to take care of the change of variables, since $du=\frac{3}{b-a}~dx$. I leave it to you to put everything together.

A: Take $g(x) = \int_0^3f(t)dt$ (yeap, a constant function) and $C = \frac{1}{b-a}$.


text:
Q: Javascript : Get all cookies with domain name as x.y.com I have a requirement to retrieve and clear cookies tat are set buy my site. However, when I fetch the cookies by document.cookie I get the parent domain's cookie as well.
Eg :
CookieA : Doamin x.y.com (Set by x.y.com)
CookieB : Domain y.com  (set by c.y.com)

I there any way I could filter the cookies by domain name?
Right now, in chrome console, when I query document.cookie, I do not get the domain name.

Thanks in advance.


text:
Q: How can http://evilsub.domain.com/linkpage.html exist on a webserver even though my host records for domain.com have no entry for "evilsub"? Google search console has recently let me know that I have a "Hacked: URL injection" security problem. The error message includes links to the pages. These are in the format:
http://weirdsubdomain.example.com/linkpage.html

*

*I've called this page with curl and wget and the page exists and is returned by the web-server

*My site is hosted at https://example.com (note "https")

*My site is a static jekyll site that lives on Github Pages

*The spam/hacking subdomain pages are "http" (not "https")

*My host records on my registrar have no entry for "weirdsubdomain"

I understand I've probably kept an old page with a <script> tag in it that most likely pulls in an old version of jquery or that there could well be some old javascript in there somewhere that allows for taking control of people's browers by introducing javascript into a form input of some similar exploit.
What I don't understand, is how it's possible for someone to get DNS to resolve and route a subdomain of my domain? That seems like a server-side thing?
All advice and info very welcome as I set off to try and clean up or disable my javascript:-)
Update 13 April 2020
I had a look at my host settings and they included records for *.example.com.
My understanding is this wildcard configuration lets another Github user apply a subdomain to my domain. I'm not sure if I've understood this properly but if my registrar has a host record that points *.example to the IP address for Github pages, and I have a CNAME file in the root of my repo with "example.com" then another Github user can place a CNAME in their directory with "subdomain.example.com" and the DNS will route requests accordingly.
Is this true? It seems crazy so prob not true:-)


text:
Q: Hausman test: Why requirement of positive definite covariance matrix? Can someone please explain to me why the covariance matrix needs to be positive definite for the Hausman test? And why we can skip this restriction by applying the "test of overidentifying restrictions"?
Isn't the issue easily explainable when simply comparing the formula of the Hausman test statistic and the formula of the Sargan test statistic?

A: There are two parts to this question:

*

*Should the asymptotic variance-covariance matrix be positive definite? The answer is yes, although in some situations this can probably be weakened to positive semi-definite. If this asymptotic VCE has negative eigenvalues, then the asymptotic distribution of the test statistic is supported on the negative half-line -- in other words, the test statistic is allowed to take negative values, so none of the $\chi^2$ results could work. With the asymptotic VCE that has non-negative eigenvalues some of which are zero, this problem does not bite you, but then you have another problem of figuring out what the degrees of freedom (= number of strictly positive) eigenvalues is. If you have the spectrum that looks like {4, 1, 0.01, 1e-5}, would the last eigenvalue converge to a valid positive, is it a computer round-off error from zero, or is it just a valid non-zero in the finite sample, but would converge to a zero eigenvalue eventually?

*In finite samples, little is guaranteed. Sometimes you will have a positive definite matrix in the middle part of Hausman test, so things will be fine. Sometimes, you can get a non-pd matrix when you subtract two variance estimators; this could be a small sample effect, or this could indicate that your model is not correctly specified, so what you think is an asymptotically efficient estimator may not actually be one.
In linear regression situations, including some of the instrumental variable models, you can push the linear algebra of the relevant matrices far enough to establish that the ultimate matrix is positive definite. The requirement is still there, but you can avoid the guesswork of figuring out what's going on with that matrix.


text:
Q: How do I use the SQLite3 import command using the C API? I have the following code:
int rc;
rc = sqlite3_exec(sqlite3_database, ".import mydata.csv mytable", callback, 0, &errMsg);

After this gets run, errMsg contains this error message:
near ".": syntax error

I assume that it does not recognize the import command. However, this command works when running it from the sqlite3 program on the command line.
I need to be able to use the import command directly in my program. Is there a way I can do this? The reason I need to use the import command is because doing inserts for each line of the CSV file takes over 5 minutes, and the import command takes a split second.

A: .import is a part of the command line program interface and not the C API I believe. You can (as i have done) set up all your data in a SQLite3 database file using another tool and then include that database file in your app. Then when you open it in your code, the data is already there.

A: Being a quite old post, I just wanted to update for reference only.
There is an open source API I am maintaining for SQLite3 C/C++ API import/export functionality. The code can be accessed via this link

A: I suspect the insert is taking so long because you're having SQLite reparse your INSERT statement for each row (that is, using sqlite3_exec()) rather than using a parameterized prepared statement (that is, using sqlite3_prepare_v2(), sqlite_bind_*() and sqlite3_step()).  As ephemient said above, that's how import is implemented internally.
Using a parameterized statement should achieve the same performance as .import, I believe.

A: The command-line shell's .import is not part of the C API; the sqlite3 tool implements it as
sqlite3_prepare(..., "INSERT INTO '...' VALUES (?, ..., ?)", ...);
sqlite3_exec(..., "BEGIN", ...);
for (each entry) {
    for (each column) sqlite3_bind_text(..., column, ...);
    sqlite3_step(...);
}
sqlite3_exec(..., "COMMIT", ...);

with some error-checking (ROLLBACK if anything goes wrong) and handling the prepared statement (sqlite3_reset, sqlite3_finalize).


text:
Q: Sometimes i receive the following error : Procedure or function expects parameter which was not supplied first I want to emphasize that this code is working in 99% of the times, but every once in a while clients complain for receiving this error. I have the bellow code for passing 2 parameters to a stored procedure. frmSetLoggerTime is a form with a datetimepicker (dtpToDate).
Did anyone came across this issue? I'm using Borland Delphi 7 with SQL Server 2008.

procedure TFormDBManager.ActionSetLoggerTimeExecute(Sender: TObject);
var
  frmSetLoggerTime: TfrmSetLoggerTime;
  var
  RecAffected, tmpOleVar:OleVariant;
  cmdObj: _Command;
  ParDataLoggerID, ParUdapteTime :_Parameter;
begin
  tmpOleVar:=OleCtrls.EmptyParam;
  frmSetLoggerTime := TfrmSetLoggerTime.Create(self);
  try
    frmSetLoggerTime.dtpToDate.DateTime := now;
    if frmSetLoggerTime.ShowModal = mrOK then
    begin
      cmdObj := CoCommand.Create;
      cmdObj.Set_ActiveConnection(DBRemoteModule.SLogConnection.ConnectionObject);
      cmdObj.CommandType := adCmdStoredProc;
      cmdObj.CommandText := 'UpdateRebelDateTime';
      ParUdapteTime := cmdObj.CreateParameter('@UdapteTime', adDate,     adParamInput, 3, frmSetLoggerTime.dtpToDate.DateTime);
      cmdObj.Parameters.Append(ParUdapteTime);
      ParDataLoggerID := cmdObj.CreateParameter('@DataLoggerID', adInteger,     adParamInput, 4, QueryLogger.FieldByName('DataLoggerID').AsInteger);
      cmdObj.Parameters.Append(ParDataLoggerID);
      cmdObj.Execute(RecAffected, tmpOleVar, 0);

    end;
  finally
    frmSetLoggerTime.free;
  end;

end;

Here is the stored procedure:
ALTER PROCEDURE [dbo].[UpdateRebelDateTime]  @UpdateDateTime datetime,      @DataLoggerID int
AS
SET NOCOUNT ON
  UPDATE tblDataLoggers SET UpdateDateTime = @UpdateDateTime,     UpdateDateTimeDelay = GETUTCDATE()
  WHERE  DataLoggerID = @DataLoggerID

A: You are using another parameter name: @UdapteTime
Your code:
 ParUdapteTime := cmdObj.CreateParameter('@UdapteTime', adDate, adParamInput, 3, frmSetLoggerTime.dtpToDate.DateTime);

And it expects:
@UpdateDateTime


text:
Q: how to stop and re-start sql server 2005? Is there a command line or even through the sql server studio to gracefully stop SQL Server 2005?

A: As mfinni said, net stop mssqlserver or similar will do it from the command line.  To add to that, from the GUI in SSMS, you can right click the instance name and hit "Stop".
You can also stop/start/restart SQL from the SQL Configuration Manager application.

A: You can also use Stop-Service -Force -Name 'MSSQL$SQLEXPRESS' if you want it in PowerShell. Substitute MSSQL$SQLEXPRESS with your SQL Server instance name.

A: If yout server on windows you can use command from cmd: SC STOP SERVICENAME  and SC START SERVICENAME
ServiceName - you can resolve by SC commnad, or look in Services (Control Panel)
Example: SC STOP MSSQL$SQLEXPRESS

A: net stop <servicename>

Will do it. The servicename will depend on whether it's the default instance or named. Run net start to see what your currently-running services are named.


text:
Q: Parsing SOAP XML in Oracle I am new to Oracle and I am working on something that needs to parse a SOAP request and save the address to DB Tables. I am using the XML parser in Oracle (XMLType) with XPath but am struggling since I can't figure out the way to parse the SOAP request because it has multiple namespaces.
Could anyone give me an example?
Thanks in advance!!!
edit
It would be a typical SOAP request similar to the one below.
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
                  xmlns:soap="http://soap.service.****.com">
  <soapenv:Header />
  <soapenv:Body>
    <soap:UpdateElem>
      <soap:request>
        <soap:att1>123456789</soap:att1>
        <soap:att2 xsi:nil="true"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
        <soap:att3>L</soap:att3>
        .....
      </soap:request>
    </soap:UpdateElem>
  </soapenv:Body>
</soapenv:Envelope>

I need to retrieve parameters att1, att2... and save them in to a DB table.

A: With Oracle's XML implementation there may several ways to shred a particular cabbage.  Here is a solution which uses XMLTable() to isolate the attributes.
I have put your SOAP message into a table with an XMLType column:
SQL> set long 5000
SQL> select xt.xmlmsg
  2  from xt
  3  where id = 1
  4  /

XMLMSG
--------------------------------------------------------------------------------
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
                                  xmlns:soap="http://soap.service.****.com">
  <soapenv:Header />
  <soapenv:Body>
    <soap:UpdateElem>
      <soap:request>
        <soap:att1>123456789</soap:att1>
        <soap:att2 xsi:nil="true"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
        <soap:att3>L</soap:att3>
        .....
      </soap:request>
    </soap:UpdateElem>
  </soapenv:Body>
</soapenv:Envelope>
SQL>

This SELECT uses XPath to extract the attributes as columns.   Note the use of the XMLTable() XMLNAMESPACES clause to define the, er, namespaces.
SQL> select
  2      atts.att1
  3      , atts.att2
  4      , atts.att3
  5  from xt
  6       , xmltable(
  7              xmlnamespaces(
  8                  'http://schemas.xmlsoap.org/soap/envelope/' as "soapenv"
  9                     , 'http://soap.service.****.com' as "soap"
 10                     , 'http://www.w3.org/2001/XMLSchema-instance' as "xsi"
 11                          )
 12               , '/soapenv:Envelope/soapenv:Body/soap:UpdateElem/soap:request'
 13               passing xt.xmlmsg
 14               columns
 15                   att1 number path 'soap:att1'
 16                   , att2 varchar2(10) path 'soap:att2/@xsi:nil'
 17                   , att3 char(1) path 'soap:att3'
 18                   ) atts
 19  where xt.id = 1
 20  /

      ATT1 ATT2       A
---------- ---------- -
 123456789 true       L

SQL>


text:
Q: Log.e with Kotlin As we have used Log.e() for logging error with java code. I was looking for same functionality with Kotlin. Though i have found Logger class
val Log = Logger.getLogger(MainActivity::class.java.name)
Log.warning("Hello World")

It is showing log in android studio logcat.
But does there any way to print log in red color the same way Log.e() does?

A: As Kotlin guarantee 100% interoperable with Java and Android, you can use Log or any java class in kotlin also.
If you insist to use Logger class, you can get the same output as Log#e using Logger#severe
Anyway, I recommend to use Timber or similar. There are many avantages on using it and using. Android's Log class logs all your outputs in any enviroment, and also consumes machine resources that you should get rid in production.

A: You can use all your java classes from Kotlin, so Log.e(  ) in java is exactly the same as Log.e(   ) in Kotlin.
If you want extra capabilities like automatically infering the tag string, you can use something like AnkoLogger

A: You can use log like this Log.d(TAG, "my Message") in KOTLIN

A: Log.e() will work perfectly in Kotlin.
In Kotlin, we also have a Logger class to log something.
Logger.getLogger(Test::class.java.name).warning("Hello..")

Otherwise, you have to use some other library like: kotlin-logging, anko logging etc.


text:
Q: perform a mongoose query in querystring I'm trying to do a simple mongoose query using the query string.
This works
router.get('/', function(req,res) {
    myModel.find({name:"test e"}, function(err,data){
        if(err) console.log(err)
        res.json(data);
    });

});

This doesn't work (I get the whole collection)..
router.get('/', function(req,res) {
    console.log(req.query.q)
    myModel.find(req.query.q, function(err,data){
        if(err) console.log(err)
        res.json(data);
    });

});

with this request
/api/myModel?q={name:"test e"}

I don't think it's an url encoding issue since I print the 'q' var and it looks fine server side.
Side question: if this isn't the standard mode, what's the RESTful standard way to query a db?
Edit for more general details:
I don't need a simple access by id or name like Ashley B suggests, I need a proper search engine for my db (the user, using a graphic web interface, have to be able to query each field separately, potentially)
Edit 2:
thanks to Blakes Seven I solved my initial problem, but if you know or use a better way to perform a complex query I would happy to discuss. Maybe I should expose anther resource "/api/seach"?

A: I think I can answer your first question by answering your second (side question).
Let's say you have a User model, normally you'd have an endpoint to get all users, like so:
router.get('/users', function(req, res) {
    // find all users
    users.find({}, function(err, data){
        if(err) console.log(err)
        res.json(data);
    });
});

To find a specific user you then have an endpoint like so:
router.get('/users/:name', function(req, res) {
    // get the user's name from the url and find that user
    users.find({name: req.params.name}, function(err, data){
        if(err) console.log(err)
        res.json(data);
    });
});

So rather than passing the whole query through the query string, you just find use a specific part. Allowing the users to directly access your data with their own queries makes it much much harder to secure.

A: I would recommend you to use some library to parse the querystrings to mongoDB queries. It would fix your problem and make your code better.
querymen would help you by transforming /myModel?q=test+e into {name: 'test e'}, giving you full control over the querystring schema.
var querymen = require('querymen')

// querymen.middleware() defines an express middleware with querystring schema
router.get('/', querymen.middleware({
  q: {
    type: String,
    paths: ['name']
  }
}), function(req, res) {
  console.log(req.querymen.query) // {name: 'test e'}
  myModel.find(req.querymen.query, function(err,data){
    if(err) console.log(err)
    res.json(data);
  });
});

A: The proper query should look like this:
/api/myModels?name=test%20e

The myModals part is in plural.
Check here: How to design RESTful search/filtering?


text:
Q: Do global execution context gets off the call stack while browser still fetches something? I have a code block something like this:
function printData(response) {
  response.json()
          .then(data => console.log(data.name));
}

const fetchedData = fetch("http://localhost:3000/url");

fetchedData.then(printData);

console.log("First console output");

This code executes directly whenever the page loads. My endpoint fetch("http://localhost:3000/url") returns response after 200ms.
Since the XHR will resolve after all global execution context finishes, it should get out of the call stack. But does global execution really gets out of the call stack? Because there is still a task to process, still we need to run printData function after request resolves. Will global execution context wait until request resolves or does it get out of the call stack even there are some requests still being fetched?
Flow is like this;

*

*printData set to memory

*fetchedData variable set to memory and browser feature xhr initiates
the request.

*printData assigned to fetchedData promise.

*console output.

Now global execution context finishes but still, we are waiting for the response of the fetch("http://localhost:3000/url");. Will the global execution context get out of the call stack or will it wait the request to fulfill?


text:
Q: Is there a generic collection that I can access the elements through the indexer by string key and by index? I want to declare a generic collection of objects and be able to access them through the indexer either by a key string value or by index. How do I do this? Is there is an out of the box .Net class that doesn't require sub-classing?
class Program
{

    static void Main(string[] args)
    {

        System.Collections.Generic.WhatKindOfCollection<PageTab> myPageTabs
            = new System.Collections.Generic.WhatKindOfCollection<PageTab>();

        PageTab pageTab1 = new PageTab();
        pageTab1.ID = "tab1";
        myPageTabs.Add(pageTab1);

        myPageTabs.Add(new PageTab("tab2"));

        myPageTabs[0].label = "First Tab";
        myPageTabs["tab2"].label = "Second Tab";

    }

    public class PageTab
    {
        public PageTab(string id)
        {
            this.ID = id;
        }

        public PageTab() { }

        //Can I define ID to get the key property by default?
        public string ID { get; set; }

        public string label { get; set; }
        public bool visible { get; set; }
    }
}

A: It looks like you're looking for something derived from System.Collections.ObjectModel.KeyedCollections.
I don't think that the specific class you're looking for exists in the .NET framework, so you'll probably have to subclass it yourself.
KeyedCollection is a base class for objects where the key is part of the object.  This means that when you access it with an integer index, you'll get back the original object instead of a KeyValueCollection.
It's been a while since I've used it, but I don't remember it being too difficult.
Edit:  Another code option for you.  It was easier than I remember:
public class MyKeyedCollection<TKey, TItem> : KeyedCollection<TKey, TItem>
{
    public MyKeyedCollection(Func<TItem, TKey> keyFunction)
    {
        _keyFunction = keyFunction;
    }

    private Func<TItem, TKey> _keyFunction;

    protected override TKey GetKeyForItem(TItem item)
    {
        return _keyFunction(item);
    }
}

To use:
var myPageTabs = new MyKeyedCollection<String, PageTab>(i => i.ID);

Or pre-LINQ:
public class MyKeyedCollection<TKey, TItem> : KeyedCollection<TKey, TItem>
{
    public MyKeyedCollection(String keyProperty)
    {
        _keyProperty = keyProperty;
    }

    private String _keyProperty;

    protected override TKey GetKeyForItem(TItem item)
    {
        return (TKey)item.GetType().GetProperty(_keyProperty).GetValue(item, null);
    }
}

and
MyKeyedCollection<String, PageTab> myPageTabs = new MyKeyedCollection<String, PageTab>("ID");

A: This is effectively the OrderedDictionary class.  However, it is, unfortunately, not a generic class, so you'd have to include casts, or wrap it in your own collection type.
There is no generic equivelent in the base class libraries, though KeyedCollection<T,U> provides the base class infrastructure to implement your own version.
The simplest alternative is just to maintain two collections - a Dictionary<string, PageTab> and a List<PageTab>.  When you create your items, you can add it to both collections, and access via the appropriate one.  Since PageTab is a class, the extra overhead is minimal (since you're just storing object references).  This could also be easily wrapped into a class:
public class IndexedDictionary<T, U>
{
    private Dictionary<T,U> dictionary = new Dictionary<T,U>();
    private List<U> list = new List<U>();

    public void Add(T key, U value)
    {
        list.Add(value);
        dictionary.Add(key, value);
    }

    public U this[int index]
    {
       get { return list[index]; }
    }
    public U this[T key]
    {
       get { return dictionary[key]; }
    }
}

Granted, you'd potentially want to implement some appropriate interfaces as well (such as IEnumerable<U>), but the above would accomplish your goals as listed in the question.

A: Why don't you use a dictionary?
Dictionary<string, PageTab> myDictionary = new Dictionary<string, PageTab>();
myDictionary.Add("tab1", new PageTab("tab1"));
PageTab myPageTab = myDictionary["tab1"];

EDIT
To avoid typing the key twice (once as dictionary key and once in the constructor) you could extend the dictionary. Create the following class in the toplevel of your namespace:
public static class Extensions
{
    public static void AddPageTab(this Dictionary<string, PageTab> mydict, PageTab pt)
    {
        mydict.Add(pt.ID, pt);
    }
}

And you call simple add the PageTab like this:
myDictionary.AddPageTab(new PageTab("tab1"));


text:
Q: Solve an integral equation in which there is Cauchy-type singularity I'm looking for a solution to an integral equation:
Given a function $f(x)$, find a function $g(x)$ such that $$\int_0^1 \frac{g(s)}{x-s} ds = f(x), \forall x \in [0,1]$$ satisfies.
Function $f(x)$ is actually a series of trigonometric functions, but let us have a simple start, say $f(x)=\cos x$. The work I'm doing now is to solve the integral numerically using Gauss-Chebyshev quadrature. Then I discretize $x$ and have a system of equations, which will give me discrete $g(s)$. I just feel the tricky part may be the discretization on $x$ and $s$ as they have the same range, and this can really affect my result.
My questions are:

*

*Is there an analytical solution to $g(x)$ and is it unique?

*What would be a good treatment for the discretization to solve the integral?

Thank you for your time to reading this. Any thoughts will be appreciated.

A: To partially answer your question, referring to Singular integral equations - Estrada, Kanwal, section 3.2. The Cauchy integral equation
$$P.V.\int_0^1 \frac{g(t)}{t-s} dt = f(s)$$
Has a solution given by
$$g(s) = \frac{c}{\pi \sqrt{s(1-s)}} + \frac{1}{\pi^2 \sqrt{s(1-s)}} \int_0^1 \frac{\sqrt{t(1-t)}f(t)}{s-t}dt$$
where $c$ is an arbitrary constant. And thus, you have an analytic solution.
Another source that comes to my mind right now is the Handbook of integral equations - Polyanin Manzhirov, section 12.4-3, where it shows solutions to a similar equation in terms of the boundability of the solution. The downside of this one is it doesn't show any of the theory behind it, only states the solution.
That's what I can say by now.


text:
Q: Bucle for con distintos resultados Actualmente tengo 3 botones en un html dentro de un div. Dichos botones los selecciono con un var ff = f0.querySelectorAll("button") (f0 hace referencia al div donde están los botones).
Puedo acceder a los 3 botones poniendo ff[0,1,2].
El problema viene cuando, a la hora de agregar funcionalidad a los botones:

      var tem = document.querySelectorAll("template");

        this.id=id;

      let f0 = document.createElement('div');
      f0.innerHTML = tem[3].innerHTML;
      document.getElementById(id).appendChild(f0);

      this.contentForm = f0.querySelector(".content-form");

      var ff = f0.querySelectorAll("button");

      for(let i = 0; i < ff.length; i++){
         f0.querySelector(ff[i]).addEventListener("click", ()=>{
            console.log('hola');
         })
      }
   }

En el ultimo bucle for, no puedo poner un querySelector del ff[i], a pesar de estar declarado. Imagino que es porque no sigue la estructura correcta. Me gustaría saber cómo se hace.
A parte de eso, una vez esté solucionado de cómo nombrar a los 3 botones en un simple bucle, ¿cómo podría asignar una función distinta a cada botón? Es decir:
En el ejemplo los 3 botones, una vez se consiga seleccionar a los 3, una vez hecho clic, TODOS imprimen por consola un "hola". Me gustaría que uno dijera hola, otro adios, y otro bienvenido.
**
[EDIT]
**
Tratando de hacer la asignación de funcionalidades en el bucle for, me topo con que no estoy asignando nada realmente:
let f0 = document.createElement('div');
      f0.innerHTML = tem[3].innerHTML;
      document.getElementById(id).appendChild(f0);

      this.contentForm = f0.querySelector(".content-form");

      var ff = f0.querySelectorAll("button");
      console.log(ff);

      for(let i = 0; i < ff.length; i++){
         if(ff[0].clicked == true){
            console.log('hola');
         }
      }

Según la docu, verificar si un botón ha sido clicado es así mediante javascript, sin necesidad de un addEventListener, dentro de un if...else
[EDIT 2]
Ahora me funciona el clicker, PERO, lo repite TRES veces...
for(let i = 0; i < ff.length; i++){
         if(ff[0].addEventListener("click", ()=>{
            console.log('hola');
         }));
      }


text:
Q: Two concatenated templates with each a concept-constraint Consider the following code:
#include <iostream>
#include <utility>
#include <type_traits>

using namespace std;

template<typename K>
    requires is_nothrow_move_constructible<K>::value
struct S
{
    using value_type = pair<K, K>;
    struct iterator
    {
    };
    template<typename P>
        requires is_constructible<value_type, P &&>::value
    pair<iterator, bool> insert( P &&x );
};

template<typename K>
    requires is_nothrow_move_constructible<K>::value
template<typename P>
    requires is_constructible<typename S<K>::value_type, P &&>::value
pair<typename S<K>::iterator, bool> S<K>::insert( P &&x )
{
}

int main()
{
    std::cout << "Hello World!\n";
}

Why does this compile with g++ 11.1.0 and not with clang 12.0.0. The clang-error is:
xxx.cpp:24:43: error: out-of-line definition of 'insert' does not match any declaration in 'S<K>'
pair<typename S<K>::iterator, bool> S<K>::insert( P &&x )
                                          ^~~~~~
1 error generated.

clang++ 13.0.0 under Windows does report the same error.
MSVC 19.29.30136 gives the following error:
xxx.cpp
xxx.cpp(25): error C2244: 'S<K>::insert': unable to match function definition to an existing declaration
xxx.cpp(24): note: see declaration of 'S<K>::insert'
xxx.cpp(25): note: definition
xxx.cpp(25): note: 'std::pair<S<K>::iterator,bool> S<K>::insert(P &&)'
xxx.cpp(25): note: existing declarations
xxx.cpp(25): note: 'std::pair<S<K>::iterator,bool> S<K>::insert(P &&)'

Is there a workaround ?

A: When you have a definition of a function template that is separate from the declaration, the two have to match exactly - be token for token identical (modulo parameter names). In your case, they don't match - you have value_type in one case and typename S<K>::value_type in the other, so this is ill-formed, no diagnostic required.
The easy workaround is: just define the function in-line so you don't have even have to worry about copying the declaration. This definitely works, and is almost always clearer anyway.
If you really want out-of-line definitions, then you need to restructure your declaration so that it allows you to name value_type the same way in both cases:
template<typename K>
    requires is_nothrow_move_constructible_v<K>
struct S
{
    using value_type = pair<K, K>;
    struct iterator
    { };

    template<typename P>
    auto insert( P &&x ) -> pair<iterator, bool>
        requires is_constructible_v<value_type, P &&>;
};

template<typename K>
    requires is_nothrow_move_constructible_v<K>
template<typename P>
auto S<K>::insert( P &&x ) -> pair<iterator, bool>
    requires is_constructible_v<value_type, P &&>
{
}

On the several advantages of the trailing-return-type approach to writing functions is that the class itself is in scope when you're doing name lookup in the contexts after it appears. So in the definition above, iterator and value_type are looked up in S<K>, which allows you to use the same token sequence (and also just lets you avoid repeating them for no reason).

Also, I changed your traits to use the form meow_v<T> instead meow<T>::value, since that's shorter.


text:
Q: I want to count values in name column if there are only in sequence form in SQL Server create table #t (Id int, Name nvarchar(max))

insert into #t
values (1, 'ABC'), (2, 'ABC'), (3, 'BBB'), (4, 'BBB'),
       (5, 'BBB'), (6, 'BBB'), (7, 'CCC'), (8, 'BBB'),
       (9, 'BBB'), (10, 'ABC')

I want to count values in name column if there are only in sequence form
how I get this result as shown in table below:
| Name | Repetition |
('ABC'),    2
('ABC'),    2
('BBB'),    4
('BBB'),    4
('BBB'),    4
('BBB'),    4
('CCC'),    1
('BBB'),    2
('BBB'),    2
('ABC'),    1

A: Try this multiple cte solution:
;with name_change as (
  select *, case when name=lag(name, 1) over (order by id) then 0 else 1 end as indicator
  from t
), name_group as (
  select name, sum(indicator) over (order by id) as g
  from name_change
)
select name, count(name) over (partition by g) from name_group

Not sure about the efficiency though, but I think it gives what you need...
SQLFiddle

A: You can also try gaps and islands type approach of counting consecutive rows like below
See live demo
select
    Name,
    Repetition= count(1) over(  partition by r,Name )
from
(
    select
    *,
    r=id-row_number() over(partition by Name order by Id)
    from #t
 ) t
order by id


text:
Q: Music21: Get all Notes per Instrument from a MIDI File I am parsing a MIDI file as instructed here. My code looks like this:
from music21 import converter,instrument # or import *
file = converter.parse('sample.mid')
components = []
for element in file.recurse():
    components.append(element)

The components list now contains data as follows:
<music21.stream.Score 0x7f50314ca390>,
<music21.stream.Part 0x7f50314caf10>,
<music21.instrument.Instrument Acoustic Guitar>,
<music21.instrument.Instrument Acoustic Guitar>,
<music21.tempo.MetronomeMark allegro moderato Quarter=130.0>,
<music21.meter.TimeSignature 4/4>,
<music21.note.Note E>,
<music21.note.Note B>,
<music21.note.Note E>,
<music21.note.Note B>,
<music21.note.Note E>,
<music21.note.Rest rest>,
.
.
.
<music21.chord.Chord B3 E3>,
<music21.chord.Chord B3 E3>,
<music21.chord.Chord B3 E3>,
<music21.chord.Chord B3 E3>,
<music21.chord.Chord B3 E3>,
<music21.chord.Chord B3 E3>,
<music21.chord.Chord D4 F#3>,
<music21.chord.Chord D4 F#3>,
<music21.chord.Chord D4 F#3>,
.
.
.
<music21.stream.Part 0x7f50309b99d0>,
<music21.instrument.Instrument Electric Guitar>,
<music21.instrument.Instrument Electric Guitar>,
<music21.meter.TimeSignature 4/4>,
<music21.note.Rest rest>,
<music21.note.Note E>,
<music21.note.Note F#>,
<music21.note.Note G>,
<music21.note.Note A>,
<music21.note.Note G>,
<music21.note.Note E>,
<music21.note.Rest rest>,

My aim is to segregate notes according to each instrument which is listed in a tag like <music21.instrument.Instrument Electric Guitar>. How do I achieve this?

A: I think you'll want the instrument.partitionByInstrument() function, which will separate your stream into different parts according to the instrument.


text:
Q: Install4j delete all files during rollback When the installer throws an error or the installation gets aborted and starts the rollback, it does not delete the files that were not added to the distribution tree, but created during the installation instead.
So what I tried is register an installerEventListener and delete the remaining files on "AFTER_ROLLBACK_ACTION", but it seems that it gets triggered after each rollback action. If I delete the files before the "Install files" rollback, the rollback throws an error, because it can't find the files, that were installed.
How can I make sure that these files are deleted during a rollback?


text:
Q: Frame rate drops / efficiency problem in three.js Upon running there is a slow but consistent drop in fps. I have tried to identify the responsible function and it seems to be that:
updatepoints() and rotateTriangle() seem to be the main culprits but it's clear I have misunderstood something or used an inefficient means of calculating something somewhere
Upon further inspection using browser tools it seems to be an array and an object that are filling up the memory which I'm guessing is what is causing the frame drops.
I have also noticed that the buffer in the performance tab for the browser tools is filling up
I know bufferGeometry is the more efficient means of creating objects but I'd still like to know the cause the performance issues
Sorry to just dump code but I feel as though it'll be something obvious.
Any advice or ways of going about finding the problem and solution would be greatly appreciated
//every scene needs these
var scene, camera, renderer, controls;

//links div with canvas
var canvas = document.getElementById('canvas');

// What I need are number of particles and the length the curve goes to be uncoupled
// Each part of degree array serves one particles
// If I added a factor so:
// factor * coord *

//creating particles
var particleCount = 360;
var particles = [];
var particles2 = [];
var particles3 = [];
var SPEED = 0.01;

var radians, y, x;
var centerX = 0;
var centerY = 0;
var radius = 231.84;
var pointPositions=[];

var vupdateXvertices, updateYvertices, updateXvertices2, updateYvertices2,
updateXvertices3, updateYvertices3;

var pivot1;
var parent;

var pointsX = [];
var pointsY = [];

var particleMaterial = new THREE.MeshBasicMaterial({
    color: 0x7a7a7a,
    transparent: true,
    opacity: 0.8
});

init();
animate();

function init() {
  scene = new THREE.Scene();
  //setup camera for scene
  //PerspectiveCamera(fov, aspect, near, far [In terms of camera frustum plane])
  camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 10000 );
  camera.position.z = 1000;
  //setup renderer for scene (generation of whatever you've made)
  renderer = new THREE.WebGLRenderer();
  renderer.setClearColor(0x31AED1, 1);
  renderer.setSize( window.innerWidth, window.innerHeight );
  //OrbitControls(Camera, HTMLDOMElement)
  controls = new THREE.OrbitControls( camera, renderer.domElement );
  // Set to true to enable damping (inertia), which can be used to give a sense
  //of weight to the controls. Default is false.
  controls.enableDamping = true;
  controls.dampingFactor = 0.25;
  controls.enableZoom = false;
  console.log("Called");
  fillSceneWithParticles();
  fillSceneWithShapes();
  canvas.appendChild( renderer.domElement );
  renderer.render( scene, camera );
}

function fillSceneWithParticles() {
  var particleGeometry = new THREE.SphereGeometry(3, 32, 32);
  parent = new THREE.Object3D();
  scene.add(parent);

  for (var i = 0; i < particleCount; i++) {
     particles[i] = new THREE.Mesh( particleGeometry, particleMaterial );
     particles[i].position.x = 0;
     particles[i].position.y = 0;
     particles[i].position.z = (0);

     particles2[i] = new THREE.Mesh( particleGeometry, particleMaterial );
     particles2[i].position.x = (200);
     particles2[i].position.y = (-115.57);
     particles2[i].position.z = (0);

    particles3[i] = new THREE.Mesh( particleGeometry, particleMaterial );
    particles3[i].position.x = (0);
    particles3[i].position.y = (231.84);
    particles3[i].position.z = (0);

    scene.add(particles[i]);
    scene.add(particles2[i]);
    scene.add(particles3[i]);
  }
}

function fillSceneWithShapes() {
  //Add a 2d Triangle W centre = 200, 115.57
  var geometry = new THREE.Geometry();
  geometry.vertices.push( new THREE.Vector3(-200, -115.57, 0));
  geometry.vertices.push( new THREE.Vector3( 200, -115.57, 0 ));
  geometry.vertices.push( new THREE.Vector3( 0, 231.84, 0 ));
  geometry.vertices.push( new THREE.Vector3( -200, -115.57, 0 ));
  var material = new THREE.LineBasicMaterial( { color: 0xffffff, linewidth: 10 } );
  line = new THREE.Line( geometry, material );
  scene.add(line);
}

function rotateTriangle() {
  var geom = line.geometry.clone();
  geom.applyMatrix(line.matrix);
  updateXvertices = geom.vertices[0].x;
  //The circle that we use to place our points
  var centerX = 0;
  var centerY = 0;
  var radius = 231.84;
  for(var degree = 90; degree < 450; degree++){
    var radians = degree * Math.PI/180;
    var x = centerX + radius * Math.cos(radians);
    var y = centerY + radius * Math.sin(radians);
    pointsX[degree - 90] = x;
    pointsY[degree - 90] = y;
  }
}

function updatePoints() {
    //link counter with number of degrees initially created
    //These are intialised because V1 = 120 degrees from V0 and V2 = 240 degrees
    var counter = 120;
    var counter2 = 240;
    var zCounter = 0;
    var curveFactor = 1;
    var material = new THREE.LineBasicMaterial( { color: 0xffffff, linewidth: 10 } );
    var secondTriangle = new THREE.Geometry();

    for (var i = 0; i < particleCount; i++) {
      parent.add(particles[i]);
      //Plot points around the circle relative to vertices of triangle
      particles[i].position.x = (pointsX[i]);
      particles[i].position.y = (pointsY[i]);
      particles[i].position.z = zCounter * curveFactor;

      //If array index out of bounds then loop back to the start of array
      //i.e. Go back around the circle relative to the triangle vertices
      parent.add(particles2[i]);
      if (counter == 360) {
        counter = 0;
      }
      particles2[i].position.x = (pointsX[counter]);
      particles2[i].position.y = (pointsY[counter]);
      particles2[i].position.z = zCounter * curveFactor;
      counter++;

      if (counter2 == 360) {
        counter2 = 0;
      }
      parent.add(particles3[i]);
      particles3[i].position.x = (pointsX[counter2]);
      particles3[i].position.y = (pointsY[counter2]);
      particles3[i].position.z = zCounter * curveFactor;
      counter2++;
      zCounter++;
    }
      //Give the second triangle the position of the last particles in array
      secondTriangle.vertices.push( new THREE.Vector3(particles[particleCount-1].position.x, particles[particleCount-1].position.y, particles[particleCount-1].position.z ));
      secondTriangle.vertices.push( new THREE.Vector3(particles2[particleCount-1].position.x, particles2[particleCount-1].position.y, particles2[particleCount-1].position.z ));
      secondTriangle.vertices.push( new THREE.Vector3(particles3[particleCount-1].position.x, particles3[particleCount-1].position.y, particles3[particleCount-1].position.z ));
      secondTriangle.vertices.push( new THREE.Vector3(particles[particleCount-1].position.x, particles[particleCount-1].position.y, particles[particleCount-1].position.z ));
      line1 = new THREE.Line( secondTriangle, material );
      scene.add(line1);
      parent.add(line1);
}

function animate() {
    requestAnimationFrame( animate );
    controls.update();
    rotateTriangle();
    updatePoints();
    line1.rotation.z -= SPEED *2;
    line.rotation.z -= SPEED *2;
    parent.rotation.z -= SPEED *2;
    renderer.render( scene, camera );
}

A: In retrospect it seems obvious what the problem was.
Since I had geometry.vertices.push inside my animate loop it was continuously pushing new Vectors to a buffer.
I just had to move the pushing of those vertices and that solved any frame rate and memory problems I was having


text:
Q: How to get the output of timeout command without using a shell script I am using a ssh command executor in java which runs the command and gets the output in stderr, stdout and an integer exit value. I am trying run a command with timeout like,
timeout 5s COMMAND

Is there a way to get a response in the stderr or the stdout so that I can know whether the command was timed out or not?

A: You can use shell scripting capabilities which should work fine with the ssh command executor.
timeout 5s sleep 1s && (>&2 echo "Successful") || (>&2 echo "Timed out")


text:
Q: select table, check and prompt when value match I have my table named sup_mon:
genmat_id    mat_name  Stock_balance
1            bar           50
5            steel         10
20           bolt          5

HTML:
        <?php
        $resource2=mysql_query("SELECT * FROM genmaterial WHERE mat_name='$mat' AND size='$unit' ORDER BY genmat_id DESC limit 0,1",$con);

        while($rows2=mysql_fetch_array($resource2))
            {

            ?>
        <form name="stockout" method="post" action="stock_out.php">
                Material
                <input  maxlength="25" type="text" readonly name="material" id="material" required="required" style="height:20px"  value="<?php echo $rows['mat_name']; ?>" >

            <input type="number" name="stock_out"/>
 <input type="submit" name="submit" value="submit"/>
        </form>
    <?php };?>

How can I check first stock_balance from the sup_mon table  for the material in the material text box from the html? and prompt reorder message when stock_balance of that particular material is less than 10?

A: You would need to add a second query inside the loop to check if stock_balance is less than 10 like this:
<?php
    $resource2=mysql_query("SELECT * FROM genmaterial WHERE mat_name='$mat' AND size='$unit' ORDER BY genmat_id DESC limit 0,1",$con);

    while($rows2=mysql_fetch_array($resource2))
        {
            $resource3=mysql_query("SELECT * FROM sup_mon WHERE genmat_id = '" . $rows2['genmat_id'] . "'",$con);
            $row3 = mysql_fetch_array($resource3);
            if($row3['Stock_balance'] < 10)
            {
                echo "Stock balance is less then 10 please reorder";
                header("refresh: 5; order.php");
            }
        ?>
    <form name="stockout" method="post" action="stock_out.php">
            Material
            <input  maxlength="25" type="text" readonly name="material" id="material" required="required" style="height:20px"  value="<?php echo $rows['mat_name']; ?>" >

        <input type="number" name="stock_out"/>
<input type="submit" name="submit" value="submit"/>
    </form>
<?php }; ?>


text:
Q: Displaying Dates from MongoDB with Express.js I saved few datasets to MongoDB using mongoose.js. But I got a problem with displaying them on an html site using express.js and ejs.
Here is my scenario:
Model
var mongoose = require('mongoose');

var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

var ItemSchema = new Schema({
    _id: ObjectId,
    creationTime: Date,
    modificationTime: Date,
    title: String
});
var Item = mongoose.model('item', ItemSchema);
module.exports.Item = Item;

Route:
app.get('/item/:id', function(req, res) {

    Item.findById(req.params.id, function(err, doc){

        console.log(doc); //This check displays everything correctly on console

        res.render('item.html.ejs', {
            item : doc
        });
    });
});

View:

<%= item.title %>:

Creation: <%= item.creationDate %>

Modification: <%= item.modificationDate %>

The result of this setting is that title is being displayed correctly while both dates are undefined.
I assume it has something to do with MongoDB's ISODate format. But I can't find a solution on how to convert it for displaying in html views.
I appreciate your help. Cheers

A: I have the following helpers using moment.js in my projects.
date: function(date){
  moment(date).format('YYYY-MM-DD hh:mm:ss');
},
fromNow: function(date){
  moment(date).fromNow()
}

A: If you just copied and pasted the code the solution is very very simple.
In your model you defined creationTime and modificationTime in your template you try to access item.creationDate and item.modificationDate.
After that change you should be able to see something other then undefined, but you probably still need to convert this into a proper date format.

A: I add an ejs filter using the example above, but I had to change it a little bit to get it to work:
Create the 'created_at' attribute on the mongoose schema and automatically create it on save():
var ItemSchema = new Schema({
    name    : { type: String, required: true, trim: true }
  , created_at    : { type: Date }
});

ItemSchema.pre('save', function(next){
  if ( !this.created_at ) {
    this.created_at = new Date;
  }
  next();
});

Install moment (and write to package.json)
npm install moment --save

Add the filter in app.js or wherever else you define filters for ejs:
var moment = require('moment');

ejs.filters.fromNow = function(date){
  return moment(date).fromNow()
}

Use the filter in page.ejs
<%=: item.created_at | fromNow %>


text:
Q: /'twəni/ ; /ˈtwenti/
"You mean it is only twenty dollars?" (audio linked)

I hear /ˈtwəni/ for twenty. I can see that in /ˈtwenti/, the /t/ sound has been weakened, in the audio. However does he weaken the /e/ sound, too,  into schwa, /ə/? If it is, do you expand the use of schwa even to this word?

A: To answer your first question of "Does he weaken the /e/ sound, too, into a shwa, /ə/?" the answer is, Yes, and goes further to make it a long schwa, /ɛ/.
As to your second question, use of the schwa does indeed extend to this word, in which case the (long) schwa can either be pronounced like the common /e/ sound in penny, or like the /u/ sound in supple.
A note on the original word, twenty: there are two proper pronunciations according to both Dictionary.com/Random House and Merriam-Webster; /ˈtwɛn ti/ (twen-tee) and /ˈtwʌn ti/ (twuhn-tee). Further weakening it to /ˈtwʌn i/ (twuhn-ee) as the speaker is doing in the sound byte could be considered regional dialect (and commenters in your original post have posited as much).

A: No, it's not a schwa, but /ɛ/. It's unlikely to find schwa in stressed syllables.
The speaker pronounces twenty as [ˈtwɛni], more precisely:

[ˈtʰw̥ɛ̈̃ni]

He has the same vowel as in bed, but a bit centralised and nasalised (in anticipation of the following /n/), so it sounds closer to schwa.
In most American accents, when a stressed syllable ends in an N and the next unstressed syllable starts with a T, the T is usually dropped, so in.ter.net becomes innernet, coun.ter becomes counner, twen.ty becomes twenni etc.

 - superscript h [ʰ]: aspirated
 - two superscript dots [ ̈]: centralised
 - tilde [ ̃]: nasalised


text:
Q: How to query Users/Recipients sharing Contacts/Calendars with Current Outlook User? As I mentioned in a former Question it is no problem to get shared contacts in Outlook via MAPI. But this is only possible, if you know the Users/Recipients sharing contacts (or also calendar) with the Current Outlook User.
Now back to my question: How can I get a list of Recipients sharing their contacts with me?
With the list I would do a foreach creating the Recipients and than access the shared folder.
// Get recipients
IList<string> recipientsSharingContacts =  **???** ;

// Import/Read shared contacts
foreach (string recip in recipientsSharingContacts){

    // Open Shared Folder
    MAPIFolder sharedContactsFolder =
      Application.Session.GetSharedDefaultFolder(recip, OlDefaultFolders.olFolderContacts)

    // Import Contacts
    ...

}

Hope someone can help me out.

A: If someone is interested in the solution, here is how I do it:
ContactsModule module = (ContactsModule)outlookObj.ActiveExplorer().NavigationPane.Modules.GetNavigationModule(OlNavigationModuleType.olModuleContacts);
foreach (NavigationGroup navigationGroup in module.NavigationGroups) {
     foreach (NavigationFolder navigationFolder in navigationGroup.NavigationFolders) {
          foreach (var item in navigationFolder.Folder.Items) {
                     // Found Folders are: Contacts, Suggested Contacts and Shared Contact Folders

                     // Import/Read ContactItems
                     ...
                }


text:
Q: Finding the location of a TD in a table So let's say I have a table, and I want to manipulate a specific  in it:
HTML:

1	 2

3	 4

5	 6

Javascript:
document.getElementsByTagName("table")[0].rows[2].cells[0];

This will help me REACH a specific cell in a table.

My question is this:
Say I have a specific  inside a table:
var td = document.getElementById("hi")

I want to KNOW its location in the table, so I can be able to reach it using table.rows[x].cells[y]
How can I check this location?

A: The cellIndex property of a td element gives the index of the cell in the row.
The rowIndex property of a tr element gives the index of the row in the table.
So,
var td = document.getElementById("hi");
var x = td.cellIndex;
var y = td.parentNode.rowIndex;

A: You will need something like this:
function getRowCellPosition(table, cell) {
    for (var i = 0; i < table.rows.length; i++) {
        for (var j = 0; j < table.rows[i].cells.length; j++) {
            if (table.rows[i].cells[j] === cell) {
                return {
                    row: i,
                    cell: j
                };
            }
        }
    }
    return null;
}

or more simple:
function getRowCellPosition(cell) {
    return {
        row: cell.parentNode.rowIndex,
        cell: cell.cellIndex
    }
}

A: I'd suggest, as you imply you know which specific cell you want to find, though currently untested:
var td = document.getElementById("hi"),
    col = td.cellIndex,
    row = td.parentNode.rowIndex;

A: Simply create a for loop that goes through each row and column and compare the TD in that index against the one you want.

A: Try this:
for row:
Array.slice(el.parentNode.parentNode.children).indexOf(el.parentNode)

for col:
Array.slice(el.parentNode.children).indexOf(el)

The slice magick is because el.parentNode.children is not an array.
edit: I wasn't aware of td.cellIndex and tr.rowIndex. Definitely use them.


text:
Q: android back navigation on child method? im creating redirect to some view on object method. this method doesn't use the parent view.
it works but when i click back navigation it doesn't showing the previous page (previous page is object oncreate() method itself), it return to the top parent activity. here is my code :
Object method on create :
public class FormDatabase extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.form_database);

method member of object method :
 public void showArrayResult(View view)
    {
        setContentView(R.layout.profile_listview);

how can when i click back navigation i would return to previous object onCreate() method NOT the parent method (MAIN_ACTIVITY).
Hope my description is clear enough. Thanks.

A: To switch between different views in the same activity, and still maintain the ability to use the back stack (back button), you should probably use Fragments.
If the two views are completely independent then you should consider moving it into its own separate Activity.

A: You can override the onBackPressed() callback method to interrupt killing the activity and instead SetContentView as you did in onCreate()
EDIT
But Nic is right about moving to a fragment or another activity.
A component such as an activity should manage one task. Otherwise it is considered as bad practice.


text:
Q: Cloudformation RDS template cannot resolve security group id I have a CF that deploys a MySql database and some resources to AWS. I want the script to be general and should be able to use it for different environments. For one of those resources (master db), I have a different security group configuration which is environment-specific. I create security groups for each environment conditional and are called VaultSecurityGroupInEnv1, VaultSecurityGroupInEnv2, etc. There is map that saves names of security groups for each environment. here are my configurations:
Mappings:
  RegionMap:
    environment1:
      VaultSG: VaultSecurityGroupInEnv1
    environment2:
      VaultSG: VaultSecurityGroupInEnv2

Resources:
  VaultSecurityGroupInEnv1:
    Condition: IsEnv1Environment

  VaultSecurityGroupInEnv2:
    Condition: IsEnv2Environment

  MasterDB:
    Type: AWS::RDS::DBInstance
    Properties:
      VPCSecurityGroups:
        - !ImportValue DbSgId
        - !Sub
          - '${vGroup}'
          - vGroup: !FindInMap
            - RegionMap
            - !Ref Environment
            - VaultSG

for which I get the following error:
Invalid security group , groupId= vaultsecuritygroupinF.groupid, groupName=. (Service: AmazonRDS; Status Code: 400; Error Code: InvalidParameterValue;

The output from !Sub is retrieved and resolved as a name string, not as a resource. Using !Ref vaultsecuritygroupinF.GroupId works fine. any idea how to use map and sub correctly?
Thanks

A: You can't use FindInMap the way you are trying. It will just resolve to the literal strings VaultSecurityGroupInEnv1 or VaultSecurityGroupInEnv2. It will not resolve to the actual resources of the same name.
Instead, I think the following should be possible:
MasterDB:
  Type: AWS::RDS::DBInstance
  Properties:
    VPCSecurityGroups:
      - !ImportValue DbSgId
      - !If
        - IsEnv1Environment
        - !Ref VaultSecurityGroupInEnv1
        - !Ref "AWS::NoValue"
      - !If
        - IsEnv2Environment
        - !Ref VaultSecurityGroupInEnv2
        - !Ref "AWS::NoValue"


text:
Q: save textfield on top of imageView (swift3) I would like to save a whatever is printed on top of the imageView. I tried to place 2 textfields over a imageView but its not saving.
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

    @IBOutlet weak var textFiel1: UITextField!

    @IBOutlet weak var textFiel_2: UITextField!

    @IBOutlet var theImage: UIImageView!

    @IBAction func save(_ sender: Any) {
              UIImageWriteToSavedPhotosAlbum((theImage.image)!, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
    }}

A: You need use the drawHierarchy method of your UIImageView, but first you need to be sure that all what you want to draw is subView of your desired view in this case your UIImageView
UIGraphicsBeginImageContext(self.theImage.bounds.size)
self.view.drawHierarchy(in: self.theImage.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
//you can do whatever you need with the image

Hope this helps you


text:
Q: Running OTB Random Forest Classification I am having trouble processing a satellite image using the RF (Random Forest) classification, that is a machine learning algorithm in the Orfeo Toolbox of QGis 2.18.1.
When I run the Tool, the processing takes less than a second but I do not have any result. So, I have neither an error nor a result.
I have tried changing parameters and inputs but nothing is showing up at the end of the process.
Please can anyone shed light on this problem for me?
A- Algorithm Compute Images second order statistics
C:\OTB\bin\otbcli_ComputeImagesStatistics
-il
"D:\documents\GIS\Formation QGis\Donnees\Raster\Imagerie.tif "
-bv
0
-ram
512
-out
"C:/Users/Yannick.Doungmo/Desktop/GDBQC/sec_stats.xml"
2019-02-17 18:08:28 (INFO): Default RAM limit for OTB is 128 MB
2019-02-17 18:08:28 (INFO): GDAL maximum cache size is 811 MB
2019-02-17 18:08:28 (INFO): OTB will use at most 4 threads
2019-02-17 18:08:28 (INFO): No kwl metadata found in file D:\documents\GIS\Formation QGis\Donnees\Raster\Imagerie.tif
2019-02-17 18:08:28 (INFO): Estimated memory for full processing: 3433.11MB (avail.: 512 MB), optimal image partitioning: 7 blocks
2019-02-17 18:08:28 (INFO): Estimation will be performed in 8 blocks of 10000x1251 pixels

Processing Image (1/1): 0% [ ]
Converting outputs
Loading resulting layers
Algorithm Compute Images second order statistics finished

B- Attributes of my classification Layer

C- Algorithm TrainImagesClassifier (rf)
C:\OTB\bin\otbcli_TrainImagesClassifier

-io.il

"D:\documents\GIS\Formation QGis\Donnees\Raster\Imagerie.tif "

-io.vd

"C:\Users\Yannick.Doungmo\Desktop\GDBQC\test\class_layer.shp "

-io.imstat

C:/Users/Yannick.Doungmo/Desktop/GDBQC/sec_stats.xml

-elev.default

0

-sample.mt

1000

-sample.mv

1000

-sample.bm

1

-sample.edg

true

-sample.vtr

0.5

-sample.vfn

Class

-classifier

rf

-classifier.rf.max

5

-classifier.rf.min

10

-classifier.rf.ra

0

-classifier.rf.cat

10

-classifier.rf.var

0

-classifier.rf.nbtrees

100

-classifier.rf.acc

0.01

-rand

0

-io.confmatout

"C:/Users/Yannick.Doungmo/Desktop/GDBQC/conf_mat.csv"

-io.out

"C:/Users/Yannick.Doungmo/Desktop/GDBQC/my_model.model"

ERROR: Parameter -sample.edg does not exist in the application.

Converting outputs

Loading resulting layers

Algorithm TrainImagesClassifier (rf) finished

I Tried the same algorithm with QGIS 3.4 but i still not have any result.
here is the log file :
Processing algorithm…
Algorithm 'TrainImagesClassifier' starting…
Input parameters:
{ 'io.il' : ['D:/documents/GIS/Formation QGis/Donnees/Raster/Imagerie.tif'], 'io.vd' : ['C:/Users/Yannick.Doungmo/Desktop/GDBQC/test/class_layer.shp'], 'io.valid' : '', 'io.imstat' : 'C:/Users/Yannick.Doungmo/Desktop/GDBQC/sec_stats.xml', 'io.out' : 'C:/Users/Yannick.Doungmo/Desktop/GDBQC/mod.model', 'io.confmatout' : 'C:/Users/Yannick.Doungmo/Desktop/GDBQC/mat.csv', 'cleanup' : True, 'sample.mt' : 1000, 'sample.mv' : 1000, 'sample.bm' : 1, 'sample.vtr' : 0.5, 'sample.vfn' : 'class', 'elev.dem' : '', 'elev.geoid' : '', 'elev.default' : 0, 'classifier' : 'libsvm', 'classifier.libsvm.k' : 'linear', 'classifier.libsvm.m' : 'csvc', 'classifier.libsvm.c' : 1, 'classifier.libsvm.nu' : 0.5, 'classifier.libsvm.opt' : False, 'classifier.libsvm.prob' : False, 'rand' : 0 }

The filename, directory name, or volume label syntax is incorrect.
Execution completed in 0.73 seconds
Results:
{'io.confmatout': 'C:/Users/Yannick.Doungmo/Desktop/GDBQC/mat.csv',
'io.out': 'C:/Users/Yannick.Doungmo/Desktop/GDBQC/mod.model'}

Loading resulting layers
Algorithm 'TrainImagesClassifier' finished
Processing algorithm…
Algorithm 'TrainImagesClassifier' starting…
Input parameters:
{ 'io.il' : ['D:/documents/GIS/Formation QGis/Donnees/Raster/Imagerie.tif'], 'io.vd' : ['C:/Users/Yannick.Doungmo/Desktop/GDBQC/test/class_layer.shp'], 'io.valid' : '', 'io.imstat' : 'C:/Users/Yannick.Doungmo/Desktop/GDBQC/sec_stats.xml', 'io.out' : 'C:/Users/Yannick.Doungmo/Desktop/GDBQC/mod.model', 'io.confmatout' : 'C:/Users/Yannick.Doungmo/Desktop/GDBQC/mat.csv', 'cleanup' : True, 'sample.mt' : 1000, 'sample.mv' : 1000, 'sample.bm' : 1, 'sample.vtr' : 0.5, 'sample.vfn' : 'class', 'elev.dem' : '', 'elev.geoid' : '', 'elev.default' : 0, 'classifier' : 'libsvm', 'classifier.libsvm.k' : 'linear', 'classifier.libsvm.m' : 'csvc', 'classifier.libsvm.c' : 1, 'classifier.libsvm.nu' : 0.5, 'classifier.libsvm.opt' : False, 'classifier.libsvm.prob' : False, 'rand' : 0 }

The filename, directory name, or volume label syntax is incorrect.
Execution completed in 0.11 seconds
Results:
{'io.confmatout': 'C:/Users/Yannick.Doungmo/Desktop/GDBQC/mat.csv',
'io.out': 'C:/Users/Yannick.Doungmo/Desktop/GDBQC/mod.model'}

Loading resulting layers
Algorithm 'TrainImagesClassifier' finished
Processing algorithm…
Algorithm 'TrainImagesClassifier' starting…
Input parameters:
{ 'io.il' : ['D:/documents/GIS/Formation QGis/Donnees/Raster/Imagerie.tif'], 'io.vd' : ['C:/Users/Yannick.Doungmo/Desktop/GDBQC/test/class_layer.shp'], 'io.valid' : '', 'io.imstat' : 'C:/Users/Yannick.Doungmo/Desktop/GDBQC/sec_stats.xml', 'io.out' : 'C:/Users/Yannick.Doungmo/Desktop/GDBQC/mod.model', 'io.confmatout' : 'C:/Users/Yannick.Doungmo/Desktop/GDBQC/mat.csv', 'cleanup' : True, 'sample.mt' : 1000, 'sample.mv' : 1000, 'sample.bm' : 1, 'sample.vtr' : 0.5, 'sample.vfn' : 'class', 'elev.dem' : '', 'elev.geoid' : '', 'elev.default' : 0, 'classifier' : 'libsvm', 'classifier.libsvm.k' : 'linear', 'classifier.libsvm.m' : 'csvc', 'classifier.libsvm.c' : 1, 'classifier.libsvm.nu' : 0.5, 'classifier.libsvm.opt' : False, 'classifier.libsvm.prob' : False, 'rand' : 0 }

The filename, directory name, or volume label syntax is incorrect.
Execution completed in 0.11 seconds
Results:
{'io.confmatout': 'C:/Users/Yannick.Doungmo/Desktop/GDBQC/mat.csv',
'io.out': 'C:/Users/Yannick.Doungmo/Desktop/GDBQC/mod.model'}

Loading resulting layers
Algorithm 'TrainImagesClassifier' finished
Processing algorithm…
Algorithm 'TrainImagesClassifier' starting…
Input parameters:
{ 'io.il' : ['D:/documents/GIS/Formation QGis/Donnees/Raster/Imagerie.tif'], 'io.vd' : ['C:/Users/Yannick.Doungmo/Desktop/GDBQC/test/class_layer.shp'], 'io.valid' : '', 'io.imstat' : 'C:/Users/Yannick.Doungmo/Desktop/GDBQC/sec_stats.xml', 'io.out' : 'C:/Users/Yannick.Doungmo/Desktop/GDBQC/mod.model', 'io.confmatout' : 'C:/Users/Yannick.Doungmo/Desktop/GDBQC/mat.csv', 'cleanup' : True, 'sample.mt' : 1000, 'sample.mv' : 1000, 'sample.bm' : 1, 'sample.vtr' : 0.5, 'sample.vfn' : 'class', 'elev.dem' : '', 'elev.geoid' : '', 'elev.default' : 0, 'classifier' : 'libsvm', 'classifier.libsvm.k' : 'linear', 'classifier.libsvm.m' : 'csvc', 'classifier.libsvm.c' : 1, 'classifier.libsvm.nu' : 0.5, 'classifier.libsvm.opt' : False, 'classifier.libsvm.prob' : False, 'rand' : 0 }

The filename, directory name, or volume label syntax is incorrect.
Execution completed in 0.11 seconds
Results:
{'io.confmatout': 'C:/Users/Yannick.Doungmo/Desktop/GDBQC/mat.csv',
'io.out': 'C:/Users/Yannick.Doungmo/Desktop/GDBQC/mod.model'}

Loading resulting layers
Algorithm 'TrainImagesClassifier' finished


text:
Q: utf8mb4 Encoding error with phpMyAdmin and remote MySQL database I am trying to use phpMyAdmin to access a remote MySQL database so I created a config.inc.php file (copying config.sample.inc.php) and added a server. Now this other server appear as an option in the login page but when connecting I receive this error: MySQL said #1115 - Unknown character set: 'utf8mb4'.
Is there a workaround?
Is there a configuration I can set?
Any help highly appreciated.

A: OPEN
C:\wamp\apps\phpmyadmin4.1.14\libraries\DatabaseInterface.class.php

search for 'utf8mb4' and replace it with 'utf8' in two consecutive lines like below
 $default_charset = 'utf8';
 $default_collation = 'utf8_general_ci';

A: Edit the following files:
<install path>/libraries/DatabaseInterface.class.php
<install path>/libraries/mysql_charsets.lib.php

And change all instances of 'utf8mb4' to 'utf8'.
It seems to have worked for me.

A: If you've already edited the lines in the files mentioned in RAHUL-BHOLA and Shane's answers:
<install path>/libraries/DatabaseInterface.class.php
<install path>/libraries/mysql_charsets.lib.php

And are still getting this error, and you're exporting a database from one phpMyAdmin installation to another phpMyAdmin installation, you can fix the error by deleting the following line in the .sql export file:
/*!40101 SET NAMES utf8mb4 */;

A: If you want to force export as well. You must edit file:
<install path>/libraries/plugins/export/ExportSql.class.php

and comment out following (from line 740) :
if ($set_names == 'utf8' && PMA_MYSQL_INT_VERSION > 50503) {
    $set_names = 'utf8mb4';
}

This will force export in SQL to be what you want to be. But you must first do changes in files (as was mentioned before)
<install path>/libraries/DatabaseInterface.class.php
<install path>/libraries/mysql_charsets.lib.php

New forced encoding in phpmyadmin is a pain in ass, because not all web hosting do recent updates. Such a stupid design!

A: There is an incompatibility with phpMyAdmin 4.1.x and MySQL <= 5.5
Install phpMyAdmin 4.0.x

A: I found that changing a portion of code located in files such as:

<install path>/libraries/DatabaseInterface.class.php
<install path>/libraries/plugins/export/ExportSql.class.php

from
PMA_MYSQL_INT_VERSION >  50503
to
PMA_MYSQL_INT_VERSION >  55503
does the trick

A: Use firefox, if You can live with that.
I got this error on only one database with Chrome. Firefox worked fine. Chrome even worked fine with a master/master replika of the faled database.
The edit in DatabaseInterface.class.php mentioned above solved the issue for Chrome.

A: I  have update the sql file that I exported by replacing  utf8mb4' to 'utf8'.

It worked for me. It happens due to improper mysql version.

A: Change at the time of export the old database:
Database system or older MySQL server to maximize output compatibility with ->mysql 4
thats it


text:
Q: Visual Studio 2015 dropdown to find procedure in a class Just installed Visual Studio 2015 and can't find nowhere how to show the dropdowns to quickly find a specific function or procedure inside a class.

A: If it's not found then set it following below steps

Click on Tools -> Options
Select Text Editor -> All Languages and check the Navigation Bar
check box


text:
Q: Stimulus JS error when toggling class from another element I'm building a transaction entry form to better understand Stimulus after the Odin Project lesson (https://www.theodinproject.com/lessons/ruby-on-rails-stimulus). 1. When the user is finished entering the amount, the next button is clicked and the numpad is hidden (including the 'next' button). 2. If the user would like to edit the amount, a click on the 'amount_box' toggles the hidden state of the numpad.
I've completed the first part, but getting an error on the second part.
JS (toggle_controller.js)
export default class extends Controller {
  static classes = [ "change" ]
  toggle() {
    this.element.classList.toggle(this.changeClass)
  }
}

HTML

$999,999.99

1

2

3

...

toggle#toggle">Next

This hides the id="numpad". But once hidden it can't be clicked to un-hide. In that case I would click the id="amount_box". So I moved the data-controller attribute to id='amount_container', which contains both the element being clicked and being toggled.
The updated HTML below throws an error "Error: Missing attribute "data-toggle-change-class" ... element: div#amount_container". It wants to see the data-toggle-change-class on the same element which has data-controller="toggle" but putting it on div#amount_container would just hide the whole thing which is my whole problem in the first place.

$999,999.99

1

2

3

...

toggle#toggle">Next

How can I click on "Next" or "div#amount_box, and hide/unhide div#numpad?

A: Currently, your toggle_controller.js toggles the classlist of this.element
export default class extends Controller {
  static classes = [ "change" ]
  toggle() {
    this.element.classList.toggle(this.changeClass)
  }
}

this.element refers to the element on which the data-controller attribute is placed. By moving the data-controller from div id="numpad" to
, this.element changes scope.
The solution is to define a stimulus target attribute to specify which element to toggle.
export default class extends Controller {
  static targets = [ "numpad" ]
  static classes = [ "change" ]

  toggle() {
    this.numpadTarget.classList.toggle(this.changeClass)
  }
}

$999,999.99

1

2

3

...

toggle#toggle">Next


text:
Q: Unsafe pointer in vertxattribpointer I've been working through some opengl in golang learning and have the following fragments:
import(
    "github.com/go-gl/gl/v3.3-core/gl"
)

vertices := []float32{
        // Position // Colors // Texture Coords
        1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, // Top Right
        1.0, -1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, // Bottom Right
        -1.0, -1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, // Bottom Left
        -1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, // Top Left
    }

vlen := int32(len(vertices) * 4 / 4)

var offset uint32 = 0

//position
gl.VertexAttribPointer(0, 3, gl.FLOAT, false, vlen, nil)
gl.EnableVertexAttribArray(0)

//color
offset = offset + 12
gl.VertexAttribPointer(1, 3, gl.FLOAT, false, vlen, unsafe.Pointer(&offset))
gl.EnableVertexAttribArray(1)

offset = 0

So I get my basic square I've been working on -- nil in the 5th position parameter for VertexAttribPointer for position seems to work, but I get nothing with color in the larger program. And if I try to specify an offset unsafe pointer of 0 for poistion I get nothing but empty space.
Specifying an unsafe pointer there is something I'm not understanding at the moment -- I think I need to specify where in vertices the offset for color is, but I'm not following. I am not sure vlen is correct either. Any input appreciated.
EDIT:
Self found solution -- what I needed was gl.PtrOffset, which I wasnt aware of when initially creating the quetion.
gl.VertexAttribPointer(1, 3, gl.FLOAT, false, vlen, gl.PtrOffset(offset))

A: Your problem comes from VertexAttribPointer(att, size, type, normalized, stride, pointer)
size is the number of components per generic vertex attribute. Position and color have 3 components, texture coords only 2.
stride is number of bytes offset between two consecutive values for the attribute you want to read in the shader.
Your buffer is PPPCCCTT, PPPCCCTT, etc (i.e. position, color, texture coords, position, color, texture coords, etc). Let's put it in bytes (a "float" is 4-bytes sized):
444 444 44,  444 444 44, etc
I detail size and stride:
Position: 3 floats, (3x4 +2x4)=20 bytes, 3 floats, 20 bytes, etc
Color: 3 floats, (2x4 + 3x4)=20 bytes, 3 floats, 20 bytes, etc
TextCoo: 2 floats, (3x4 + 3x4)=24 bytes, 2 floats, 24 bytes, etc
Position attribute: VertexAttribPointer(att1, 3, gl.FLOAT, false, 20, nil)
Color attribute:  VertexAttribPointer(att2, 3, gl.FLOAT, false, 20, nil)
Texture coords attribute: VertexAttribPointer(att3, 2, gl.FLOAT, false, 24, nil)
att is the location of the attribute in your shader.