text:
Q: Is it possible to rename an open Word document without closing it? I just ask this question as I do not believe that after so many versions of Word, it wouldn't exist.
Usually when I'm working on a document and I realize I have to rename it, I have to close the document down, go to file explorer and then rename it, and then opening it up again.
It's a procedure that's so ingrained in my usage pattern that I didn't realize until now that  I'm actually having to open and close multiple windows/ applications etc. simply to rename a file. Surely, it's the year 2012, I should be able to do a simple thing like that with a few clicks right?
So is there a way to just rename the file name of a word /excel / office document without having to close it first?

A: Word opens documents in exclusive mode AFAIK, so this locks the files and prevents access by other programs until the lock is released by closing the files or Word itself. I don't think providing shared access to documents is a workable solution, otherwise it would surely have been implemented long back if it made sense.

A: Yes, it's possible!
At least on a Mac (OS X 10.8.5). Just Cmd + click on the file name on top of your opened Office document, that you want to rename. You then see the path where the file is located. Next you click on the name of the folder directly under the file name. The name then appears in a Finder screen, where you can adjust its name to whatever you want.
So no need to first close the file, nor to use 'save as' and removing the first file from the finder! (I don't know if the same or similar trick works out in Windows.)

A: Prompted by the suggestions of  @Adam and @Lưu Vĩnh Phúc, I created the following macro that does what you requested. Note that this will delete any history associated with the file.
      Sub RenameActiveFile()
    '
    ' Renames the current file without closing the document (assuming file has already been saved)
    '  (Actually, saves with new name and deletes previous, so history will be lost).
    '
    Dim strFileFullName, strFileName, strNewName As String
    Dim res As VbMsgBoxResult

    ' Get current name:
    strFileFullName = ActiveDocument.FullName               'for Word docs
    'strFileFullName = ActiveWorkbook.FullName               'for Excel docs
    'strFileFullName = Application.ActivePresentation.FullName       'for Powerpoint presentations*
    If (InStr(strFileFullName, ".") = 0) Then
        res = MsgBox("File has not been saved. Can't rename it.", , "Rename File")
        Exit Sub
    End If
    strFileName = Right(strFileFullName, Len(strFileFullName) - InStrRev(strFileFullName, "\")) 'strip path
    strFileName = Left(strFileName, (InStr(strFileName, ".") - 1))  ' strip extension

    ' Prompt for new name:
    strNewName = InputBox("Rename this file to:", "Rename File", strFileName)
    If (strNewName = "") Or (strNewName = strFileName) Then ' (Check whether user cancelled)
        Exit Sub
    End If

    ' Save file with new name:
    ActiveDocument.SaveAs2 FileName:=strNewName             'for Word docs
    'ActiveWorkbook.SaveAs2 FileName:=strNewName            'for Excel docs
    'Application.ActivePresentation.SaveAs FileName:=strNewName      'for Powerpoint presentations*

    ' Delete old file:
    With New FileSystemObject   ' (this line requires: Tools->References->Microsoft scripting runtime)
        If .FileExists(strFileFullName) Then
            .DeleteFile strFileFullName
        End If
    End With
End Sub

*Note: although this macro works with Powerpoint (with modifications noted above), PowerPoint can't save it globally.

A: To answer the need of Rich Lysakowski (and mine too), here is a different approach which preserves history! (it actually closes and reopens the file)
Sub RenameActiveFile()
    Dim strFileFullName, strFilePath, strFileName, strFileExt, strNewName, strNewFullName As String
    Dim result As VbMsgBoxResult

   'check if it is a new file which has never been saved
   If ActiveDocument.Path = "" Then
      On Error Resume Next    'to avoid VBA error if cancel is pressed
      ActiveDocument.Save
      Exit Sub
   End If

   ' Get current name:
   strFileFullName = ActiveDocument.FullName               'for Word docs
   strFilePath = ActiveDocument.Path 'Left(strFileFullName, InStrRev(strFileFullName, "\"))
   strFileName = Left(ActiveDocument.Name, (InStrRev(ActiveDocument.Name, ".") - 1))  ' strip extension
   strFileExt = Mid(ActiveDocument.Name, (InStrRev(ActiveDocument.Name, ".") + 1)) 'get extension

   If Not (ActiveDocument.Saved) Then
      result = MsgBox("""" & strFileName & """ needs to be saved before renaming." & vbCrLf & "Save """ & strFileName & """ ?" & strNewName, _
                     vbQuestion + vbYesNo, "Document not saved")
      If result = vbNo Then Exit Sub
      ActiveDocument.Save
   End If

   ' Prompt for new name:
   strNewName = InputBox("Rename """ & strFileName & """ to:" & vbCrLf & "(do not type extension: ""." & strFileExt & """ will be added)", _
               "Rename File", strFileName)

   'Check whether user cancelled
   If (strNewName = "") Or (strNewName = strFileName) Then
      Exit Sub
   Else
      strNewFullName = strFilePath & "\" & strNewName & "." & strFileExt
   End If

   'check if new name exist (not working with online files)
   If Dir(strNewFullName) > "" Then
      result = MsgBox("A file """ & strNewName & """ already exist in the same folder!", vbExclamation, "Renaming failed")
      Exit Sub
   End If

   'close, rename and reopen file
   ActiveDocument.Close
   Name strFileFullName As strNewFullName
   Documents.Open FileName:=strNewFullName
End Sub

A: Microsoft has included ground breaking new features in the latest Word designed to accommodate those with your exact concerns -
Click file and then 'Save As'


text:
Q: How to apply slicing window to transform pandas to 2D array? I have the following DataFrame:
y =
    1
    3
    1
    4
    2
    5
    1

I need to apply a slicing window and transform this DataFrame into a numpy array as follows:
array([
        [ 1, 3, 1, 4 ],
        [ 3, 1, 4, 2 ],
        [ 1, 4, 2, 5 ],
        [ 4, 2, 5, 1 ]
     ]

Each row contains the 4 sequential values from y. The last 3 rows are not included because they would include NaNs.
How can I do it?

A: Check out np.as_strided()
import numpy as np
import pandas as pd

y = pd.Series([1,3,1,4,2,5,1])
y_arr = y.to_numpy()
z_arr = np.lib.stride_tricks.as_strided(
  x = y_arr,
  shape = (4,4),
  strides = (y_arr.strides[0], y_arr.strides[0])
)

print(z_arr)
[[1 3 1 4]
 [3 1 4 2]
 [1 4 2 5]
 [4 2 5 1]]

BEWARE - some of the elements in z_arr are actually referencing the same memory block (so you probably want to use z_arr.copy())
Here's a neat example explaining how this works

A: Another option would be to use simple list comprehension with casting to NumPy ndarray:
if y is a DataFrame:
np.array([y[k:k+4] for k in range(4)])[:,:,0]

if y is a Series:
np.array([y[k:k+4] for k in range(4)])

redpajama_set_name: RedPajamaStackExchange


text:
Q: Reference request: Optimal $L^p$-decay for nonhomogenous heat equation in $\mathbb R^d$ Let $u$ be a classical solution for the nonhomogeneous heat equation in $\mathbb R_+ \times\mathbb R^d$:
$$
\begin{cases}
\partial_tu(t,x)-\Delta u(t,x) = f(t,x), \\
u(0,x)=u_0(x).
\end{cases}
$$
Suppose $f(t,\cdot) \in L^q(\mathbb R^n), 1 \le q \le \infty$, for each $t > 0$, and suppose $f$ has the decay behavior
$$
\|f(t, \cdot)\|_{L^q} \le \frac{C}{1+t^\gamma}, \quad \gamma >0.
$$
Now my question is that, given $\gamma$ and $q$, what is the decay rate of $\|u(t, \cdot)\|_{L^p(\mathbb R^d)}$ for each $1\le p \le \infty$? Probably there is no decay for all values of $p$ in this range, but I am interested in the optimal results. In particular, I would be interested in a reference (book or research paper), where this has been studied in detail.
I tried to derive the results from the representation formula for $u$:
$$
u(t,x)=\int_{\mathbb R^d} H(t, x-y)u_0(y)\, dy + \int_0^t\int_{\mathbb R^d} H(t-s, x-y)f(s,y) \, dy \, ds,
$$
where
$
H(t,x)=(4\pi t)^{-d/2}e^{-\frac{|x|^2}{4t}}
$
is the heat kernel. Here the problem comes with the latter term for large dimensions $d$. Simple arguments by using Minkowski's (or Hölder's) inequalities give some decay estimates, but then one ends up with some strange looking integrability conditions in the time integral. In particular, in this manner one only obtains decay for some values of $p$ and I doubt the estimates obtained are optimal in this sense. So I am wondering what is the correct approach and what would be the reference for this.

A: Suppose that $u_0=0$, otherwise $L^p$ decay estimates are well-known. Let $\{T(t)\}_{t\geq0}$ denote the heat semigroup, i.e., $T(t)$ for $t>0$ is convolution with $(4\pi t)^{-d/2}\,e^{-|x|^2/(4t)}$. Notice that, for $p\geq q$,
$$
  \|T(t)\|_{L^q\to L^p} = \left\|\frac1{(4\pi
    t)^{d/2}}\,e^{-\,\frac{|x|^2}{4t}}\right\|_{L^r} =
  C_{d,r}\,t^{-\,\frac{d}2\left(1-\frac1r\right)},
$$
where $1+\frac1p=\frac1q+\frac1r$ (here, $p,\,q,\,r\in[1,\infty]$).

Let $p\geq q$ and $\displaystyle \frac1q-\frac1p<\frac2d$. Further let $\displaystyle \|f(t)\|_{L^q} \lesssim (1+t)^{-\gamma}$ for some $\gamma\in \mathbb R$. Then $\displaystyle \|u(t)\|_{L^p} \lesssim \alpha_\gamma(t)(1+t)^{-\,\frac{d}2\left(\frac1q-\frac1p\right)}$, where
  $$
   \alpha_\gamma(t) = \begin{cases}
   (1+t)^{1-\gamma}, & \gamma<1, \\
   \log \left(e+t\right), &  \gamma=1, \\
   1, & \gamma>1.
   \end{cases}
$$

Indeed, $u(t)=\int_0^t T(t-s)f(s)\,ds$, so
$$
\begin{aligned}
   \|u(t)\|_{L^p} &\leq \int_0^t \|T(t-s)\|_{L^q\to L^p}
   \|f(s)\|_{L^q}\,ds \lesssim \int_0^t
   \frac{(t-s)^{-\,\frac{d}2\left(1-\frac1r\right)}}{(1+s)^\gamma}\,ds \\
   & \lesssim
   t^{1-\,\frac{d}2\left(1-\frac1r\right)}\sideset{_{2\,}}{_1}F\left(1,\gamma;2-\,
  \frac{d}2\left(1-\frac1r\right);-t\right).
\end{aligned}
$$
To find the asymptotics of $\displaystyle \sideset{_{2\,}}{_1}F\left(\dots;-t\right)$ as $t\to\infty$, use
$$
\begin{aligned}
  \sideset{_{2\,}}{_1}F\left(a,b;c;-t\right) & =
  \frac{\Gamma(b-a)\Gamma(c)}{\Gamma(c-a)\Gamma(b)}
  \,t^{-a}\sideset{_{2\,}}{_1}F\left(a,a-c+1;a-b+1;-\,\frac1t\right) \\ &\qquad
  +\,\frac{\Gamma(a-b)\Gamma(c)}{\Gamma(c-b)\Gamma(a)}\,t^{-b}\,
  \sideset{_{2\,}}{_1}F\left(b-c+1,b;-a+b+1;-\,\frac1t\right)
\end{aligned}
$$
in case $a-b\notin\mathbb Z$; and similarly for $a-b\in\mathbb Z$.

The estimates above are best possible (as $t\to\infty$) provided that $q=1$ or $\gamma\neq1$.

In case $\gamma<1$ or $(q,\gamma)=(1,1)$, this is shown by the example of
$$
  u(t,x) = \frac1{(4\pi t)^{d/2}}\,e^{-\,\frac{|x|^2}{4t}}\,h(t), \quad
  f(t,x) = \frac1{(4\pi t)^{d/2}}\,e^{-\,\frac{|x|^2}{4t}}\,h'(t),
$$
where $h\in\mathscr C^\infty(\overline{\mathbb R}_+)$, $h(t)=0$ near $t=0$, upon choosing $h$ appropriately. For instance, $\displaystyle h'(t)=t^{-\delta}$ for $t\geq1$ (and $h'(t)=0$ for $0\leq t\leq1/2$) with $\displaystyle \delta=\gamma-\frac{d}2\left(1-\frac1q\right)$ will do.
For $\gamma>1$, it is enough to remark that $\alpha_\gamma(t)\gtrsim 1$, with this lower bound being implied by the Cauchy problem (e.g., take $f$ such that $f=0$ for $t>1$).


text:
Q: Confidence interval for sum of random variables Suppose I have realizations $x_1, ..., x_n$ for random variable $X$ and I have realizations $y_1, ... , y_m$ for random variable $Y$. $n<<m$ are small numbers.
Let $ Z = a*X + b*Y $, where $a,b$ constants.  How can I derive a confidence interval for the mean $\mu_Z$?
Can I simply use bootstrapping? That is, suppose $F_n$ and $H_m$ are the empirical distribution functions obtained from the two sets of realizations. I could, for example, generate many bootstrap samples $z_i^* = x_i^* + y_i^*$, $i = 1, ...$ , compute the empirical distribution of (studentized) means and then the confidence interval.
Is this a reasonable procedure or am I making a conceptual mistake somewhere? By the way, this question is motivated by a real application. For that I am actually interested in a sum of random variables with many terms, all of which have a different number of observations.


text:
Q: Issues with youtube video on mobile browser I have an embed tag containing youtube video.
However this does not play on mobile browsers as it says flash required.
I am using HTML and not HTML 5 since my app should support IE 8 too.
I browsed through some awesome JQuery solutions but got only HTML5 based Jquery solutions
Can someone suggest me good solution to have my youtube video play in IE8+ , Chrome , FF+ and mobile browsers too.

A: This embed code youtube provides by default will work for HTML5 browsers (mobile phones) as well as old browsers that need flash:
http://jsfiddle.net/austinpray/G5GhH/1
<iframe width="560" height="315" src="http://www.youtube.com/embed/VIDEO_ID" frameborder="0" allowfullscreen></iframe>

As best I can tell by looking at the iframe's code, this code sniffs the capabilities of what your browser can play and displays what works best. If you are on browser that has flash capabilities it uses flash and if flash isn't available it defaults to HTML 5. I tested this and it works on iPhones and Android phones. Here is the Youtube support document.


text:
Q: ActiveRecord scope based on hour iteration
<% @challenges.with_exact.each do |challenge| %>
 etc...
<% end %>

model scope attempts
scope :with_exact, -> { where("exact == ?", Time.zone.now.hour) } # Error: PG::UndefinedFunction: ERROR:  operator does not exist: time without time zone == integer
scope :with_exact, -> { where(exact: Time.zone.now.hour) } # Error: PG::InvalidDatetimeFormat: ERROR:  invalid input syntax for type time: "13"

Some challenges will have a nil exact.
How can I iterate challenges only where Time.zone.now.strftime('%H') == challenge.exact.strftime('%H')

A: You can use date_part(text, timestamp) postgres function:
where("date_part('hour', exact) = ?", Time.zone.now.hour)

Here is also month, year and so on.
There is an another way with extract(field from timestamp)
where("extract(hour from exact) = ?", Time.zone.now.hour)


text:
Q: XAMPP, Node.js and port forwarding I am making a multi-platform game which sends and receives data to my XAMPP server regarding player profile updates. And its a multi-player game so players are connected via Node.js and SocketIO. Can I make my XAMPP files and Node.js server accessible online via port forwarding? Will I need two different ports for XAMPP and Node.js? Is port forwarding a good idea or should I go with a professional shared hosting provider?

A: i hope with "port forwarding" you mean on your home router, this is crazy, it depends on some variables, how many users can you support?,it's your connection good in upload and download? have you server at home? if the connection go down have you a backup?, have you the backup of data? etc etc, maybe the shared hosting it's better


text:
Q: c programming segfault unitialised int? I have this c program that looks like.
int indexLength;
char *args[1024];
while(args[indexLength])
     indexLength++;

If i run the program under computer at work, the while loop line gives me a segfault..and the indexLength take some ridiculous arbitrary value.
But if i run the program on a linux machine at home, there are no segfault and my program run normally.
The only difference i can think of between the 2 machine is that the one at work has gcc4.7 redhat version, and is running Fedora OS, and my machine at home has gcc4.7 downloaded from ppa repository, and is running ubuntu OS.
But, i'm not convinced that's the only difference! What can it be?
EDIT: sorry i forgot to mention. The segfault went away on the computer at work if i initialise indexLength = 0..

A: Reading from uninitialized memory is undefined behavior. Variables are not initialized by default, so indexLength can take any value until you assign it. Since the behavior is undefined, the program could run on some machines, and crash on others.
Moreover, even initializing the indexLength to zero does not fix undefined behavior, because args remains uninitialized. This means that the program may not stop upon reaching the end of the array, and access values past the end of the allocated region. Of course in order to do that all values in the array of 1024 items must be non-zero, so the odds are in favor of stopping before reaching the end of the array. However, in order to fix this undefined behavior you need to check the index before accessing values.

A: Your code invokes undefined behaviour

*

*args is uninitialised so each element contains unpredictable values.  Maybe you'll find a NULL pointer in the next 4k of stack and exit the loop; maybe you won't and you'll read beyond the end of the array

*indexLength is uninitialised so you may read way beyond the end of your array immediately

*the effect of reading beyond the end of args is also unpredictable.  This includes potentially crashing, say if you don't find a zero word before you reach the limits of readable memory for your process

Despite initial appearances, setting indexLength=0 didn't actually make your code safe.  You're still reading uninitialised memory so are relying on finding a NULL element inside args.  There is no way to guarantee that you'll find this.  If your loop doesn't exit before you reach the end of your array, you're back into undefined behaviour so your program may crash on any further iteration.


text:
Q: get value of textfield in a table using angularjs Below is my angularjs form

                    Item
                    Rate

                        <select name="item"  ng-model="item" >
                            <option value="">Choose..</option>
                            <option value="T-SHIRT">T-SHIRT</option>
                            <option value="JACKET">JACKET</option>

                        </select>

                    <input type="text" name="rate"  ng-model='rate'>

                        <select name="item1"  ng-model="item1" >
                            <option value="">Choose..</option>
                            <option value="T-SHIRT">T-SHIRT</option>
                            <option value="JACKET">JACKET</option>

                        </select>

                    <input type="text" name="rate1"  ng-model='rate1'>

        <button type="button"  ng-click='saveorder()' >SAVE ORDER</button>

Here in this above for loop the second commended line is working and it returns value of item, But I want to get all items value in table. When I use item+i in loop it returns a null value means its not working like $scope.item1,$scope.item2 etc.
I am new to angularJs any help? thanks in advance

A: Try by changing your column and type name to use like order_no[0], order_no1, etc.. and type[0], type1, etc.. and check with code below :
var rowCount = $('#item_table tr').length;
for (i = 0; i < rowCount; i++) {
    order_no[i] =  $scope.order_no[i];
    type[i] =  $scope.type[i];
}

You can check fiddle https://jsfiddle.net/qh73ogzw/30 to check changed example as per your code


text:
Q: MySQL more columns then in php query I changed to another database with more columns. Nut now my register page doesn't work anymore. The tables all have default settings.
How can I let the query put all the data in the columns and use the defaults for other columns?
This is my query:
    mysql_query("

    INSERT INTO `users`
    (`username`, `password`, `mail`, 'account_created', 'ip_last', 'ip_reg')
     VALUES(
            '".$naam."', '".$wachtwoord."', '".$email."',
            '".$timestamp."', '".$ip."', '".$ip."'
           )
     ");

It worked before, but now on this new database it doesn't work anymore. I didn't change my php version or something.

A: You can use variables in query strings without quotes.
By the way you should think about more secure -
PDO? What is this magic system
PDO Version:
$query = $db->prepare("INSERT INTO users(username, password, mail, account_created, ip_last, ip_reg) VALUES (?, ?, ?, ?, ?, ?)");
$query->execute(array($naam, $wachtwoord, $email, $timestamp, $ip, $ip));

Trash Version:
mysql_query("INSERT INTO users(username, password, mail, account_created, ip_last, ip_reg) VALUES ($naam, $wachtwoord, $email, $timestamp, $ip, $ip)");

A: Know the difference between back ticks and single quotes
 mysql_query("
INSERT INTO `users` (`username`, `password`, `mail`, `account_created`, `ip_last`, `ip_reg`) VALUES('".$naam."', '".$wachtwoord."', '".$email."', '".$timestamp."', '".$ip."', '".$ip."')");


text:
Q: How to subtract time from current time in Laravel? $clock_in = Carbon::createFromFormat('g:i A', Input::get('clock_in'))->timezone('UTC');
$clock_out = Carbon::createFromFormat('g:i A', Input::get('clock_out'))->timezone('UTC');

$attendance->clock_in = $clock_in->format('H:i:s');
$attendance->clock_out = $clock_out->format('H:i:s');

In this code I have clockIn and clockOut which get current time. Now, I want to subtract 5 hour :30 min from both i.e. clockIn and clockout. So, How can I do this? Please help me.
Thank You

A: 5 hr 30 min is equals to 5*3600+30*60 seconds,
So you can use subSeconds look like this:
$sec = 5*3600+30*60;
$attendance->clock_in = $clock_in->subSeconds($sec)->format('H:i:s');
$attendance->clock_out = $clock_out->subSeconds($sec)->format('H:i:s');

Or you can use subMinutes:
$min = 5*60+30;
$attendance->clock_in = $clock_in->subMinutes($min)->format('H:i:s');
$attendance->clock_out = $clock_out->subMinutes($min)->format('H:i:s');


text:
Q: ARM disassembler output: When there are two arguments instead of three I am trying to annotate a disassembly block for exam practice. Here's what I have done so far:
00000190 <mystery>:
190:   2300      movs    r3, #0            // move address 190 (offset 0) into r3 ?
192:   e004      b.n     19e <mystery+0xe> // if 19e then branch to mystery
194:   f010 0f01 tst.w   r0, #1  ; 0x1     // update flags to 1 in status register
198:   bf18      it      ne                // if 198 not equal to ??? then ???
19a:   3301      addne   r3, #1            // add to r3 if not equal to 19a offset 1?
19c:   1040      asrs    r0, r0, #1        // shift r0 right one spot (leave it in r0)
19e:   2800      cmp     r0, #0            // compare contents of r0 against 0 ?
1a0:   d1f8      bne.n   194 <mystery+0x4> // branch to 194 if not equal to something at line 194?
1a2:   4618      mov     r0, r3            // move r3 wholecloth into r0
1a4:   4770      bx      lr                // branch(return from the mystery function)
1a6:   bf00      nop                       // No operation

So my comments are pretty rudimentary and likely to be massively incorrect but most of all I really don't understand what instructions such as those at 190 or 19a mean. There are only two arguments instead of three, so how do these work?
Taking as an example
19a:   3301      addne   r3, #1

My interpretation of this so far is: if not equal to X, then add Y to r3? What are X and Y? Should I be using the result from the previous line? If so, which argument (of the standard three) does it take the place of?
Blah!
I am willing to accept that I have no idea what I am doing and am completely misinterpreting everything.
Please send help!

A: 190:   2300      movs    r3, #0    // assign the value 0 to R3, affecting
                                   // the status flags (the S suffix)

19a:   3301      addne   r3, #1    // add 1 to r3 IF the previous comparison was
                                   // Not Equal to 0

The ne suffix checks the status flags which were earlier set by the movs instruction.

A: 1) TST instruction is basically the same as ANDS, except it doesn't change the first operand. So, TST r0, #1 sets flags based on the result of (r0 & 1). Specifically, it will set the Z (zero) flag if the result was zero, i.e. bit 0 of r0 was not set.
2) IT stands for "If-Then". It checks the condition indicated, and conditionally executes up to 4 following instructions. In your example you have only one conditional instruction, which the disassembler helpfully provided with the NE suffix from the IT instruction (the suffix is not encoded in the instruction itself for Thumb-2). NE means "not equal", but in this case there was no comparison, so what gives? The trick is that the equality check checks the Z flag, so you can think of this one as "not Zero". So, our ADD will be executed in case the Z flag was not set, i.e. r0 did have bit 0 set.
3) A similar situation happens around CMP/BNE. CMP basically subtracts operands and sets the flags based on the result. In our case, it will set Z if r0 was equal to 0. Next, BNE will test the Z flag and branch if it was not set (i.e. r0 was not equal to 0).
Converting it all to pseudo-C, we get:
r3 = 0
goto test_loop;
loop:
  Z = (r0 & 1) == 0;
  if (!Z)
    r3 += 1;
  r0 = r0 >> 1
test_loop:
  Z = (r0 - 0) == 0;
  if (!Z) goto loop;
  r0 = r3;
  return;

Or, in "normal" C:
r3 = 0;
while ( r0 != 0 )
{
  if ( r0 & 1 )
    r3++;
  r0 >>= 1;
}
return r3;

Looks like it's counting bits in r0.
Have a look here for the table of condition codes and what flags they check. This describes how and when the flags are set.

Edit: I just reread your question and realized one source of your confusion. In line like this:
b.n     19e <mystery+0xe>

there is one operand, not two. The disassembler tries to be helpful and shows not just the absolute destination address (19e) but also its representation as an offset from the nearest symbol (mystery is at 190, so 19e is mystery+0xe).
Another thing you need to realize is that in ARM (and many other processors), setting flags and using flags is usually done in separate instructions. That's why you first do TST or CMP (or other flag-setting instruction), and then use conditional instructions, IT, or conditional branches.

A: If you look at the ARM ARM (ARM Architectural Reference Manual) it has a section closer to the front about the flags.  Unlike many other instruction sets, if you look at the ARM instructions, the ARM flavor in particular (not thumb) the top four bits of every instruction are conditional bits.  Unlike most other processors, with the arm you can conditionally execute any instruction, most others only allow for conditional branches.   The condition codes, ne, nz, cs, nc, etc are listed in that early section on the condition codes.  So an add if the zero flag is clear would be addne.  Also unlike most other processors ARM (in arm mode) allows for you to choose when you want to destroy/write the flags.  Most others would always update the flags on an add for example, arm only does if you add the s, add does not adds does.  It gets tricky when you combine the conditional execution and these other modifiers to the instruction, for example is it addsne or addnes?  that takes trial and error to figure out.  I would guess addnes, but I use combinations like that so rarely that I dont have it memorized.
As already mentioned the disassembler creates something that is not assembleable, there are additional items on the output to help you decode the instruction.
It looks like you are looking at thumb2 code, which is a frankenstein mixture of ARM and thumb.  So you are going to have some arm features and some thumb features and at least with binutils some annoying binutils-isms (dont have an arm toolchain anymore to compare).  For example even though we know that many thumb instructions modify the flags without it being an option, and the disassembler shows this by giving adds instead of add, you cannot use adds r1,r2 for thumb mode as it complains, it wants you to use add r1,r2 even though you are modifying the flag.  ARM is working to push a unified arm/thumb assembly syntax, which probably already works with their toolchain but will have to see what happens with the gnu tools.
So I wouldnt expect to be able to take the disassembly output and re-assemble that syntax for those two reasons.  The extra stuff is there to help you understand the specific instruction that was encoded.


text:
Q: Elasticsearch schema for multiple versions of the same text I'm working on a system that downloads articles from various news sites and performs various NLP analyses on the texts. I want to store multiple versions and aspects of each article, including

*

*The raw HTML

*A cleaned-up text-only version

*CoreNLP output of the article.
Since I want to store the text-only version on Elasticsearch, I thought about storing everything else on Elasticsearch, as well. I have no Elasticsearch experience, so I can't tell what's a better way to store these:

*

*Have one record per article, with the HTML, text and CoreNLP outputs as properties of that article : {html: '....', text: '....', CoreNLP: '....'}

*Store each type of information in its own type: /articles/html/1, /articles/text/1, /articles/corenlp/1, etc...

Which one is more common? Is there a third, better option?

A: Depends on where you want to do the COreNLP, the html tidy up, etc. If you want to do this in elastic I would use the multi field types:
https://www.elastic.co/guide/en/elasticsearch/reference/0.90/mapping-multi-field-type.html
If you do it outside of elastic, which would not be common since this is a good task for elastic, you could use the multiple fields approach.


text:
Q: Adding JSON Array to already existing JSON file I have already existing JSON file similiar to this:
[{
    "x": []
}]

and I want to put prepared JSON Array as a value for "x" key.
How to do it using JSON Simple library?

A: Quick solution:
    JSONObject jsonObject = (JSONObject) jsonArray.get(0);
    jsonObject.put("x", jsonArrayWithValueForXKey);
    jsonArray.clear();
    jsonArray.add(jsonObject);


text:
Q: What's the process of disabling interrupt in multi-processor system? I have a textbook statement says disabling interrupt is not recommended in multi-processor system, and it will take too much time. But I don't understand this, can anyone show me the process of multi-processor system disabling the interrupts? Thanks

A: on x86 (and other architectures, AFAIK), enabling/disabling interrupts is on a per-core basis.  You can't globally disable interrupts on all cores.
Software can communicate between cores with inter-processor interrupts (IPIs) or atomic shared variables, but even so it would be massively expensive to arrange for all cores to sit in a spin-loop waiting for a notification from this core that they can re-enable interrupts.  (Interrupts are disabled on other cores, so you can't send them an IPI to let them know when you're done your block of atomic operations.)  You have to interrupt whatever all 7 other cores (e.g. on an 8-way SMP system) are doing, with many cycles of round-trip communication overhead.
It's basically ridiculous.  It would be clearer to just say you can't globally disable interrupts across all cores, and that it wouldn't help anyway for anything other than interrupt handlers.  It's theoretically possible, but it's not just "slow", it's impractical.

Disabling interrupts on one core doesn't make something atomic if other threads are running on other cores.  Disabling interrupts works on uniprocessor machines because it makes a context-switch impossible.  (Or it makes it impossible for the same interrupt handler to interrupt itself.)

But I think my confusion is that for me the difference between 1 core and 8 core is not a big number for me; why disabling all of them from interrupt is time consuming.

Anything other than uniprocessor is a fundamental qualitative difference, not quantitative.  Even a dual-core system, like early multi-socket x86 and the first dual-core-in-one-socket x86 systems, completely changes your approach to atomicity.  You need to actually take a lock or something instead of just disabling interrupts.  (Early Linux, for example, had a "big kernel lock" that a lot of things depended on, before it had fine-grained locking for separate things that didn't conflict with each other.)
The fundamental difference is that on a UP system, only interrupts on the current CPU can cause things to happen asynchronously to what the current code is doing.  (Or DMA from devices...)
On an SMP system, other cores can be doing their own thing simultaneously.

For multithreading, getting atomicity for a block of instructions by disabling interrupts on the current CPU is completely ineffective; threads could be running on other CPUs.
For atomicity of something in an interrupt handler, if this IRQ is set up to only ever interrupt this core, disabling interrupts on this core will work.  Because there's no threat of interference from other cores.


text:
Q: Concurrency multithreading with requests I am trying to figure out how to create concurrent requests with multithreading whilst using the requests library. I want to grab the links, and total pages from a url's POST request.
However, I am iterating over a very large loop so it will take an awfully long time. What I have tried doesn't seem to make the requests concurrent nor does it produce an output.
Here's what I have tried:
#smaller subset of my data

df = {'links': ['https://www.theparking.eu/used-cars/#!/used-cars/%3Fid_pays%3D6%26id_marque%3D138%26id_modele%3D687',
'https://www.theparking.eu/used-cars/#!/used-cars/%3Fid_pays%3D6%26id_marque%3D138%26id_modele%3D492',
'https://www.theparking.eu/used-cars/#!/used-cars/%3Fid_pays%3D6%26id_marque%3D138%26id_modele%3D499',
'https://www.theparking.eu/used-cars/#!/used-cars/%3Fid_pays%3D6%26id_marque%3D138%26id_modele%3D702',
'https://www.theparking.eu/used-cars/#!/used-cars/%3Fid_pays%3D6%26id_marque%3D138%26id_modele%3D6143'],
 'make': [138.0,138.0,138.0,138.0,138.0],
 'model': [687.0,492.0,499.0,702.0,6143.0],
 'country_id': [6.0,6.0,6.0,6.0,6.0]}

import requests
from bs4 import BeautifulSoup
from multiprocessing.pool import ThreadPool
import threading
import gc

def get_links(url):
    headers = {
        'authority': 'www.theparking.eu',
        'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"',
        'accept': '*/*',
        'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'x-requested-with': 'XMLHttpRequest',
        'sec-ch-ua-mobile': '?0',
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36',
        'sec-ch-ua-platform': '"macOS"',
        'origin': 'https://www.theparking.eu',
        'sec-fetch-site': 'same-origin',
        'sec-fetch-mode': 'cors',
        'sec-fetch-dest': 'empty',
        'referer': 'https://www.theparking.eu/used-cars/used-cars/',
        'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',
    }
    formal_data = defaultdict(list)
    for id_ in df['country_id']:
        for make in df['make']:
            for model in df['model']:
                data = {
                    'ajax': '{"tab_id":"t0","cur_page":1,"cur_trie":"distance","query":"","critere":{"id_pays":[%s],"id_marque":[%s], "id_modele":[%s]},"sliders":{"prix":{"id":"#range_prix","face":"prix","max_counter":983615,"min":"1","max":"400000"},"km":{"id":"#range_km","face":"km","max_counter":1071165,"min":"1","max":"500000"},"millesime":{"id":"#range_millesime","face":"millesime","max_counter":1163610,"min":"1900","max":"2022"}},"req_num":1,"nb_results":"11795660","current_location_distance":-1,"logged_in":false}' % (round(id_), round(make), round(model)),
                    'tabs': '["t0"]'
                            }
                response = requests.post(url, headers=headers, data=data)
                test = json.loads(response.text)
                pages = round(int(test['context']['nb_results'])/27)
                if pages != 0:
                    formal_data['total_pages'].append(pages)
                    formal_data['links'].append(url)
                    print(f'You are on this link:{url}')
    return formal_data
threadLocal = threading.local()

with ThreadPool(8) as pool:
    urls = df['links']
    pool.map(get_links, urls)
    # must be done before terminate is explicitly or implicitly called on the pool:
    del threadLocal
    gc.collect()

A: Note that a more modern approach to use requests asynchronously is to use other libraries, like requests-threads.
With your approach, you connect to various URL in parallel, but sequentially to each URL. Consequentially, you might no be taking full advantage of multithreading. Indeed, for a single URL in df['links'], you get the same results as a single thread. The easiest way to circumvent this is to use itertools.product, that makes an iterator of what would be otherwise a nested loop.
import requests
from concurrent.futures import ThreadPoolExecutor as ThreadPool
from itertools import product

#   ... snipped df definition ...

def get_links(packed_pars):
    url, id_, make, model = packed_pars
    headers = {
        'authority': 'www.theparking.eu',
        'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="97","Chromium";v="97"',
        'accept': '*/*',
        'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'x-requested-with': 'XMLHttpRequest',
        'sec-ch-ua-mobile': '?0',
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36',
        'sec-ch-ua-platform': '"macOS"',
        'origin': 'https://www.theparking.eu',
        'sec-fetch-site': 'same-origin',
        'sec-fetch-mode': 'cors',
        'sec-fetch-dest': 'empty',
        'referer': 'https://www.theparking.eu/used-cars/used-cars/',
        'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',
    }
    data = {
        'ajax': '{"tab_id":"t0","cur_page":1,"cur_trie":"distance","query":"","critere":{"id_pays":[%s],"id_marque":[%s], "id_modele":[%s]},"sliders":{"prix":{"id":"#range_prix","face":"prix","max_counter":983615,"min":"1","max":"400000"},"km":{"id":"#range_km","face":"km","max_counter":1071165,"min":"1","max":"500000"},"millesime":{"id":"#range_millesime","face":"millesime","max_counter":1163610,"min":"1900","max":"2022"}},"req_num":1,"nb_results":"11795660","current_location_distance":-1,"logged_in":false}' % (round(id_), round(make), round(model)),
        'tabs': '["t0"]'
    }
    response = requests.post(url, headers=headers, data=data)
    test = response.json()
    pages = round(int(test['context']['nb_results'])/27)
    if pages != 0:
        print(f'You are on this link:{url}, with {pages} pages')
    else:
        print("no pages")
    return url, pages

with ThreadPool(8) as pool:
    rv = pool.map(get_links, product(df['links'], df['country_id'], df['make'],
                                     df['model']))
    # This converts rv to the dict of the original post:
    formal_data = dict()
    filtered_list = [(url, pages) for url, pages in rv if pages]
    if filtered_list:
        formal_data['links'], formal_data['total_pages'] = zip(*filtered_list)
    else:  # Protect against empty answers
        formal_data['links'], formal_data['total_pages'] = [], []

As for why this is not producing any output: at last with the data provided in the question, test['context']['nb_results'] is 0 every time. It is very likely that your query returns zero items each time even with the full dataset.
Some other comments:

*

*The use of m̀ultiprocessing.pool.ThreadPool is not recommended: you should switch to concurrent.futures.ThreadPoolExecutor.

*You are not using threadLocal at all: it can be removed. I do not know what you would use it for.

*You are importing threading but not using it.

*request responses have a json method that parses the text right away: there is no need for importing json in this case.

*It is very likely that you want to ceil instead of round the number of pages.

*Since you are waiting for I/O, it is OK to use more threads than available cores.

A: so one thing is that for programs like using web apis where they are I/O bound (here where the performance hit taking is waiting on requests from another machine/server/etc), the more general approach is to using async programming. a good library for async http requests is httpx (there are others as well). you'll find interface of these libraries similar to requests along with allowing to be able to do async or sync, so should be easy transition to use. from there will want to learn about async pogramming in python. the quickstart and async along with other good tutorials can find via google on general python async programming.
can see that this is approach other python http wrapper libraries do like asyncpraw
Just as quick note on why async is nice vs multiprocessing. is that:

*

*async essentially allows with a single process/thread executes other parts of program as other pars on waiting on output, so basically feels as if all of the code is executing in parrellel

*multiprocessing is actually kicking off separate processes (i am paraphrasing a bit but thats the gist) and likely wont get same performance gains like would in async.


text:
Q: Can mongoose do such thing? DB collection is like:
        "suid" : "8986691b1db3d99b6fbe27cceac2e19c",
        "auid" : "22e7e5632acb4ac154b9bcb95710ca38",
        "msg" : "ceshi1",
        "ctime" : ISODate("2013-05-22T03:52:26.344Z"),
        "sended" : true,
        "__v" : 0,
        "_id" : ObjectId("519c411351db351236000001")
MongoDB shell command is:
db.runCommand({"group":{ns:"messages",key:{"auid":true},"initial":{"lastmsgtime":0},condition:{auid:'456'},$reduce:function(doc,prev){senttime=doc.ctime.valueOf();if(senttime>prev.lastmsgtime){prev.suid=doc.suid;prev.lastmsgtime=new Date(senttime);}}, } })
Can mongoose do this job?

A: Mongoose doesn't have direct support for group, so you need to access the native driver's group method via your Mongoose model like this:
Model.collection.group({"auid":true}, ...);


text:
Q: How to compose a sentence for possession? Apostrophe or preposition? I would like to know the difference between these sentences:

I have never seen any of his father's cars (I think it's correct).  I have never seen any cars of his father (I think it's wrong).

In my opinion this is definitely incorrect.

I have never seen his father's any cars.

What is the commonest way to write the sentence? What's better? An apostrophe to show the possession or a preposition?

A:
I have never seen any of his father's cars

This is correct. This is the one that any native speaker would use.

I have never seen any cars of his father

This is wrong, however "I have never seen any of the cars of his father" is, as far as I am aware, grammatically correct. But please never write this, it sounds incredibly awkward and no native speaker would speak or write this way unless they were intentionally trying to sound like a Norse god or something.

I have never seen his father's any cars.

This is completely wrong, I couldn't even understand it without seeing the other two sentences.
In general, we use an apostrophe for possession. There are, however, times when a preposition is used (particularly when trying to sound important). Things like titles (The Lord of the Rings rather than The Rings' Lord) or announcements (Will the owner of the blue car outside please move their vehicle) are places that you might use a preposition.


text:
Q: PHP Separation of Concerns and MVC To start with I'm not exactly sure if this question will fit the question model of SO so moderators please close it if it doesn't fit...
I have been reading a lot on MVC and SoC lately and how they relate to programming in PHP and am having some difficulty grasping how the concepts differ to my current programming style. Any application I write uses url_rewrite routes, with the routing handled by a single file which selects the appropriate controller.php file based on the sub system requested. Then within that controller file the final smarty template file is assigned and the PHP file which contains the business logic of the page in question is included into the stack.
The issue I am having is that while I review MVC and SoC information all the examples I see are written as extensive inter-dependant classes and some rather deep namespaces, but when I code I only use objects where I need an object for reusable but distinct code (in line with object examples on the PHP site itself), and so wind up with some code being classed and namespaced nearly 70% of my application remains in the global namespace with no classing. It seems to me that this coding technique still meets the design principal of separation of concerns, though i'm not so sure about being MVC as every example of MVC I can find is built solely out of a very large number of classes.
Could someone please explain if I am way off base here or if I am achieving SoC and possibly even MVC with my current coding and explain to me if embedding the entire application within a range of classes is a requirement for SoC and MVC.
Thanks

A: OK I usually take on these open ended questions :P
Let me rephrase your whole thing to a new question – and feel free to tell me I am wrong!
I think you are asking - "Is my coding style in-line with best practice for x y z?"
Now look – i have been in a variety of roles, and I strongly believe that no one has ever cracked a complete SoC architecture – at some point there is always a trade-off between enabling someone at the view end to do their job, and someone upstream ingesting the input and making it work such that it ties to the database and logic.
For example - I am actually right now building a system that takes HTML files as input, reads them via PHP. PHP converts the HTML elements to a bunch of JSON and adds logic to that JSON based on x, y and z, then shoves it out to Facebook React components – which converts it all back to HTML / DOM – when you explain to someone that there is a sausage machine that takes, as input, HTML, and outputs HTML, you can see why they might go – holy shit what are you doing!!
Now – why did we do this? Because it made sense for the project, and it made sense for the team. We could have equally used some pre-defined framework and blah blah blah – however this worked for us.
(a caveat here would be, if you need a highly performant application, this might be the wrong approach, however – bear in mind that what you read (inter dependant classes etc.) may also not be performant – optimisation of PHP code is hard work – my advice here is, get it working first, then if the product is successful, pay someone to fix your shitty code – server time is cheap – your time is not)
My statement for you would be, without concrete examples and use cases – people will struggle to comment on your approach – but understand that there are many different ways of doing things and you may see much open source code written in one way or another, but if you write something that achieves a goal, your only concern should be that it is performant and that it has 'enough' separation such that your designer can work on design, your coder can work on code and your CEO can look at sales figures.
Hope this helps.

A: From the information you've given, you're doing a good job. I think you have a grasp at Separation of Concerns and probably MVC. I think you should take a closer look at how things are abstracted in other codebases, how things are modularized, and think about how you would handle things that potentially come up in web development.
What if I want to have some code run before every controller? Or middleware that runs between the request and the controller? Or inject a variable into the view after every controller is processed? How are you separating POST, GET, PUT, DELETE logic but still grouping them within a resource? Some of these can be achieved with your architecture but I think many of the solutions would be cleaner with a class-heavy architecture. Of course, something being cleaner is in the eye of the beholder.
Frameworks released to the public try to be generic and tackle as many use cases as possible. One issue I see is that you make the assumption that the controller file would be called last and then setup the view. So, even though the logic in there is in the global state, it only exists within that file. In essence, the file acts as a namespace. I don't think that's an assumption a generic web framework should make, but it's something you can get away with when writing something for yourself.


text:
Q: Bind datasource to a datagridview I use .net 4.0 c# in winform. Now I use a stored procedure to insert a new row to the database. Obviously I am confused by binding steps between asp.net and windows form. In asp.net it is very simple but in winform it seems like we must use BindingSource object???
Which means in winform we have to use a different way. The following code is that I used to use in asp.net to insert new record and binding. How to rewrite it to bind the datasource to a datagridview.
public void ExecuteNonQuery(string storedProcedure, Dictionary<string, object> parameters)
    {
        using (SqlConnection conn = new SqlConnection(_connectionString))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand(storedProcedure, conn))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                if (parameters != null)
                {
                    foreach (string parameter in parameters.Keys)
                    {
                        cmd.Parameters.AddWithValue(parameter, parameters[parameter] ?? DBNull.Value);
                    }
                }
                cmd.ExecuteNonQuery();
            }
            conn.Close();
        }
    }

After setting parameters, then call it like:
        DBAccess dbaccess = new DBAccess(connString);
        dbaccess.ExecuteNonQuery("InsertStoredProcedure", parameters);

I don't know how to bind database to the datagridview.
 Thanks.

A: If you inserted a Row to database, then you need to fetch the rows from the database again. using the another Stored Procedeure (with SELECT Query).
you are using ExecuteNonQuery, that means you are not querying anything from the database. So It willn't give you result in the form of grid. But it will just return an integer with number of row affected.
So my suggestion is after inserting the row, write another query to fetch the rows with cmd.ExecuteReader() and bind the SqlReader object to Grid.
I Hope that will resolve your problem.


text:
Q: Is there any way to refresh the compose window through a Gmail Addon? I've created an addon that, upon user request, replaces the attachments with a password-protected zip. It basically reads the draft and updates it with the new attachment, thus removing the previous ones, using something like this:
draft.update(message.getTo(),message.getSubject(), message.getBody(), {attachments: zipAttachment, cc:message.getCc(), bcc:message.getBcc(),  htmlBody: message.getBody()});

The behavior I'm seeing is that the draft email is correct but the changes are not reflected on the compose window. If the user closes the compose window and re-opens it from the draft, it's fine, but I would like to "refresh" the compose window with the updated version of the message.
Is there any way to do this?


text:
Q: Image aspect ratio changes even with match_aspect set to true in bokeh figure with image_url I tried to keep the aspect ratio of an online image as is. However, the aspect ratio will change when the browser window is resized. This doesn't happen with image, but happens with image_url. Is this a feature or a bug? Thanks.
I use the figure(match_aspect=True) and need to stretch the layer to occupy the full window layer = layout(p, sizing_mode='stretch_both')

Sample code
from bokeh.plotting import figure, show
from bokeh.layouts import layout
p = figure(match_aspect=True)
p.image_url(['https://static.bokeh.org/logos/logo.png'],0,0,1,1)
layer = layout(p, sizing_mode='stretch_both')
show(layer)


text:
Q: Magento dashboard not updating Since now i see a problem on a dashboard from our client, it is showing the amount of orders but not the total value (price) of the orders... That is stopped since i think 2 weeks.
The total value stays on 5.949,90 but only the amount of orders is counting not the value of it.

A: To refresh sales report statistics:
1.  On the Admin menu, select Reports > Refresh Statistics.
2.  In the list, select the checkbox of each report that needs to be refreshed.
3.  Set the Actions control to one of the following:

Refresh Lifetime Statistics
Refresh Statistics for the Last Day

4.  When complete, click the Submit button.


text:
Q: Angular ng-repeat not functioning I am attempting to display JSON data to a view via an $http() call.  I am getting my data back, however, the ng-repeat is not displaying my data properly.  I am getting a console error stating "Error: $digest already in progress".
Another note is that the getRoundDetails() function is being called in the addRound() from the previous view's submit.
I am relatively new to using Angular and have never seen a $digest reference.  Please help.
Here is my controller.js:
statTrackerApp.controller('roundController',
    function($scope, $http, $window, $route) {
        $scope.newRound = {};
        $scope.savedRound = {};
        $scope.roundDetails = []; //I have tried {} as well with no success

        $scope.facilities = {};
        $scope.courses = {};
        $scope.tees = {};
        $scope.holes = {};

        ...

        $scope.addRound = function () {
            $http.post("/api/round/", $scope.newRound)
                .then(function (result) {
                    // Successful
                    //angular.copy(result.data, $scope.facilities);
                    //$window.location = "#/facilities";
                    $scope.savedRound = result.data;
                    $scope.getRoundDetails();
                    $window.location.href = '#/roundDetail';
                },
          function () {
              // Error
              alert("Could not save new round");
          });
        };
        $scope.getRoundDetails = function () {
            $http.get("/api/roundDetail/" + $scope.savedRound.roundId)
                .then(function (result) {
                    // Successful
                    //angular.copy(result.data, $scope.roundDetails);

                    $scope.roundDetails = result.data;
                },
                    function () {
                        // Error
                        alert("Could not load round details.");
                    });
        };
    });

Here are my 2 view wrappers:
<form class="form-horizontal" role="form" ng-submit="addRoundDetails()" ng-controller="roundController">

</form>

<form class="form-horizontal" role="form" ng-submit="addRound()" ng-controller="roundController">

</form>

Here is the _roundDetails-form.html:

Round Details

                    {{roundDetail.roundDetailId}}

Here is _round-form.html:

Round

                Facility:
                <select ng-change="getCourses(newRound.facilityId)" ng-model="newRound.facilityId" class="form-control" id="facility" required="required">
                        <option ng-repeat="facility in facilities" value="{{facility.facilityId}}">{{facility.name}}</option>
                    </select>

                Course:
                <select ng-change="getTees(newRound.courseId)" ng-model="newRound.courseId" class="form-control" id="course" required="required">
                        <option ng-repeat="course in courses" value="{{course.courseId}}">{{course.name}}</option>
                    </select>

                Tees:
                <select ng-model="newRound.teeId" class="form-control" id="tee" required="required">
                        <option ng-repeat="tee in tees" value="{{tee.teeId}}">{{tee.name}}</option>
                    </select>

                Date:
                <input type="date" ng-model="newRound.date" class="form-control" id="date" required="required" placeholder="Enter date." />

                Is Official:
                <input type="checkbox" ng-model="newRound.isOfficial" class="form-control" id="official" />

                Holes:
                <input type="checkbox" ng-model="newRound.holes" class="form-control" id="holes" />

                Hole by Hole:
                <input type="checkbox" ng-model="newRound.hbh" class="form-control" id="hbh" />

                Total Score:
                <input type="text" ng-model="newRound.TotalScore" class="form-control" id="score" value="0" />

                            <input ng-click="getHoles(newRound.teeId)" type="submit" class="btn btn-primary" value="Save Round" />


text:
Q: Can't get a script file in Jade | Error 404 I'm new to Jade and I'm really strugling with it, I created a simple drag and drop table system, but for some reason I can't use my script file in jade. I have a css and a JS file and I linked both to the jade file, for some reason only the css is connected correctly...
script(src='routes/dragdrop.js' type='text/javascript')

This is the reference to the "dragdrop.js" file, I put it at the end of the body tag. The console log gives me the following:
GET /routes/dragdrop.js 404 20.949 ms - 507

What's possibly wrong here?

A: If you have your file index.jade located in /sample/views/index.jade and dragdrop.js in /sample/routes/dragdrop.js then if you want to call dragdrop.js from index.jade you should call it in this way script(src='../routes/dragdrop.js' type='text/javascript').
If you'd need to go back two folders you should use ../.. three ../../... and so on.


text:
Q: How to select all div in `.content` but not contain the div I don't want to? How to select all div in .content but not contain the div I don't want to?
.content div:not(class="a", class="c"){ // not work
    display: none;
}

    ...

A: Chain them together, and use .a or .c for classes a and c:
.content div:not(.a):not(.c){
    display: none;
}

Working jsFiddle


text:
Q: How to place elements where you want on a webpage? I'm very new to web development. I feel confident in my knowledge in HTML and CSS to start building my webpage and I was exposed to a very small amount of bootstrap. My question is regarding a personal webpage I am building for myself. I want to have a navigation bar on the top that will link to different pages such as: "Home", "about me", "Projects". But I still have a hard time understanding how to position them where I want. My idea is to make these 3 fields a list, take out the list styling, and then make these elements inline-block. But for some reason, my code does not translate to what I want which is all 3 phrases on a single line and spaced out evenly. Further, even if I can manage that how can I control where it goes beside floating left or right or using bootstrap? Even though it may be less efficient can anyone explain to me the naive way of hardcoding it with just HTML and CSS just so I have an understanding? Do I have to manipulate the margins and padding through trial and error? Any advice would be appreciated, I have just begun to learn HTML and CSS but I am determined to get good at web development.
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>First WebPage</title>
    <link rel="stylesheet" type="text/css" href = "style.css">

Home

About Me

Projects

My CSS is
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.top-border {
  width: auto;
  height: 100px;
  background-color: #D46A6A;
}

.navbar{
  float:left;
  display: inline-block;
  list-style: none;
  margin-left: 20px;
}

A: Using
 tag is not proper way for layout implementation, Please omit them, I proffer using flex, the flex-box methods are very simple and useful. see below code:
.navbar {
  display: flex;
  flex-direction: row;
}

For more styles, use your past CSS.

A: to make your menu single line, remove
 from your list and set li to float: left

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.top-border {
  width: auto;
  height: 100px;
  background-color: #D46A6A;
}

.navbar {
  float: left;
  display: inline-block;
  list-style: none;
  margin-left: 20px;
}

.navbar li {
  float: left;
  border-right: 1px solid yellow;
  padding: 2px 5px
}

Home

About Me

Projects

A: Not using bootstrap here, as you have mentioned in your question

         Home
         About
         Project

Also, don't forget to make the body margin 0.

A: I found that w3css (https://www.w3schools.com/w3css/) was easier than Bootstrap, had enough structure to produce the types of layouts you describe, AND has the added bonus of having a really small code footprint. Standard CSS only (No jQuery or JavaScript library).
Each feature links to a  'Tryit' editor. This link shows the layout you describe with two cells.
(https://www.w3schools.com/w3css/tryit.asp?filename=tryw3css_layout_container)

Hello W3.CSS Layout.

Hello W3.CSS Layout.

Just add one more cell block, and you're there.

Hello W3.CSS Layout.

Hello W3.CSS Layout.

Hello W3.CSS Layout.

Hope this helps, good luck!


text:
Q: Not booting - Failed to start user manager for uid 121 My Ubuntu 18.04.4 won't start.
It goes into a black screen where it tries to start User Manager for UID 121
And then display the message:
Failed to start User Manager for UID 121
See 'systemctl status user@121.service' for details.

I managed to access the desktop through recovery mode but it happens at each start-up now.
I tried Repair Broken packages but does not not fix it.


text:
Q: What is Ampere force for a thick/wide conductor? In simple case in uniform constant Magnetic field, when field is perpendicular to the wire and when wire is very thin Ampere force $F=I B L$
where I - current, B - magnetic field, L - the length of the wire.
What happens if we have not a small wire, where the current goes uniformly?
For example, if I have a metal plate (or aluminium foil) of length L and width d and connect it in such a way, that current goes uniformly in it. and total current is I (when I measure it directly at current source). Is the Ampere force in this simple case (uniform constant Magnetic field, field is perpendicular to the current) will be the same $F=I B L$ or it depends on width d somehow? Or I need to integrate exact equation $dF=I B dl $ to get a full force?

A: The magnetic force on a general current distribution is $$\vec{F} = \int \vec{j}\times \vec{B} \,dV$$ but in this case the current density has constant magnitude and direction, and the same applies to the magnetic field $\vec{j} = \frac{I}{dh} \hat{x}$, $\vec{B} = B\hat{y}$, where $h$ is the size of the plate in the $z$ direction. Therefore the integral takes the form $$\vec{F} = \frac{IB}{dh}\hat{z} \int \,dV = \frac{IB}{dh}dhL = IBL$$


text:
Q: Sleak in RCP: Device is not tracking resource allocation I have tried to make Sleak work on my Indigo RCP application. I have followed the steps on this guide. I.e. I have installed the plugin, added the swt tools plugin to current plugins, added the required plugins, modified the tracing options, and added the view in my application with folder.addView("org.eclipse.swt.tools.views.SleakView");
The view does indeed show up but I keep getting the error 'Device is not tracking resource allocation' when I try to use it.
I have tried the answers to older questions in stackoverflow on the matter, but had no luck
Sleak (SWT & RCP) : Device is not tracking resource allocation (eclipse 4.3)
Sleak SWT tool, Device is not tracking resource allocation
I have explicitly checked that the .options file loaded in the debug configuration does indeed have both the tracing options needed.
Any additional ideas?

A: I think you haven't set these properties correctly:
org.eclipse.ui/debug=true
org.eclipse.ui/trace/graphics=true

A: I faced the same problem recently, and managed to find a solution.  Here's what I found, who knows it might help you.
On RCP startup, there's a call to PlatformUI.createDisplay(), which chains to a call to Workbench.createDisplay().  That's the exact point where the debug settings needed by Sleak are properly read and set.
What happened on our software was that a call to Display.getDefault() was made BEFORE the above call to PlatformUI.createDisplay().  It caused the creation of a new Display object, which was set as the default.  This creation did not read and set the debug settings.
By the time our code got to the PlatformUI.createDisplay() call, it didn't actually create a new Display.  Instead, it returned the previously-created, not-debug-friendly one.  Thus leading Sleak into warning about "device not tracking resource allocation".
Adding a breakpoint at the method Display.register (Display display) helped us identifying the early creation origin and properly change it.


text:
Q: How to access "user.home" with Java on a Raspberry Pi and write to it? I have some issues creating files on a Raspberry Pi. The same code runs on Windows without any problems...
Surprisingly System.getProperty("user.home"); returns just /.
System.getProperty("user.dir"); returns /var/lib/abc but i guess my application has no access to it.
The code:
    String path = System.getProperty("user.dir") + "/def";
    File file =  new File("/a.txt");
    file.delete();
    try {
        new File(path).mkdirs();
        file.createNewFile();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    try {
        FileWriter writer = new FileWriter(file);
        writer.write(value);
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

The exceptions:
/var/lib/abc/def/a.txt (No such file or directory)
java.base/java.io.FileInputStream.open0(Native Method)
java.base/java.io.FileInputStream.open(FileInputStream.java:219)
java.base/java.io.FileInputStream.(FileInputStream.java:157)
java.base/java.io.FileInputStream.(FileInputStream.java:112)
java.base/java.io.FileReader.(FileReader.java:60)

*

*

No such file or directory
java.base/java.io.UnixFileSystem.createFileExclusively(Native Method)
java.base/java.io.File.createNewFile(File.java:1035)

*

*

/var/lib/abc/def/a.txt (No such file or directory)
java.base/java.io.FileOutputStream.open0(Native Method)
java.base/java.io.FileOutputStream.open(FileOutputStream.java:298)
java.base/java.io.FileOutputStream.(FileOutputStream.java:237)
java.base/java.io.FileOutputStream.(FileOutputStream.java:187)
java.base/java.io.FileWriter.(FileWriter.java:96)

Any ideas where and how to create a file without access restrictions? It should work across plattforms.

A: Try Runtime.getRuntime().exec(),
public static String getUserHomeDir() throws IOException {
      return new BufferedReader(new InputStreamReader(Runtime.getRuntime().exec(new String[]{"sh", "-c", "echo $HOME"}).getInputStream())).readLine();
}

use pwd for user.dir


text:
Q: SQLSTATE[HY000] [2002] No such file or directory У меня не так много опыта работы с докером, из за чего не совсем понимаю почему вышла эта ошибка.

Я уже испробовал самые популярные варианты (изменить в .env DB_HOST c localhost на 127.0.0.1 или же на имя контейнера) так же указание пути к soket.
Docker-compose файл, модуль приложения и бд:
  db:
    image: mysql:8.0
    container_name: db
    restart: unless-stopped
    tty: true
    ports:
      - "8001:3306"
    environment:
      MYSQL_DATABASE: test_db
      MYSQL_ROOT_USER: root
      MYSQL_ALLOW_EMPTY_PASSWORD: 1
    volumes:
      - /var/data/mysql:/var/lib/mysql
      - /etc/mysql:/etc/mysql
      - .docker/mysql/mysql-files:/var/lib/mysql-files
      - .docker/mysql/my.cnf:/etc/mysql/my.cnf
    networks:
      - test-app

  php-fpm:
    depends_on:
      - db
    build:
      context: .docker/php-fpm
      dockerfile: Dockerfile
    image: test-php-fpm
    environment:
      XDEBUG_REMOTE_ENABLE: 1
    volumes:
      - .:/var/www/laravel:delegated
      - .docker/php-fpm/extra-config.ini:/usr/local/etc/php/conf.d/extra-config.ini:cached
      - .docker/php-fpm/laravel-schedule:/etc/cron.d/laravel-schedule:cached
      - ~/.composer/cache:/root/.composer/cache:delegated
    networks:
      - test-app

.env:
DB_CONNECTION=mysql
DB_HOST=db
DB_PORT=8001
DB_DATABASE=test_db
DB_USERNAME=root
DB_PASSWORD=

database.php:
'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '8001'),
            'database' => 'test_db',
            'username' => 'root',
            'password' => env('DB_PASSWORD', ''),
            // 'unix_socket' => env('DB_SOCKET', ''),
            'unix_socket' => '/var/run/mysqld/mysqld.sock',
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

конфиг php
extension=imagick.so

pdo_mysql.default_socket=/var/run/mysqld/mysqld.sock

post_max_size = 1G
upload_max_filesize = 1G
max_file_uploads = 200
memory_limit = 1G

К самой бд подключиться могу спокойной через тот же heidiSQL, есть предположение что дело с php или с самим докером, заранее спасибо за помощь!

A: Миграции выполнили?
php artisan migrate

Второй вариант, идем в класс модели и смотрим название таблицы в переменной $table и сверяем с названием в БД.


text:
Q: ELOGIN error while connecting to the SQL server I'm learning full stack web development and was trying to connect to SQL server from my backend Node.js. I was following an online video. While running the index.js file I get the below error -
ConnectionError: Login failed for user 'systemadmin'.
    at C:\Users\akunjalw\Desktop\FullStack\server\node_modules\mssql\lib\tedious\connection-pool.js:70:17
    at Connection.onConnect (C:\Users\akunjalw\Desktop\FullStack\server\node_modules\tedious\lib\connection.js:1038:9)
    at Object.onceWrapper (node:events:640:26)
    at Connection.emit (node:events:520:28)
    at Connection.emit (C:\Users\akunjalw\Desktop\FullStack\server\node_modules\tedious\lib\connection.js:1066:18)
    at Parser.<anonymous> (C:\Users\akunjalw\Desktop\FullStack\server\node_modules\tedious\lib\connection.js:2574:20)
    at Object.onceWrapper (node:events:639:28)
    at Parser.emit (node:events:520:28)
    at Readable.<anonymous> (C:\Users\akunjalw\Desktop\FullStack\server\node_modules\tedious\lib\token\token-stream-parser.js:32:12)
    at Readable.emit (node:events:520:28) {
  code: 'ELOGIN',
  originalError: ConnectionError: Login failed for user 'systemadmin'.
      at Login7TokenHandler.onErrorMessage (C:\Users\akunjalw\Desktop\FullStack\server\node_modules\tedious\lib\token\handler.js:239:19)
      at Readable.<anonymous> (C:\Users\akunjalw\Desktop\FullStack\server\node_modules\tedious\lib\token\token-stream-parser.js:26:33)
      at Readable.emit (node:events:520:28)
      at addChunk (node:internal/streams/readable:315:12)
      at readableAddChunk (node:internal/streams/readable:289:9)
      at Readable.push (node:internal/streams/readable:228:10)
      at next (node:internal/streams/from:98:31)
      at processTicksAndRejections (node:internal/process/task_queues:96:5) {
    code: 'ELOGIN',
    isTransient: undefined
  }
}
undefined
[nodemon] clean exit - waiting for changes before restart

The code is as follows
const sql = require("mssql");

const config = {
  user: "systemadmin",
  password: "R@jasthaan1212",
  server: "localhost",
  database: "ORG_EMPLOYEEDATA",

  options: {
    trustedconnection: true,
    trustServerCertificate: true,
    enableArithAbort: true,
    instancename: "SQL2019",
  },
  port: 50685,
};

async function getEmployeeName() {
  try {
    let pool = await sql.connect(config);
    let employeeData = await pool
      .request()
      .query("select * from dbo.EMPLOYEES_DATA");
    return employeeData.recordsets;
  } catch (error) {
    console.log(error);
  }
}

module.exports = { getEmployeeName: getEmployeeName };

const dboperations = require("./dboperations");

dboperations.getEmployeeName().then((result) => {
  console.log(result);
});

Please let me know what exactly I'm missing here. I couldn't find the way to resolve this by searching in internet as well, may be I'm terrible at searching. Any help to resolve this is appreciated.


text:
Q: Fullcalendar 5 resourceLabelContent return promise I'm using FullCalendar 5 with Angular.
I want to display a custom resource label based on data from database. I use the resource render hook resourceLabelContent with returning an HTML string.
In order to get the data I need, I must to define the function as an asynchronous function with the use of async and await (see code example below).
My problem is : as soon as I add the keyword async to my function, resources labels aren't displaying anymore. I think it's because the function is now returning a Promise and not a "{ html : '..' }.
What I want to do : I have users who are attached to different places (resources) according to the dates. I want to display the name of the users below the resource label using resourceLabelContent. I must therefore request my database to retrieve them and so make an asynchronous request.
Is there a way to display resources label with async function or should I avoid it ?
Code example :
async resourceLabelContent(info) {

  const date = info.date;
  const usersAvailable= await this.service.getUsersAvailable(date, info.resource.id);

  return { html: '<span>'+ usersAvailable+'</span> }
}

Just in case, how I bind my function :
this.calendarOptions.resourceLabelContent = this.resourceLabelContent.bind(this);

EDIT : In order to be clearer, I've added a description of what I need to do with resourceLabelContent

A: Since your function is async, is returns a Promise. So, in order to use it, you have to change your calling code
resourceLabelContent()
.then(response => response.json())
.then(data => console.log(data)) // <-- Here is your expected data

Give it a try!


text:
Q: Bubble sort doesn't print the right winner - CS50 week 3 as a beginner - I'm lost please help a newbie like me, I'm lost, I don't get it - I looked at answers, it still doesn't work and I can't spot the error.
I'm working on plurality, I know we can solve it without bubble sort but I want to find out why my solution isn't working.
I bubble sorted it - and I can't get the right names to print.
I feel like I tried to put the printf everywhere in any bracket and it is never right and shows me any solution but the right one.
Currently, it prints the last 2  names regardless of who has the most votes.
I feel like it's something pretty simple and basic but it's been 3 days now and I can't get anywhere - please help me, where am I misunderstanding things?
void print_winner(void)
{
int temp;
for (int i = 0; i < candidate_count; i++) //going through each name/vote struct - -1 because c-count is acvg arguments
{
    for(int j = 0; j < (candidate_count - i - 1); j++) // c_c - i - 1 is for ignoring already compared candidates
    {
        if (candidates[j].votes < candidates[j + 1].votes)
        {
            temp = candidates[j].votes;
            candidates[j].votes = candidates[j + 1].votes;
            candidates[j + 1].votes = temp;
        }
    }
}

int top = candidates[candidate_count - 1].votes;

for (int i = 0; i < candidate_count; i++)
{
    if (candidates[i].votes == top)
    {
        printf("%s\n", candidates[i].name);
    }
}
return;
}


text:
Q: How to unit test angularjs route's resolve with karma and mocha+chai? I am working on an app where I need to resolve promises in the router (ngRoute). The problem is that I am not sure how to write the unit tests for this, I am using karma with mocha and chai.
Here is the part of the code I'd like to test:
function config ($routeProvider) {
    $routeProvider
        .when('/', {
             templateUrl: 'views/orders.html',
             controller: 'OrderController',
             controllerAs: 'vmr',
             resolve: OrderController.resolve,
             data: {...}
    });
}

function OrderController (OrderService, newOrders) {
    this.newOrders = newOrders;
}

OrderController.resolve = {
    newOrders: function (OrderService) {
        return OrderService.getOrders();
    }
};

This is how I started to write my unit tests when I didn't have the resolve part yet:
describe('OrderController', function() {

    'use strict';

    var controller,
        service,
        httpBackend;

    beforeEach(module('myApp.orders'));

    beforeEach(inject(function($controller, _OrderService_, $httpBackend) {
        service = _OrderService_;
        httpBackend = $httpBackend;
        // Create the controller
        controller = $controller('OrderController', {});
    }));

    beforeEach(function() {
        httpBackend.when('GET', 'url/to/get/orders')
            .respond(200, {[...]});
    });

    afterEach(function() {
        httpBackend.verifyNoOutstandingExpectation();
        httpBackend.verifyNoOutstandingRequest();
    });

    it('should get the list of new orders', function() {
        httpBackend.flush();
        expect(controller.neworders).not.to.undefined;
        expect(controller.neworders.length).to.equal(3);
    });
});

At this point is where I am getting the error:

Unknown provider: newOrdersProvider <- newOrders

I understand why I get this error, but I don't know how to solve it. Basically I don't know how to test the promise that resolves in the route.
Thanks in advance for your help!

A: After a lot of searching and reading the AngularJS Testing Cookbook I find out how to inject the result of the promise in the controller.
The main code doesn't change, so I will post here only the update code for the unit tests:
describe('OrderController', function() {

    'use strict';

    var controller,
        service,
        httpBackend;

    // here is where I will inject a new value
    beforeEach(function() {
        module('myApp.orders', function($provide) {
            $provide.value('resolver', {
                newOrders: function(service) {
                    return service.getOrders();
                }
            });
        });
    });

    beforeEach(inject(function($controller, _OrderService_, $httpBackend, resolver) {
        service = _OrderService_;
        httpBackend = $httpBackend;
        // Create the controller
        controller = $controller('OrderController', {
            // add them to the controller
            newOrders: resolver.newOrders(service)
        });
    }));

    beforeEach(function() {
        httpBackend.when('GET', 'url/to/get/orders')
            .respond(200, {[...]});
    });

    afterEach(function() {
        httpBackend.verifyNoOutstandingExpectation();
        httpBackend.verifyNoOutstandingRequest();
    });

    it('should get the list of new orders', function() {
        httpBackend.flush();
        expect(controller.neworders).not.to.undefined;
        expect(controller.neworders.length).to.equal(3);
    });
});

If someone has a better/different solution I'd like to hear it as well!


text:
Q: android monkey runner scripts I was trying to run a a sample python program using monkey runner but unfortunately throwing an error of this type :
Can't open specified script file

Usage: monkeyrunner [options] SCRIPT_FILE

-s      MonkeyServer IP Address.
-p      MonkeyServer TCP Port.
-v      MonkeyServer Logging level (ALL, FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE, OFF)

Exception in thread "main" java.lang.NullPointerException
 so any one can guide me how to resolve this and how to use monkey runner to execute this type of things

A: I've found that making the path to the script absolute helped monkeyrunner.
I am invoking the runner from a Python script where a helper class has a startMonkey method:
def startMonkey(self, monkeyScript):
    command = [ self.env + '\\tools\\monkeyrunner.bat' ]
    command.append( os.path.abspath( monkeyScript ) )
    return startProcess( command )

This seems to be working for me.

A: Script file should be a full path file name try below monkeyrunner c:\test_script\first.py
So go to the folder \ sdk \ tools

and press shift and right click to open command prompt and type monkeyrunner c:\test_script\python_file_name.py


text:
Q: table with sales and quantity of products - add column that count the products i have this table:

i want to add column:count - that i can see for each product how many sales were, like this:

i try like this:
update #t
set quantity = (select count(*) from #t group by product)

it is not good because it's return more then 1 value

A: You can use window function :
sum(quantity)  over (partition by product)

Or you can correlated your subquery :
update t1
       set t1.quantity = (select sum(t.quantity)
                          from #t as t
                          where t.product = t1.product
                         )
from #t t1;

A: Use window functions:
select
    t.*,
    sum(quantity) over(partition by product) cnt
from mytable t

As suggested by jarlh, a better idea than updating would be to create a view, so you don't need to worry about maintaining integrity of the derived column:
create view myview
select
    t.*,
    sum(quantity) over(partition by product) cnt
from mytable t

A: Use window functions:
update #t
    set quantity = new_quantity
    from (select t.*, count(*) over (partition by product) as new_quantity
          from #t t
         ) t;

You should probably do this when you create the temporary table, but you can update the value afterwards as well.


text:
Q: position a absolutely positioned div dynamically At this page, from view port width 1024px and narrower, the #slider's absolute position stops working properly, because the logo's width becomes fluid:

.top_header-logo.grid12-8 img {
    width: 80%;
}
#slider {width: 90%; position: absolute; left: 0; top: 184px; display:table-cell; background-color: #8A0E02; z-index: 9998;}
@media only screen and (max-width: 1199px) {
    #slider {top: 165px;}
}
@media only screen and (max-width: 1024px) {
    #slider {top: 145px;}
}

I'm looking for a solution to allow the #slider to be positioned at the top of <div class="banner grid12-12"> (i.e. directly below the navigation menu, with no gap).
I could make #slider position:relative; but that would destroy the layout of the slider/sidebar combination.
Help appreciated.


text:
Q: CSCore: playback float array from pure data I'm writing a program in C# which communicates with pure data using the libpd library (more information: http://libpd.cc/)
My pure data patch is simply creating a sine wave.
I wrote some test code to see if I get any data from my pure data patch. The LibPD.Process method writes samples into the outbuffer array and the contents are continuous values between -1 and 1:
// Initialise Pd with 0 input and 2 output channels and a samplerate of 44100. Project dependent.
int pdOpen = -1;
pdOpen = LibPD.OpenAudio(0, 2, 44100);

if (pdOpen != 0)
{
    Console.WriteLine("Error opening audio... exiting");
    return;
}

string patchFile = @"..\..\..\test.pd";
int patch = LibPD.OpenPatch(patchFile);
LibPD.ComputeAudio(true);

//Read from Process Function...
// The size of each buffer must be the product of the number of channels, the number of ticks,
// and the number of samples per tick. (The number of samples per tick is the value
// returned by libpd_blocksize(), i.e., 64.)

int ret;
float[] outbuffer = new float[2 * 1 * LibPD.BlockSize]; // Size = 128

for (int i = 0; i < 10; i++)
{
    ret = LibPD.Process(1, new float[0], outbuffer);
    Thread.Sleep(1000);
}

LibPD.ClosePatch(patch);
LibPD.Release();

So I am sure that I am getting processed data from my patch.
Now I would like to play back this float array using CSCore. I found the ISampleSource interface in the documentation and I think it's the right one to go for this task. I tried something like this in the Read method of my interface implementation:
...

public PureDataSource()
{
    _WaveFormat = new WaveFormat(44100, 16, 2);

    int pdOpen = -1;
    pdOpen = LibPD.OpenAudio(0, 2, 44100);

    if (pdOpen != 0)
    {
        Console.WriteLine("Error opening audio... exiting");
        return;
    }

    string patch = @"..\..\..\test.pd";
    _Patch = LibPD.OpenPatch(patch);
    LibPD.ComputeAudio(true);
}

...

public int Read(float[] buffer, int offset, int count)
{
    LibPD.Process(1, new float[0], buffer);

    return count;
}

But it doesn't work out - I only get crackling sounds (guess what). I know it has something to do with the buffer size of the Read method, but where can I configure this? The Process function of LibPd works like this:
The size of each buffer must be the product of the number of channels, the      number of ticks,
and the number of samples per tick. (The number of samples per tick is the value
returned by libpd_blocksize(), i.e., 64.)

in my case that's: 2 channels (output channels), 1 tick and number of samples per tick is 64 --> 128.
EDIT:
I wrote a PureDataSource class which implements the ISampleSource interface using the information above:
class Program
{
    static void Main(string[] args)
    {
        PureDataSource pdSource = new PureDataSource();
        WasapiOut soundOut = new WasapiOut();

        soundOut.Initialize(pdSource.ToWaveSource());

        soundOut.Play();
        Thread.Sleep(5000);
        soundOut.Stop();
    }
}

class PureDataSource : ISampleSource
{
    public long Length
    {
        get
        {
            return 0;
        }
    }

    public long Position
    {
        get
        {
            return 0;
        }

        set
        {
            throw new NotImplementedException();
        }
    }
    private WaveFormat _WaveFormat;
    public WaveFormat WaveFormat
    {
        get
        {
            return _WaveFormat;
        }
    }

    private int _Patch;
    public int Patch
    {
        get { return _Patch; }
        //set { _Patch = value; }
    }

    public PureDataSource()
    {
        _WaveFormat = new WaveFormat(44100, 16, 2);

        // Initialise Pd with 2 ins and outs and a samplerate of 44100. Project dependent.
        int pdOpen = -1;
        pdOpen = LibPD.OpenAudio(0, 2, 44100);

        if (pdOpen != 0)
        {
            Console.WriteLine("Error opening audio... exiting");
            return;
        }

        string patch = @"..\..\..\test.pd";
        _Patch = LibPD.OpenPatch(patch);
        LibPD.ComputeAudio(true);
    }

    public void Dispose()
    {
        LibPD.ClosePatch(_Patch);
        LibPD.Release();
    }

    public int Read(float[] buffer, int offset, int count)
    {
        int ticks = 1;

        int pdBufferPos = 0;
        float[] pdBuffer = new float[2 * ticks * LibPD.BlockSize];
        LibPD.Process(ticks, new float[0], pdBuffer);

        for (int i = offset; i < count; i++)
        {
            if (pdBufferPos >= pdBuffer.Length)
            {
                pdBufferPos = 0;
                LibPD.Process(ticks, new float[0], pdBuffer);
            }

            buffer[i] = pdBuffer[pdBufferPos];
            pdBufferPos++;
        }

        return count;
    }
}

The Read method fills the whole buffer with the output provided by LibPD.Process (this is a float array with the size of 128 each time).
I can hear a sine wave now, but with a lot of crackling sound - it seems the samples are not processed continuously. Any ideas how to solve this?

A:
But it doesn't work out - I only get crackling sounds (guess what). I know it has something to do with the buffer size of the Read method, but where can I configure this?

You can't "configure" it. If the WasapiOut requests a certain amount of data, it is in your hands, how much data you want to return. Fill the buffer, starting at the specified offset, with the data you want. Return the number of provided samples. That's how you "configure" it.


text:
Q: Form stays invalid after submission angular 9 I am new to angular and just making a small demo application in angular 9 and coreui admin template.
I have a simple form with one textbox and one disabled button. On page load the form classes are this
<form _ngcontent-bcs-c113="" novalidate=""
class="form-horizontal ng-untouched ng-pristine ng-invalid" ng-reflect-form="[object Object]">
</form>

after entering some text in textbox my form looks like this -
<form _ngcontent-ruw-c113="" novalidate=""
class="form-horizontal ng-dirty ng-valid ng-touched" ng-reflect-form="[object Object]">
</form>

since the form is valid button enables and I can submit the form. Now there is a table below form with one edit button. On editing I fill the form with row data and can submit it again as button is enabled. On edit click my form look like this.
<form _ngcontent-ruw-c113="" novalidate=""
class="form-horizontal ng-valid ng-untouched ng-pristine" ng-reflect-form="[object Object]">
</form>

Since form is valid button is enabled and I can update data. After submitting form, my form looks like this
<form _ngcontent-ruw-c113="" novalidate=""
class="form-horizontal ng-untouched ng-pristine ng-invalid" ng-reflect-form="[object Object]">
</form>

Now my form is invalid again and button is disabled. But when I enter something in textbox to submit data again, even though validation are passed my form remains invalid and button stays disabled, like this
    <form _ngcontent-ruw-c113="" novalidate=""
     class="form-horizontal ng-invalid ng-dirty ng-touched" ng-reflect-form="[object Object]">
    </form>

In my component I reset my form after insert and update like this ---
this.rolesForm.reset(true);
 this.rolesForm.markAsPristine();

Everywhere I searched I got this as a solution and although it does reset my textbox value to empty after submission but not solving my problem. Please let me know If I need to give more information.
stackblitz link -
https://stackblitz.com/edit/create-obwnjo?file=app/app.component.html

A: The issue is with the edit button, you need to mark it as type="button". Right now as soon as you click on edit button, it call edit() method as well as create() method.
And one more thing you do not need to create a new formGroup when user clicks on edit button. Changes you need to do are the following:
<button class="btn btn-sm btn-danger" type="button" (click)="edit($event)"> Edit</button>

I have also done changes in component class file. Please find working stackblitz here: https://stackblitz.com/edit/create-2gqm2q


text:
Q: Python Assistance with Functions I would like to create a program named admission that takes as Input the student name, GPA and the admission Test Score, the application should display if the student got accepted or rejected. The program should use a function named AcceptOrReject( gpa, testScore) to control the program. Acceptance is based on the following criteria:
The student can get accepted in the following two cases:
1- if the GPA is less than 3.0, the test score has to be more than 80 to get accepted
2-if the GPA is more or equal to 3.0 then the test score has to be more than 60 to get accepted
Otherwise, the student will get Rejected.**
So I understand the objective at hand, but I'm having trouble trying to translate it to my actual code. I feel like it's a really simple assignment, but I'm not sure.
I know that we're going to need an if statement for the GPA, but how would you go about doing the test scores to determined if they failed or not? So far I have this segment and I'm not sure how to continue
    def AcceptOrReject(gpa, testscore):
    if gpa < 3.0:
        return testscore
     #I don't think I need a return testscore there.

    name=(input("Please provide your full name: "))
    testscore=float(input("What is your admissions test score? "))
    gpa=float(input("What is your GPA? "))

I'm figuring stuff out as I go, but any type of direction will be gladly appreciated. Please let me know if there's any more information that I can provide. Hopefully, I've provided as much information to you all.

A: It makes the most sense for the AcceptOrReject to return a boolean value based on the given GPA and Test score.
Since the problem states:

...the application should display if the student got accepted or rejected.

we can print "Accepted" or "Rejected" based on the return value of the function.
The solution is for AcceptOrReject to check both criteria in an if statement, and return true if that criteria is met. Otherwise, we reject at the end since both criteria weren't met.
Finally, we can print "Accepted" or "Rejected" based on the return value of AcceptOrReject.
def AcceptOrReject(gpa, testscore):
    # If GPA is less than 3.0 and testscore is more than 80 then
    if (gpa < 3.0 and testscore > 80):
        # Accept
        return True
    # Otherwise, if gpa is more or equal to 3.0 and testscore is more than 60 then
    elif (gpa >= 3.0 and testscore > 60):
        # Accept
        return True
    # Otherwise
    else:
        # Reject
        return False

testscore = float(input("What is your admissions test score? "))
gpa = float(input("What is your GPA? "))

if AcceptOrReject(gpa, testscore):
    print("Accepted")
else
    print("Rejected")

A: I thnk that would help:
def AcceptOrReject(gpa,testscore):
    if gpa<3 and testscore>80:
        print("Accepted!")

    elif gpa>3 and testscore>60:
        print("Accepted!")

    else:
        print("Rejected")

student_name=input("What is your Name? ")
student_gpa=int(input("What is your GPA? "))
testscore=int(input("What is your testscore? "))

print(AcceptOrReject(student_gpa,testscore)')

.
I did not understand the use of name that you take as input. Place it accordingly where it is needed!

A: def AcceptOrReject(student_name,gpa,testscore):
        if (gpa < 3.0 and testscore > 80):
            return True
        elif gpa >= 3.0 and testscore > 60:
            return True
        else:
            return False
if __name__ == '__main__':
        student_name=(input("Please provide your full name: "))
        testscore=float(input("What is your admissions test score? "))
        gpa=float(input("What is your GPA? "))
        print(AcceptOrReject(student_name,gpa,testscore))

A: Thank you for the assistance. Everyone's aid greatly helped with my understanding of my program. This community works like magic and most of the people I've seen are really helpful too. Thank you once again! @ghareebfathy @TheDeadGuy @Ruan


text:
Q: How to use String.index and nested function call inside an if then else block I'am actually kinda new to oCaml and trying to learn.
I'am facing a big problem on one of my functions.
It's inside a simple function (below), inside it i'am trying to check the validity of an email adress by checking if it has a '@' then a '.' and text before and after each.
(I don't wanna use Regexp, i'am really sorry if you only know how to do that with regexp but i will not take into account regexp answers ^^').
Here is the code, thank you in advance :
let checkMail mail =
if String.contains mail '@' = false
then false
else
    let tmp = String.sub mail (String.index mail '@') ((string_length mail) - (String.index mail '@')) in;;
    if tmp.length < mail.length && String.contains tmp '.' = true
    then
        let last = String.sub tmp (String.index tmp '.') ((string_length tmp.length - 1) - (String.index tmp '.')) in;;
        if last.length < tmp.length && last.length > 1
        then true
        else false
    else false

;;
Also i receive this error in the ocaml prompt: File "yolo.ml", line 8, characters 105-107:
Error: Syntax error

That correspond to the second if call, when i'am trying to find the right sub-string size by calling String.index at the end. It occurs on the '@'.
If you have any idea why, please be free to share it :) !

A: The first problem I see is this line:
let tmp = String.sub mail (String.index mail '@')
    ((string_length mail) - (String.index mail '@')) in;;

The ;; is a signal to the toplevel (OCaml REPL) that you're done typing and that it should evaluate what you've typed so far. In this code since you haven't typed a full expression yet, it will cause a syntax error.
IMHO it's really helpful to think of ;; as something you type only when talking to the toplevel. It's not part of the OCaml language per se (despite rumors to the contrary that I see all the time).

A: indeed, there is kind of a lot of wrong Ocaml syntax ;)
let checkMail mail =
if String.contains mail '@' = false
then false
else
    let tmp = String.sub mail (String.index mail '@') ((String.length mail) - (String.index mail '@')) in
if String.length tmp < String.length mail && String.contains tmp '.' = true
    then
        let last = String.sub tmp (String.index tmp '.') ((String.length tmp - 1) - (String.index tmp '.')) in
 if String.length last < String.length tmp  && String.length last > 1
        then true
        else false
    else false;;

Notably :

*

*last.length is not an Ocaml syntax, unless last is a record.

*Same for string_length : String.length.

*and ;; which appears just after in keyword at 2 locations


text:
Q: How to install root CA certificate from app on iOS and prompt user to trust? I'm using the NEVPNManager to create a personal VPN for my iOS app which is working. Now I'm trying to install a root CA certificate that can be used by all apps. I understand the user will need to trust this certificate under General -> About - Certificate Trust Settings. I'm trying to automate as much of this process as possible. The two ways I've found to attempt to do this are either:
1) Open Safari with a URL to the root certificate hosted on a website and iOS will prompt the user to install the certificate as a profile.
2) Install the certificate pragmatically within the app.
Option #1 works, but after the user installs the certificate they are not take back to the app and still have to manually go in and trust the certificate in the Certificate Trust Settings.
With option #2 if SecItemAdd is used it is only added to the keychain for the sandbox for my app and not available to other apps. The only option I have seen to make if available to other apps it to increase it's trust level as shown here, but this seems to require an old open source library from Apple that I was not able to get to build.
So, what is the best option to accomplish installing the root certificate and prompting the user to make it trusted? If it is possible through #2, any ideas how I build and then incorporate that library into my app? If I'm left with #1, what is the best way to simplify the process for the user?

A: SecTrustSettingsSetTrustSettings and related symbols are private API and your app will be rejected by Apple on submission. Even if you manage to compile this open source, it will still export the private symbols, and your app will be rejected.
Instead, you should use the openURL: API and point to a .p12 file, either locally hosted (by using an in-app web server) or remote. The .p12 file should include the certificate chain.
This will open the Settings app and ask the user to install the certificate. Once the user installs, all applications on the device will trust it.