text:
Q: gcc /g++ produces windows executables that only create output on msys2 bash, not on other terminals I have three machines running VSCode on Windows 10 set up for C++ with msys2 / mingw64 /gcc.
The Microsoft Compiler cl.exe and the Visual Studio build tools are also installed.
Via Github they share each other's code. On one Machine i have several problems with MSYS2 GCC compiler family (gcc /mingw64, gcc/ucrt64, clang64) on Windows.
Lets say i have two types of cpp files, a.cpp and b.cpp (in fact a whole bunch of .cpp files that consistently behave in exact one of the two ways)
On my "normal" PCs, they behave just fine - i can load them in my VSCode, compile and run them, and they produce some simple output on commandline.
I can also run gcc on the commandline, like
gcc a.cpp -o a.exe
and then call the resulting a.exe, giving me the correct output. Works on "normal" PCs with a.cpp as well as with b.cpp
On my "faulty" pc, just the files of type a.cpp work the same:
I can compile them from either vsccode or commandline, from a cmd terminal, powershell or from the according msys bash, and then execute them, getting the correct output.
Now there are the files of type b.cpp
They seem to compile fine like the others in VSCode - no compiler error or something like that - but they simply do not produce any output when executed.
Just an empty line, then it returns to the prompt.
It gets even more weird when i go to a cmd window:
when i try to run the compiled b.exe on the cmd prompt, a mesagebox comes up with the message
b.exe - Entry Point Not Found
The procedure entry point "_ZST28__throw_bad_array_new_lengthv"
could not be located in dll "b.exe".

[OK]

(Text is translated to english as it was on a german windows version)
As it was compiled using MigW64 environment, i try the MingW64 bash, running the compiled b.exe from there, and it works:
I do get the correct output.
It also works on the ucrt64 environment, but not on the clang64 environment.
when i go into the clang64 bash i can compile b.cpp into b-clang.exe, which works and gives the proper output.
But this b-clang exe will not work in MingW64 bash nor in UCRT64 bash nor in cmd prompt.
in the last one, in cmd, it gives me another popup error messagebox saying
The execution of the code cannot proceed because libc++.dll was not found.
Reinstalling the program may potentially fix the problem

[OK]

(Text is translated to english)
I tried a complete new install of the MSys2 Environments, but it didn'T change anything.
gcc --version on all machines (the good ones and the faultyone) gives me
gcc (Rev7, Built by MSYS2 project) 12.2.0
Copyright (C) 2022 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

here is a short sample of a simple a.cpp fle that will do well on all PCs:
#include <iostream>
using namespace std;
int main ( void ) {
    string array [] = { "es", "wie", "geht", "Dir ?" };
    string hilf = " ";
    int i = 0;
    int y = 0;
    while ( i < 3 ) {
        y= i+1;
        while ( y < 4 ) {
            if ( array [ i ] < array [ y ] ) {
                hilf = array [ i ];
                array [ i ] = array [ y ];
                array [ y ] = hilf;
            }
            y++;
        } // end while innen
        i++;
    } // end while aussen
    for ( string s : array ) cout << s << "\n ";
}

and here is a simple file iof type b.cpp that will do strange things on this one PC:
#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main() {
    vector<string> msg {"\nHello", "C++", "World", "from", "VS Code", "and the C++ extension!\n"};

    for (const string& word : msg) {
        cout << word << " ";
    }
    cout << endl;
    std::cout << "C++ language version : " << __cplusplus << std::endl;
}

A: It has been dll issues.
The simple sulution was to move the c:\msys64\mingw64\bin entry to the beginning of the path, as first entry.
I did have quite a lot in the path, so if somneone stumbles on absurd problems like the ones i described: always be aware that you might get into trouble when there are .dll files that might have same names.
In my case, i still have to watch out carefully if now some other software will not work properly because now it finds the msys2 dlls before the ones that are neede. (None found so far...)


text:
Q: Infinite For Loop - Javascript - Whats wrong? function sortArray(array) {
    var tempArray = [];
    var tempNum;
    var tempPos;
    for (var i = 0; i < array.length; i+= 1) {

        if (i = 0) {
            tempNum = parseInt(array[i]);
            tempPos = 0;
        }

        else if (parseInt(array[i]) <= tempNum) {
            tempNum = parseInt(array[i]);
            tempPos = i;
        }
    console.log(i);
    }

}

It's supposed to take an array and order it from least to greatest but didn't even get that far as the for loop becomes infinite. What did i do wrong?

A: You're setting i = 0 in the first if, which means you will never have i large enough to exit the for loop. You want to use == instead
ie:
if (i = 0) {
    tempNum = parseInt(array[i]);
    tempPos = 0;
}

should be
if (i == 0) {
    tempNum = parseInt(array[i]);
    tempPos = 0;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can you observe a snapshot of a upper level child w/o overriding the lower child rules? JSON
"users" : {
"02PdiNpmW3MMyJt3qPuRyTpHLaw2" : {
  "Coordinates" : {
    "latitude" : -24.809620667034363,
    "longitude" : 28.321706241781342
  },
  "Education" : "6", ........./// here are 10 Childs further on same level as education
  "Music"

The current rules
{
"rules": {
   ".read": false,
   ".write": false,
,    "users": {
       "$uid": {
         "Education" :{
         ".read": "$uid == auth.uid",
         ".write": "$uid == auth.uid"
}

According to my understanding, if I make users read rule for authorized users, it will override the education rule. This below is where users read rule is needed
  let artist = Database.database().reference().child("users").queryOrdered(byChild: "music").queryStarting(atValue:dateToday.timeIntervalSince1970*1000)
artist.observe(DataEventType.value,  with: {  snapshot in

Update: I had a typo "users" at the rules

A: In general indeed the rule is that if you grant somebody read (or write) access to a node, they have the same access to all data under that node. So you can't just say ".read": true on /people as that will them to read the entire node.
What you can do is specify what query is allowed in your security rules. So to allow every to read all nodes with the given music value, you could do:
"baskets": {
  ".read": "query.orderByChild == 'music' &&
            query.equalTo > 1354867200000"
}

A few things to keep in mind here:

*

*I hard-coded it here, but you will have to calculate the value for the filter in your rules somehow based on the now variable.

*You can only filter on a single value, so you can't filter on both music and uid. You may be able to merge the two values into a single property and order/filter on that. For more on this see: Query based on multiple where clauses in Firebase


text:
Q: pure.js must work with the existing page nodes?

    <meta charset="utf-8">

Test Page

The above codes don't insert data into p object.But the following works,

    <meta charset="utf-8">

Test Page

It seems to insert data, the jquery object(here,it is p)must manipulate the existing html tags? It is not reasonable like the latter,i want the first codes to insert data,but how?
Thanks, :)

A: render returns always a node. And if the template is in the DOM, it is replaced with the rendered node.
You can do this:
p = p.render(data, directives);
$(".result").after(p);

or
$(".result").after( p.render(data, directives) );


text:
Q: Window aggregation or normal aggregation? My table has 8107 rows in total.
suppose I'm finding "avg(altitude)" group by "country" on a column with Window  I get output :
avg = ap.withColumn('avg_alt',mean(ap.altitude).over(Window.partitionBy(ap.country)))

o/p: 8107 rows
same with spark.sql-
select avg(altitude) from table group by country

o/p:240 rows
Which is the correct output?
Should I use window or normal sql ?
Both are technically right but window gives for each row

A: Both outputs are correct, they only differ in the output format. As you mentioned correctly the window approach will attach the average altitude to each row of your dataframe whereas the SQL group-by approach will only have the average altitude per country.
In most cases you only want to use the grouped and aggregated results (e.g. if you  want to plot it, or display the highest/lowest countries etc.)
If you want to do further computations, the window-approach should be best (e.g. if you want to find the locations that have the maximum difference to the average altitude).


text:
Q: A quite efficient way to get large gaps. I know that the method of 'factorial' can guarantee that there are arbitrarily large gaps between consecutive primes, but I have a question about this method, consider the number $$g=p_1\cdot p_2...p_n$$
then we know that $g+2$ is not a prime because it's a multiple of two, and the same thing with 3, and so on, but near the end, we would have this $$g+p_n \text{ a multiple of }p_n$$
$$g+(p_n+1) \text{ an even number }$$
so what about $g+p_n+2$, is this the last number we would have before getting a number that we're not sure whether it's composite or not? note that $p_n,p_n+1,p_n+2$ are three consecutive numbers so one of them  is divisible by $3$, but this doesn't implies that $p_n+2$ is divisible, this thing depends whether $p_n\equiv 1\pmod 3$ or not.


text:
Q: "improve upon" another party's design - meaning? My supervisor in Japan is currently translating my CV from English into Japanese, however she has asked me to reword one sentence (in English) as to her its meaning is not what I intended it to be. The sentence reads:
"Researched into the design of a Formula 1 car simulator including both the aesthetics and hardware, focusing on improving upon the main competitor's designs."
The point in question here is the use of "improving upon". She has told me it sounds like I'm improving on the competitor's design, as opposed to bettering the design of my own company.
How can I reword this to have the intended meaning?

A: "Researched into the design of a Formula 1 car simulator including both the aesthetics and hardware, focusing on improving upon the main competitor's designs."
I am amused. The Japanese missed your designs!
Please see the following from Oxford dictionary. The word DESIGNS has dishonest  connotations as you shall see from what is given below.
Say ......" main competitor's design."
" have designs on
2
    Aim to obtain (something desired), typically in a secret and dishonest way: he suspected her of having designs on the family fortune
    More example sentences
    He emerged as sole leader of the opposition in 1263, but his position had weakened, for many magnates suspected him of having designs on the throne.
    We still have designs on taking that third spot and qualifying for Europe.
    The only way to avoid deaths on such a grand scale is to ensure someone who has designs on power are dealt with in the strictest manner at the earliest opportunity.
    Get more examples"

[2] Now let the sentence be written as follows.
"Researched into the design of a Formula 1 car simulator including both the aesthetics and hardware, focusing on ERADICATION OF SHORTFALLS IN the main competitor's designs."
Hope you are satisfied. I request the site to send me feed backs from the actual users of our service/ advice.


text:
Q: I want to put my computational stuff in secondary thread while keeping main loop in main thread I want to put my computational stuff in secondary thread while keeping main loop in main thread.
For example I want a cube rotating around OY with changing texture. Cube rotation is supported by idle function which rotates camera. But my texture computations are too complex and need some time so I cannot just put them into idle (I don't need to change the texture every time my cube rotates). Can I use foo function that does some computational stuff, creates texels buffer and sets new texture for the cube in a separate thread?
This piece of code from main function doesn't change texture of spinning cube.
glutIdleFunc(idle);
boost::thread_group tgroup;
tgroup.create_thread(boost::bind(&foo));
glutMainLoop();
tgroup.join_all();

Also are there concurrency problems with setting new texture in a different thread?

A: While it is not possible to call OpenGL operations on a given context from several threads at a time, it is possible to offload texture buffer manipulations to another thread using a mapped PBO.
In your (main) OpenGL thread allocate a pixel buffer object (PBO) with the right size for your texture's data and map it into process memory. The usage pattern in this case will be, that the PBO acts a short term intermediary for the data, i.e. upload into that buffer followed by an OpenGL access to that buffer, followed by either buffer deletion, or data change; this is the STREAM usage pattern.
GLuint pboID;
glGenBuffers(1, &pboID);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pboID);
glBufferData(GL_PIXEL_UNPACk_BUFFER, size, NULL, GL_STREAM_DRAW);
void *buffermap = glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_WRITE_ONLY);
glBindBuffer(GL_PIXEL_UNPACk_BUFFER, 0); /* the memory mapping is preserved */

/* queue that pbo for the worker thread to work upon */

You can now write values into the memory area pointed to by buffermap; every thread can do this. Once you're done with updating the buffer unmap it and use it to load data into the texture. When there's a pixel unpack buffer bound, the data parameter to glTex[Sub]Image turns into a 0-based offset parameter, designating the offset position within the buffer object from which to source the data.
if( workerthread_is_done ) {
    glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pboID);
    glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);

    /* prepare a texture object as usual */
    glTex[Sub]Image2D(…, NULL);

    glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
}

You can now either delete the PBO pboID or reuse it by supplying it with new data.

A: You cannot call OpenGL functions from multiple threads generally speaking (without using multiple render contexts, or context switching).
You have to have a bound render context to issue OpenGL commands, and window systems will restrict you to a single context-per thread. To get around this, you are going to need to use a framework that is more advanced than GLUT. The basic idea is that you need to share resources between contexts, one for uploading data into and one for actually rendering.
But the more I think about this, there is no real reason for you to do any of this. Stick to using a single thread for all GL commands, maybe load image files from disk in another thread. And signal the thread that you do your rendering in to send the data to GL using glTexImage2D (...). Your use-case is not complicated enough to warrant multi-threaded rendering, to be honest.

A: You can't multithread OpenGL calls. However, if you wanted to, you could perhaps precompute the texture calculations without using OpenGL code, and then put the results in the main thread for OpenGL to grab.


text:
Q: For i = LBound(MyAr) To UBound(MyAr) Error when only 1 entry in MyAr I am stuck with the Problem described in the headline. I am populating a TreeView from strings using and adapted Version of @Siddharth Rout 's approach (https://stackoverflow.com/a/21457669/6564572). However, if I only have one entry in the respective range  I get a "Runtime Error 13 - Type mismatch". I tried manually Setting i = 1 to UBound(MyAr) and a few other things but needless to say, it did not work. If there are 2 or more entries, it runs through smoothly.
Any help would be greatly appreciated.
Dim ws As Worksheet, wsNew As Worksheet
Dim MyAr As Variant, TempAr As Variant
Dim LRow As Long, lCol As Long
Dim i As Long, j As Long, k As Long, r As Long, Level As Long
Dim delRange As Range
Dim sFormula As String, stemp1 As String, stemp2 As String

Set ws = ThisWorkbook.Sheets("Supplier Skills")

ws.Columns(1).Sort Key1:=ws.Range("A2"), _
Order1:=xlAscending, Header:=xlNo, OrderCustom:=1, _
MatchCase:=False, Orientation:=xlTopToBottom, DataOption1:=xlSortNormal

Dim f As Range
Dim ColumnLetter As String

Set f = ws.Range("A1:ZZ1").Find(What:=UserForm1.SESNo, LookIn:=xlValues, Lookat:=xlWhole, MatchCase:=False)
ColumnLetter = Split(f.Address, "$")(1)

LRow = ws.Range(ColumnLetter & "30").End(xlUp).row
MyAr = ws.Range(ColumnLetter & "2:" & ColumnLetter & LRow).value

Set wsNew = ThisWorkbook.Worksheets("Selected TreeView")
wsNew.Range("A1:D30").Clear

r = 2: k = 3

With wsNew
    For i = LBound(MyAr) To UBound(MyAr)    '<<<<<<<<<<<<<<<--ERROR HERE--<<<<<<<<<<<
        TempAr = Split(MyAr(i, 1), "\")
        Level = UBound(TempAr) - 1
        .Range("B" & r).value = TempAr(1)
.

.   'same as in original code

.

A: If there's only 1 item in MyAr it's not set-up as an array yet, so you can try the following workaround when MyAr will reslut with only 1 element:
If IsArray(MyAr) Then
    For i = LBound(MyAr) To UBound(MyAr)
        ' do your loop things here

    Next i
Else
    ' only 1 element in array

End If

A: For everyone else wondering the same in the future, I followed Shai Rado's tip, with the following Addition:
If IsArray(MyAr) Then
    For i = LBound(MyAr) To UBound(MyAr)
        'Loops here
    Next i
Else
    Dim myElements() As String

    myElements = Split(ws.Range(ColumnLetter & "2").value, "\")

    wsNew.Range("B2") = myElements(0)
    wsNew.Range("C3") = myElements(1)
    wsNew.Range("C4") = myElements(2)

End If

I just declared the range where the string-parts need to be copied to manually after splitting the Array. It is easy since you should know exactly at what column/row number the extra-case will occur for each entry.


text:
Q: Making sense of the derivatives of $|Ax-b|^2$ in Least Square Fitting from Calculus
The partial derivatives of $|Ax|^2$ with respect to $x_1, ... , x_n$ fill the vector $2A^T Ax$.
The derivatives of $2b^T Ax$ fill the vector $2A^T b$. So the derivatives of $|Ax-b|^2$ are
zero when __________________

From the least square fitting I understand that derivatives of $|Ax-b|^2$ are
zero when $A^TAx=A^Tb$ where the idea is to minimise errors. But, how do I make sense of the first two statements in the given question:
"The partial derivatives of $|Ax|^2$ with respect to $x_1, ... , x_n$ fill the vector $2A^T Ax$" and "The derivatives of $2b^T Ax$ fill the vector $2A^T b$" ?
$$
|Ax-b|^2=(Ax-b)^T(Ax-b)=(x^TA^T-b^T)(AX-b)\\=x^TA^TAx-x^TA^Tb-b^TAx-b^Tb\\
=|Ax|^2-b^TAx-(b^TAx)^T-|b|^2
$$
Reference: 24, 4.3, Chapter 4 : Orthogonality, Introduction to Linear Algebra, Gilbert Strang

A: Basically, the problem here is to minimize the function $f = \| Ax -b\|^2$, which can be written as
$$ \min_{x} \| Ax -b\|^2 $$
The minimum value of $f$ is reached at $\hat{x}$, which is also the point for which the gradient (the first derivative) of $f$ w.r.t to $x$ equals to zero, that is:
$$ \frac{\partial \| Ax -b\|^2}{\partial x} = 0$$
For simplicity, we use the Frobenius product notation, and then we differentiate w.r.t $x$
\begin{equation}
\begin{split}
y & = Ax-b \\
dy & = Adx \\
f & = \|y\|^2 \\
  & = y:y \\
df & = dy:y + y:dy  \\
  & = 2y:dy \\
  & = 2y:Adx \\
  & = 2A^Ty:dx \\
\frac{df}{dx} & = 2A^Ty\\
& = 2A^T(Ax -b)\\
\end{split}
\end{equation}
Now, we set the derivative equal to zero
\begin{equation}
\begin{split}
\frac{df}{dx} & = 0 \\
2A^T(Ax -b) & = 0\\
2A^TAx - 2A^Tb & = 0 \\
\implies 2A^TAx & = 2A^Tb \\
\implies \hat{x} & = (A^TA)^{-1}A^Tb \\
\end{split}
\end{equation}


text:
Q: Some extra characters are being printed at the end of decrpted message #include<stdio.h>
char arr[75][75];
char message[22], key[22], emessage[22], retMessage[22];
int findRow(char);
int findColumn(char);
int findDecRow(char, int);

int main() {
  int i = 0, j, k, r, c;
  k = 47;
  for (i = 0; i < 75; i++) {
    k++;
    for (j = 0; j < 75; j++) {
      arr[i][j] = k++;
      if (k == 123)
        k = 48;
    }
  }
  printf("\nENTER MESSAGE TO ENCRYPT\n");
  gets(message);
  printf("\nENTER THE KEY TO ENCRYPT THE MESSAGE\n");
  gets(key);
  // Encryption
  for (i = 0; key[i] != NULL; i++) {
    c = findRow(key[i]);
    r = findColumn(message[i]);
    emessage[i] = arr[r][c];
  }
  emessage[i] = '\0';
  printf("\nENCRYPTED MESSAGE IS:\n\n");
  for (i = 0; emessage[i] != NULL; i++)
    printf("%c", emessage[i]);
  //decryption
  for (i = 0; key[i] != NULL; i++) {
    c = findColumn(key[i]);
    r = findDecRow(emessage[i], c);
    retMessage[i] = arr[r][0];
  }
  retMessage[i] = '\0';
  printf("\n\nMESSAGE DECRYPTED IS (ORIGINAL MESSAGE):\n\n");
  for (i = 0; retMessage[i] != NULL; i++)
    printf("%c", retMessage[i]);
  getch();
  return (0);
}

int findRow(char c) {
  int i;
  for (i = 0; i < 75; i++) {
    if (arr[0][i] == c)
      return (i);
  }
}

int findColumn(char c) {
  int i;
  for (i = 0; i < 75; i++) {
    if (arr[i][0] == c)
      return (i);
  }
}

int findDecRow(char c, int j) {
  int i;
  for (i = 0; i < 75; i++) {
    if (arr[i][j] == c)
      return (i);
  }
}

Here is my code to encrypt and decrypt a message using Vernam Cipher. every thing is working fine except the decrypt part. some extra characters are being printed at the end of decrypted message.
for example:
 Message: 571635
 key: BYUg872e78
 Cipher: G`Vm;<
 Decrypted Msg: 571635a
 Expected msg: 571635

An extra character 'a' is being printed at the end of Decrypted Msg.
How do I correct it in my code?

A: Hint: what is the return value of  findRow(c) when c is not in arr[]?
Rollover for answer

 It missing - this leads to undefined behavior (UB) with c = findRow(key[i]); and others.

Enable all warnings to save time.
You may receive something like
warning: control reaches end of non-void function [-Wreturn-type]

at the end of findRow(), findColumn(), findDecRow()

Other issues exist.

A: Your encoding and decoding is broken.
You do not properly care if the key and the message are equally long.
If your key is shorter than the message you only encode part of the message. Then you terminate the result at that position. Apart from losing part of the message this is fine so far.
If your key is longer than the message, you try to encode characters from the message that was not entered by the user.
First you will try to encode the terminating '\0' after the last message character.
This will fail because findcolumn does not return proper value and invokes undefined behaviour. You will probably store some "random" character into your encrypted message.
Similar for any further character in the message.
When decoding you try to decode those random content and it is unlikely that you will get the initial '\0' again. Instead you get "random" results from decoding.
Listening to the warnings about not returnung a value from non-void function will at least show you when you try to encode or decode some fishy value and you can look why this could happen at all.


text:
Q: MYSQL REGEXP_SUBSTR: get string or ip out of text I struggle through a complex query and need help with a REGEXP_SUBSTR command being used in the WHERE CLAUSE:
In deed this are two questions.

*

*given three possible records, I want to get the part between the brackets, but only if they match something that looks like an ip. In one case the question is simply between brackets like "[192.168.178.21]"

*other case is the text is like "sender=<some192-168-178-12.example.here>"

Case 1:
SELECT REGEXP_SUBSTR('This is a sample of [192.168.178.12] containing relevant data','(?<=[ ]\[)[^\]]#]+') AS sender
SELECT REGEXP_SUBSTR('This is a sample of [dyn-192-168-178-12.example.com] containing relevant data','(?<=[ ]\[)[^\]]#]+') AS sender
SELECT REGEXP_SUBSTR('This is a sample of [only.example com] containing relevant data','(?<=[ ]\[)[^\]]#]+') AS sender

The problem above is that escaping does not work the way I've expected.
Expected would be:
127.0.0.1
dyn.127.0.0.1.example.com
NULL

Case 2:
If I search in the field using the WHERE CLAUSE I have limited success with
WHERE ( sndtext RLIKE ' sender=\\<.*[0-9]{1,3}(.|-|_)[0-9]{1,3}(.|-|_)[0-9]{1,3}(.|-|_)[0-9]{1,3}.*\\>')

but the match is too broad, it needs to stop at the '>'
How can I achieve both solution in a WHERE CLAUSE?

A: Might not be perfekt but my solution was (less escaping):
SELECT
   REGEXP_SUBSTR(msgtext, '(?<=[[])[^]]+') AS ip,
   REGEXP_SUBSTR(msgtext,'(?<=[ ]sndtext=<)[^>]+') AS txt
FROM txtmessage m
   WHERE msgtext RLIKE ' sndtext=<.*([0-9]{1,3}[[:punct:]]){3}[0-9]{1,3}[^>]'

A: This works in the MySQL online tester if I'm understanding what you are looking for correctly.
with tbl(id, data) as (
  select 1, 'This is a sample of [192.168.178.12] containing relevant data' from dual union all
  select 2, 'This is a sample of [dyn-192-168-178-12.example.com] containing relevant data' from dual union all
  select 3, 'This is a sample of [only.example com] containing relevant data' from dual union all
  select 4, 'sender=<some192-168-178-12.example.here>' from dual
)
select id, data
from tbl
where ( data RLIKE '^.*(\\[|\\<).*[0-9]{1,3}(\\.|\\-)[0-9]{1,3}(\\.|\\-)[0-9]{1,3}(\\.|\\-)[0-9]{1,3}.*(\\]|\\>).*$');


text:
Q: Use MySQL data as the chart data for the cakephp highchart plugin I would like to use the highchart plugin in cakephp. I installed it and I can run all the demos that come with the plugin.
I would like to use it in my own controller and took one of the examples as an implementation guide.
If I have the following code in my controller it does NOT work, i.e. highchart does not display any of the input values.
    $resultStatistics = $this->Statistic->find("all", $params = array(  'fields' => 'new_students_total','recursive'    =>  -1) );
    $chartData1 = array();
    $chartData1 = Hash::extract($resultStatistics, '{n}.Statistic.new_students_total');

//  $chartData1 = array(0=>5, 1=>5, 2=>4, 3=>4);
    $this->print_r2($chartData1);

    $chartName = 'Evolution of Actual Number of Students';
    $mychart = $this->Highcharts->create($chartName, 'line');

    $this->Highcharts->setChartParams($chartName, array(
                    'renderTo'              => 'linewrapper', // div to display chart inside
                    'chartWidth'            => 600,
                    'chartHeight'           => 500,
                    'chartMarginTop'        => 60,
                    'chartMarginLeft'       => 90,
                    'xAxisCategories'       => array('Jan', 'Feb', 'Mar', 'Apr'),

                    // autostep options
                 //   'enableAutoStep'      => TRUE
                        )
                );
    $series1 = $this->Highcharts->addChartSeries();
    $series1->addName('ABC')
            ->addData($chartData1);

    $mychart->addSeries($series1);
    $this->set(compact('chartName'));

The result from the database query is a simple array with 4 integer values.
But if I uncomment the line 4, "$chartData1 = array(0=>5, 1=>5, 2=>4, 3=>4);", basically defining the values of the array manually it DOES WORK and a linechart is drawn. I use Cakephp 2.4.3  and PHP 5.6
I can't seem to figure out the difference between the "mysql" version of the array $chartData1 and the "manual defined" version of $chartData1. What am I missing?

A: After lots of checking I eventually found the problem. The Cake plug in helper expects integer (or reals) in the chartData1 array. So simple adding the following lines:
foreach ($resultStatistics as $result) {
    $chartData[] = (int) $result['Statistic']['new_students_total'];
}

at last solved my problem.
Thank anyway for your help


text:
Q: Populate Spinner with ArrayList object I have a Spinner which I want to populate from an ArrayList holding custom objects which itself gets it's data from SQLite. Each object contains multiple fields and I want to get just one of the fields and use that for the spinner entries.
I have gotten so far using this tutorial but it looks like the spinner is populating the whole object instead of just the string I want - the spinner entries look like;

*

*getSiteApproaches:com.herbert.cruisespeed.Approach@3e1725c

*getSiteApproaches:com.herbert.cruisespeed.Approach@6fde965

*getSiteApproaches:com.herbert.cruisespeed.Approach@57563a

In my activity I have;
db = new SQLiteHelper(getApplicationContext());
approachList = db.getSiteApproaches(currentsiteid);
ArrayAdapter<Approach> sAdapter = new ArrayAdapter<Approach>(this, android.R.layout.simple_spinner_item, approachList);
toolbarSpinner.setAdapter(sAdapter);

And the Approach class:
package com.cruisespeed.herbert.cruisespeed;

public class Approach {

    int _id;
    int _siteid;
    String _approachname;
    int _speedlimit;
    int _distance;
    String _createddatetime;

    // Constructors

    public Approach(){

    }

    public Approach(int id, int siteid, String approachname, String createddatetime) {
        this._id = id;
        this._siteid = siteid;
        this._approachname = approachname;
        this._createddatetime = createddatetime;
    }

    public Approach(int siteid, String approachname, String createddatetime) {
        this._siteid = siteid;
        this._approachname = approachname;
        this._createddatetime = createddatetime;
    }

    // Getters

    public int getID(){
        return this._id;
    }

    public int getSiteID(){
        return this._siteid;
    }

    public String getApproachName(){
        return this._approachname;
    }

    public int getSpeedLimit(){
        return this._speedlimit;
    }

    public int getDistance(){
        return this._distance;
    }

    public String getCreatedDateTime(){
        return this._createddatetime;
    }

    // Setters

    public void setID(int id){
        this._id = id;
    }

    public void setSiteID(int siteid){
        this._siteid = siteid;
    }

    public void setApproachName(String approachname){
        this._approachname = approachname;
    }

    public void setSpeedLimit(int speedlimit){
        this._speedlimit = speedlimit;
    }

    public void setDistance(int distance){
        this._distance = distance;
    }

    public void setCreatedDateTime(String createddatetime){
        this._createddatetime = createddatetime;
    }
}

And from my SQLiteHelper class
// Fetch all approaches with a specific SiteID
public ArrayList<Approach> getSiteApproaches(int siteid){
    ArrayList<Approach> approaches = new ArrayList<Approach>();
    SQLiteDatabase database = this.getReadableDatabase();

    String selectQuery = "SELECT * FROM " + TABLE_APPROACHES + " WHERE " + KEY_SITE_ID + " = " + siteid;

    Log.e(LOG, selectQuery);

    Cursor c = database.rawQuery(selectQuery, null);

    if (c.moveToFirst()){
    do {
        Approach ap = new Approach();
        ap.setID(c.getInt(c.getColumnIndex(KEY_APPROACH_ID)));
        ap.setSiteID(c.getInt(c.getColumnIndex(KEY_SITE_ID)));
        ap.setApproachName(c.getString(c.getColumnIndex(KEY_APPROACH_NAME)));
        ap.setSpeedLimit(c.getInt(c.getColumnIndex(KEY_APPROACH_SPEED_LIMIT)));
        ap.setDistance(c.getInt(c.getColumnIndex(KEY_APPROACH_DISTANCE)));
        ap.setCreatedDateTime(c.getString(c.getColumnIndex(KEY_CREATED_AT)));

        approaches.add(ap);
        Log.e(LOG, "getSiteApproaches:" + String.valueOf(ap)); // todo debugging spinner
    } while (c.moveToNext());
}
    c.close();
return approaches;
}

I have checked SO but not found any solutions to my specific issue - the spinner is populating but it looks like its holding the whole object, I just want to display the approachname field.

A: You should override toString() in Approach class
 @Override
 public String toString() {
    return _approachname.toString();
}

A: you can either go for a custom Adapter, overriding getView() which will give you more flexibility on the how the info will be laid down, or you could simply override toString() in your model class, and return the info you want to show. In fact, what you are seeing atm, is the result of default implementation of toString() of the class Object.


text:
Q: How can I remove all my docker images? Sometimes I just want to clear everything out of docker, and start with a clean slate. Is there a systematic way to just remove all my Docker containers & images?
Containers
$ docker ps -a | head
CONTAINER ID        IMAGE                COMMAND                CREATED             STATUS                     PORTS               NAMES
7b055e9e5f1f        fedora:latest        /bin/sh                6 days ago          Exited (0) 6 days ago                          ecstatic_colden
40da968258eb        fedora:latest        /bin/sh                6 days ago          Exited (127) 6 days ago                        naughty_thompson
5be4581afad6        fedora:latest        /bin/bash              6 days ago          Exited (0) 6 days ago                          kickass_wright
4d6c33d4be6d        fedora:latest        /bin/bash              6 days ago          Exited (0) 6 days ago                          furious_fermat
db7a29bdbc2d        fedora:latest        /bin/bash              6 days ago          Exited (0) 6 days ago                          mad_hawking
e6b7365690ce        fedora:latest        /bin/bash              6 days ago          Exited (0) 6 days ago                          trusting_ardinghelli
15655c21fcd3        8018e08e6a58         /bin/sh -c 'apt-get    3 weeks ago         Exited (100) 3 weeks ago                       drunk_bardeen
607547aabbca        f02ed0c206d5         /bin/sh -c 'apt-get    3 weeks ago         Exited (100) 3 weeks ago                       cocky_franklin
f031f28bd29a        f02ed0c206d5         /bin/sh -c 'apt-get    3 weeks ago         Exited (100) 3 weeks ago                       stoic_mcclintock

Images
$ docker images -a | head
REPOSITORY          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
docker              master              266a5746d179        2 weeks ago         1.528 GB
<none>              <none>              c1f6a4b1345c        3 weeks ago         1.526 GB
<none>              <none>              6558c36ecb3f        3 weeks ago         1.526 GB
<none>              <none>              b1b7c7a6b6a7        3 weeks ago         1.24 GB
<none>              <none>              0bf9d6bf97e9        3 weeks ago         1.182 GB
<none>              <none>              48c444f1d2e7        3 weeks ago         1.182 GB
<none>              <none>              5c5c172a0038        3 weeks ago         1.182 GB
<none>              <none>              de5e09bb86c1        3 weeks ago         1.182 GB
<none>              <none>              785aaf265f18        3 weeks ago         1.182 GB

A: The simplest way to do this is to use do the following 3 steps:

*

*stop all the containers

*remove all the containers

*remove all the images

To achieve this you can make use of the docker ps and docker images commands abilities to just return you a list of IDs via there -q or --quiet switch. This gets rid of all the cruft that both these commands typically returns and just gives you a nice list, like so:
Default output
$ docker ps -a
CONTAINER ID        IMAGE                COMMAND                CREATED             STATUS                     PORTS               NAMES
7b055e9e5f1f        fedora:latest        /bin/sh                6 days ago          Exited (0) 6 days ago                          ecstatic_colden
40da968258eb        fedora:latest        /bin/sh                6 days ago          Exited (127) 6 days ago                        naughty_thompson

Quiet output
$ docker ps -aq
7b055e9e5f1f
40da968258eb
5be4581afad6
4d6c33d4be6d

NOTE: Both docker images and docker ps also make use of the -a or --all switch which shows you all the IDs.
You can utilize this output to construct Docker commands that make use of output from other Docker commands like so:
$ docker rm $(docker ps -qa)

Cleaning house
So to accomplish your task of removing everything you'd use the following commands:
$ docker stop $(docker ps -qa)
$ docker rm $(docker ps -qa)
$ docker rmi $(docker images -qa)


text:
Q: Trend line or line of best fit in pgfplots Is there an "out of the box" way to automatically draw the trend line in pgfplots?
Below follows a basic illustration of a scatter graph with a line of best fit:

A: Can be achieved using
/pgfplots/table/create col/linear regression={⟨key-value-config⟩}
documented in Section 4.22 of the pgfplots manual.

Here's a slightly adapted version of the example from the manual. If you want to plot data directly from a file, replace the \datatable in the \addplot command with the file name.

\documentclass{standalone}

\usepackage{pgfplots, pgfplotstable}

\pgfplotstableread{
X Y
1 1
2 4
3 9
4 16
5 25
6 36
}\datatable

\begin{document}
\begin{tikzpicture}
\begin{axis}[legend pos=outer north east]
\addplot [only marks, mark = *] table {\datatable};
\addplot [thick, red] table[
    y={create col/linear regression={y=Y}}
] % compute a linear regression from the input table
{\datatable};
\addlegendentry{$y(x)$}
\addlegendentry{%
$\pgfmathprintnumber{\pgfplotstableregressiona} \cdot x
\pgfmathprintnumber[print sign]{\pgfplotstableregressionb}$}
\end{axis}
\end{tikzpicture}
\end{document}


text:
Q: Freetextbox and validating requests I am using freetextbox and have added  to the web.config of my app but I still get the following error when submitting text with html:
A potentially dangerous Request.Form value was detected from the client (ctl00_MainContent_FreeTextBox1="

I know this is not the preferred way to set up an app but why am I getting these errors even though I have turned off request validation in my app?

A: The short answer is you shouldn't be getting such an error if you turned off Request Validation.
Did you do one of these two things correctly?

*

*Disable on the page by inserting this at the top of the ASPX

*Add the below section to your web.config.
<configuration>
<system.web>
<pages validateRequest="false" />
</system.web>
</configuration>
If that doesn't work then check the machine.config and see if the pages validaterequest value is set to true in there as that would override the web.config.

A: I had the same problem, and it was actually my fault. Maybe you have done the same mistake: I placed <httpRuntime requestValidationMode="2.0"/> inside
<configuration><location><system.web> instead of <configuration><system.web>.

A: Ensure that you haven't enabled request validation for this page. I would keep validation running for your site - but turn it off on pages where you need this control.
Be sure to sanitize anything that gets posted and be prudent about security.


text:
Q: C++: Using getline to input from a text file either skips the first line or messes up the rest I'm trying to read in from a specially formatted text file to search for specific names, numbers, etc. In this case I want to read the first number, then get the name, then move on to the next line. My problem seems to be with while loop condition for reading through the file line by line. Here is a sample of the txt file format:
5-Jon-4-Vegetable Pot Pie-398-22-31-Tue May 07 15:30:22
8-Robb-9-Pesto Pasta Salad-143-27-22-Tue May 07 15:30:28
1-Ned-4-Vegetable Pot Pie-398-22-31-Tue May 07 15:30:33

I'll show you two solutions I've tried, one that skips the first line in the file and one that doesn't take in the very last line. I've tried the typical while(!iFile.eof()) as a last ditch effort but got nothing.
    transactionLog.clear();
    transactionLog.seekg(0, std::ios::beg);

    std::string currentName, line, tempString1, tempString2;
    int restNum, mealNum;
    bool nameFound = false;
    int mealCount[NUMMEALS];

    std::ifstream in("patronlog.txt");

    while(getline(in, line))
    {
        getline(in, tempString1, '-');
        getline(in, currentName, '-');

        if(currentName == targetName)
        {
            if(getline(in, tempString2, '-'))
            {
                mealNum = std::stoi(tempString2);
                mealCount[mealNum - 1] += 1;
                nameFound = true;
            }
        }

I believe I understand what's going in this one. The "getline(in, line)" is taking in the first line entirely, and since I'm not using it, it's essentially being skipped. At the very least, it's taking in the first number, followed by the name, and then doing the operations correctly. The following is the modification to the code that I thought would fix this.
    while(getline(in, tempString1, '-'))
    {
        getline(in, currentName, '-');

        // same code past here
    }

I figured changing the while loop condition to the actual getline of the first item in the text file would work, but now when I look at it through the debugger, on the second loop it sets tempString1 to "Vegetable Pot Pie" rather than the next name on the next line. Ironically though this one does fine on line #1, but not for the rest of the list. Overall I feel like this has gotten me farther from my intended behavior than before.

A: You need to parse the contents of lines after they are read. You can use a std::istringstream to help you with that.
while(getline(in, line))
{
    // At this point, the varible line contains the entire line.
    // Use a std::istringstream to parse its contents.

    std::istringstream istr(line);

    getline(istr, tempString1, '-');  // Use istr, not in.
    getline(istr, currentName, '-');  //    ditto

    ...
}


text:
Q: Clang error while compiling Rcpp package in Big Sur I'm trying to compile an Rcpp package and am currently running Big Sur (mistake, apparently). I've installed and updated Xcode, as well as CLANG as instructed here. However, I get the following error when attempting to build:
ld: warning: directory not found for option '-L/usr/local/gfortran/lib/gcc/x86_64-apple-darwin18/8.2.0'
ld: library not found for -lquadmath
clang-4.0: error: linker command failed with exit code 1 (use -v to see invocation)

This is strange for many reasons; first of all, my gfortran directory is L/usr/local/gfortran/lib/gcc/aarch64-apple-darwin20.2.0/11.0.0.
My ~/.R/Makevars file is setup as such:
CC=/usr/local/clang4/bin/clang
CXX=/usr/local/clang4/bin/clang++
CXX1X=/usr/local/clang4/bin/clang++
CXX98=/usr/local/clang4/bin/clang++
CXX11=/usr/local/clang4/bin/clang++
CXX14=/usr/local/clang4/bin/clang++
CXX17=/usr/local/clang4/bin/clang++
LDFLAGS=-L/usr/local/clang4/lib

A: Few quick notes I'm leaving as an answer (sorta) to the compilation issue with ARM.

*

*the post linked to is a bit old (latest update 2017 / R 3.4.0) and was geared toward incorporating OpenMP into old versions of R. I'll make sure to update it later today to emphasize this.

*the focus was on using Intel-based macs since the ARM architecture (e.g. M1 chip) wasn't announced.

With that being said, our attention now turns to the elephant in the room: ARM and Big Sur. Presently, there is no native/ARM-compiled versions of R and gfortran available outside of developer nightlies on the macOS R developer portal.
The best approach here is to run R and gfortran through Rosetta 2 (e.g. use a non-native version) until R 4.1.0 is released this upcoming April.
For more in-depth analysis, see: Will R Work on Apple Silicon?

A: There is a newer version of recommendations regarding gfortran and clang from The Coatless Professor here:
R COMPILER TOOLS FOR RCPP ON MACOS
One of the updates is that they no longer recommend using ~/.R/Makevars.
Note that this only addresses through Catalina (10.15), though it is for R version 4.y.z (the one linked was for R 3). Theoretically, it may also work for Big Sur. I haven't found a solution yet, but I'm running Big Sur on an Intel Mac (not M1/ARM).
Apologies for answering rather than commenting, but I can't comment yet (too new).


text:
Q: android.view.InflateException: Binary XML file line #16: Error inflating class android.support.design.widget.NavigationView Não consigo revolver erro:
android.view.InflateException: Binary XML file line #16: Error inflating class android.support.design.widget.NavigationView

<include
    layout="@layout/app_bar_options_user"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<android.support.design.widget.NavigationView (Erro Nessa linha)
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_options_user2"
    app:menu="@menu/activity_options_user_drawer" />


text:
Q: Python output to command prompt (and at all) stopped working Summary
I used to get output from all the print statements, and my Python script would run as expected, now I run it normally, if line feeds the command prompt, wait about 3-5 seconds, and then display a new line with the command prompt. This happened as I was making additions to the test suite and data sets I was given.
Details
I'm making a Python 3.7 machine learning test suite on a Windows machine for my boss and was making pretty great headway when the output of my python script stopped working. I've searched the inter-webs and have not found situations like mine with any solutions, most problems arise from people not writing their scripts properly.
When I run the script in command prompt, I run it with "py myscript.py {args}" or "python myscript.py {args}". I have also tried with a -3 and -3.7 Python option.
My debugging of this problem is as follows:
- Added a print statement at the beginning of main: no print output
- Changed the instantiation name of a variable that is required later while keeping the use of that variable the same: no error output
- Uninstalled argparse (which is used in the script) using pip uninstall: no error output
- Created a separate Python script that only has a single print statement in main: no output
- Running python –V: outputs "Python 3.7.2"
- Changing or completely removing the #! line at the top of the file: no difference
I only have Python 3.7 installed on the computer I am working on. I also installed Visual Studio Code(VSC) and the respective Python module for VSC, and the Python script runs perfectly there when run under VSC's run with (or without) debugging. I tried to run it through VCS's terminals, and the output is missing there as well.
The included code is a small subset of the program that should answer most of the immediate questions. Am I just missing something?
#!python3.7
.
. (import statements)
.
def main():
  print ('Python Output Test\n')
  parser = argparse.ArgumentParser()
  parser.add_argument('-s', '--seed', type=int, default=42, help='Set the seed for the algorithms.')
  parser.add_argument('-q', '--quiet', default=False, action="store_true", help='Use when lots of output is not necessary.')
  parser.add_argument('-r', '--run', type=int, default=0, choices=[0, 1, 2, 3, 4, 5, 6], help='Use to determine which file to use.')
  args = parser.parse_args()

  seed = args.seed
  quiet = args.quiet
  runType = args.run

  print ('MachineLearning.py -s ', seed, ' -r ', runType)
.
. (lots of code that used to work)
.
return 0

if __name__ is "__main__":
  main()

The above code should output those print statements to the command prompt, or maybe errors should be reported if there are errors, but I'm getting nothing.


text:
Q: Strange behaviour of isinstance function I have a class named Factor in the module Factor.py (https://github.com/pgmpy/pgmpy/blob/dev/pgmpy/factors/Factor.py) and also have function named factor_product in Factor.py as:
def factor_product(*args):
    if not all(isinstance(phi, Factor) for phi in args):
            raise TypeError("Input parameters must be factors")
    return functools.reduce(lambda phi1, phi2: _bivar_factor_operation(phi1, phi2,
                                                            operation='M'), args)

Now if I even pass instances of Factor to the function, it still throws TypeError. A few lines from the debugger with breakpoint set just above the if statement:
(Pdb) args
args = (<pgmpy.factors.Factor.Factor object at 0x7fed0faf76a0>, <pgmpy.factors.Factor.Factor object at 0x7fed0faf7da0>)

(Pdb) isinstance(args[0], Factor)
False

(Pdb) type(args[0])
<class 'pgmpy.factors.Factor.Factor'>

(Pdb) Factor
<class 'pgmpy.factors.Factor.Factor'>

Any idea why this is happening ?

A: reload is a good way to end up with two copies of the same class from the same module: one from before the reload (if any instances of that class are still lurking about) and one from after.
Most likely you had objects of the new type, but Factor referred to the old type, since it was imported some time ago.  So it's completely true that your objects aren't instances of Factor...  not that Factor, anyway.
Never trust reload.  :)

A: As  isinstance Return true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof , it just return true if you pass the instance of your class to it not the class itself , see the following example :
>>> class A :
...  pass
...
>>> isinstance(A,A)
False
>>> isinstance(A(),A)
True
>>> z=A()
>>> isinstance(z,A)
True


text:
Q: Multiclass Classification Evaluator in PySpark from pyspark.ml.classification import MultilayerPerceptronClassifier
inputneurons = len(pipe_df.columns)
nn = MultilayerPerceptronClassifier(layers = [inputneurons,20,2])
nn_model = nn.fit(train_data)
results = nn_model.transform(test_data)
from pyspark.ml.evaluation import MulticlassClassificationEvaluator
evaluator = MulticlassClassificationEvaluator()
mlp_accuracy = evaluator.evaluate(results)

and when run it, shows errors ---------------------------------------------------------------------------
Py4JJavaError                             Traceback (most recent call last)
 in ()
     23 evaluator = MulticlassClassificationEvaluator()
     24
---> 25 mlp_accuracy = evaluator.evaluate(results)
     26
     27
and I tried BinaryClassificationEvaluator but it does't work as well..
Is anyone know whats wrong here? I am new to PySpark...


text:
Q: How to select the cell when case is true First off, just starting trying to learn Excel and VBA yesterday....so bear in mind.
Private Sub CommandButton2_Click()

For a = 1 To myLastRow
    Select Case ActiveWorkbook.Sheets("Sheet2").Cells(a, 2).Value
        Case Is = myOrderNumber
            ActiveWorkbook.Sheets("Sheet2").Cells(a, 2).Active
        Case False: MsgBox "False"
    End Select
Next a
End Sub

I want to know which cell or the row of the cell that matches my variable. This does not do what I want.......
Thanks guys

A: I appreciate you are learning code. But beyond getting the range syntax correct two better methods (efficiency wise) are shown below

*

*Array

recut
Private Sub CommandButton2_Click()
Dim myLastRow As Long
Dim myOrderNumber As Long
Dim lngCnt As Long
Dim ws As Worksheet
Dim X

myOrderNumber = 2

Set ws = ActiveWorkbook.Sheets("Sheet2")

X = ws.Range(ws.[b1], ws.[b10])
For lngCnt = 1 To UBound(X)
If X(lngCnt, 1) = myOrderNumber Then MsgBox "True " & lngCnt
Next

End Sub

*Evaluate

From Is it possible to fill an array with row numbers which match a certain criteria without looping?
myOrderNumber = 2
MsgBox Join(Filter(Application.Transpose(Application.Evaluate("=IF(B1:B10=" & myOrderNumber & ",ROW(B1:B10),""x"")")), "x", False), ",")

A: Try this
Private Sub CommandButton2_Click()
Dim myLastRow As Long, a As Long, myOrderNumber As Long

myLastRow = 10
For a = 1 To myLastRow
    With ActiveWorkbook.Sheets("Sheet2")
        If .Cells(a, 2).Value = myOrderNumber Then
            MsgBox "True " & .Cells(a, 2).Row
        Else
            Msgbox "False"
        End If
    End With
Next a
End Sub

A: For a = 1 To myLastRow
With ActiveWorkbook.Sheets("Sheet2")
    If .Cells(a, 2).Value = myOrderNumber Then
        myRow = .Cells(a, 2).Row
        MsgBox "True " & myRow
    Else
        'MsgBox "False "
    End If
End With

Next a


text:
Q: Swift 3: index out of range error I'm new to iOS. Doing project by watching tutorial which is written using Swift 2. It works when author runs app but not in my case.
ViewController:
var books = [[String: AnyObject]]()

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.dataSource = self
    searchBar.delegate = self
}

And the extension
extension ViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "BookCell", for: indexPath)

        // error on this line
        if let volumeInfo = self.books[indexPath.row]["volumeInfo"] as? [String: AnyObject] {
            cell.textLabel?.text = volumeInfo["title"] as? String
            cell.detailTextLabel?.text = volumeInfo["subtitle"] as? String
        }

        return cell
    }
}

The console output:

Please, help me to identify what is the cause.

A: I'm assuming a lot about your project but if you only have one section in your tableView, which is the default, you shouldn't use indexPath.section for your books dictionary. You should use indexPath.row as seen below
Change -
if let volumeInfo = self.books[indexPath.section]["volumeInfo"] as? [String: AnyObject]

To -
if let volumeInfo = self.books[indexPath.row]["volumeInfo"] as? [String: AnyObject] {

A: You have to return books.count from numberOfRowsInSection, never "hard-code" that value if it's related to the data source array.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return books.count
}

PS: In Swift 3 you should use [String:Any] rather than [String:AnyObject]


text:
Q: Should I dispose of manually a Dictionary data structure after I am done using it? Is it worth the effort to try and actively dispose of the Dictionary in this code, or just leave it to managed garbage collection?
private void LogReprocessTsk(List<ReprocessTsk> reprocessTsks)
{
    foreach (ReprocessTsk reprocessTsk in reprocessTsks)
    {
        Dictionary<string, string> logMessage = new Dictionary<string, string>
        {
            { "Message", "insert into REPROCESS_TSK - parentId changed" },
            { "TSKLOC", reprocessTsk.TSKLOC },
            { "CRS", reprocessTsk.CRS.ToString() },
            { "PROCESSED", reprocessTsk.PROCESSED.ToString() },
            { "OldParentId", reprocessTsk.OldParentId },
            { "NewParentId", reprocessTsk.NewParentId }
        };

        _logger.LogInformation(JsonConvert.SerializeObject(logMessage));
    }
}

A: The garbage collector does its job very well and there is no reason to force a premature garbage collection. The dictionary gets out of the scope of the loop anyway at each iteration and becomes automatically a candidate for garbage collection.
You can minimize the number of object creations if you declare only one dictionary before the loop and clear it after use.
var logMessage = new Dictionary<string, string>();
foreach (ReprocessTsk reprocessTsk in reprocessTsks) {
    logMessage.Add("Message", "insert into REPROCESS_TSK - parentId changed");
    logMessage.Add("TSKLOC", reprocessTsk.TSKLOC);
    logMessage.Add("CRS", reprocessTsk.CRS.ToString());
    logMessage.Add("PROCESSED", reprocessTsk.PROCESSED.ToString());
    logMessage.Add("OldParentId", reprocessTsk.OldParentId);
    logMessage.Add("NewParentId", reprocessTsk.NewParentId);

    _logger.LogInformation(JsonConvert.SerializeObject(logMessage));
    logMessage.Clear();
}

Since you are using the same keys at each foreach iteration, yet another possibility is to re-assign the new values to the same dictionary keys.
var logMessage = new Dictionary<string, string>();
foreach (ReprocessTsk reprocessTsk in reprocessTsks) {
    logMessage["Message"] = "insert into REPROCESS_TSK - parentId changed";
    logMessage["TSKLOC"] = reprocessTsk.TSKLOC;
    logMessage["CRS"] = reprocessTsk.CRS.ToString();
    logMessage["PROCESSED"] = reprocessTsk.PROCESSED.ToString();
    logMessage["OldParentId"] = reprocessTsk.OldParentId;
    logMessage["NewParentId"] = reprocessTsk.NewParentId;

    _logger.LogInformation(JsonConvert.SerializeObject(logMessage));
}

Note that the dictionary indexer creates non existing entries and replaces existing ones. See: the remarks section for the Dictionary<TKey,TValue>.Item[TKey] Property.


text:
Q: ASP.NET MVC 2 C#: Short hand IF within loop? I'm trying to find out how I can put a condition within my loop as I print out list items...

   <% foreach (var filter in Model.Filter)
     { %>

     <li <% filter.TagChecked == 1 ? //yes : //no %>><%: filter.TagLabel %>

   <% } %>

I'm trying to see if a filter is checked... if yes, then I need to write the class and also add the image. If not, then just write a normal li

A:

<% foreach (var filter in Model.Filter)
 { %>

 <li <%: filter.TagChecked == 1 ? "class=\"some-class\"" : "" %>><%: filter.TagLabel %>

<% } %>

A: Just return the needed string:
<%: filter.TagChecked == 1 ? " class=\"myclass\"" : string.Empty %>


text:
Q: How to use react-native-modal-datetime-picker to take multiple timings and display it I have started learning react-native and I am using the react-native-modal-datetime-picker first time. I tried to take multiple timings from timePicker but I am not getting how to do it. I want to take 5 different timings for my app also I have to display it. following is my code for you to understand my requirement.
    _showDateTimePicker = () => {
            this.setState({ isDateTimePickerVisible: true })
        }

     _hideDateTimePicker = () => this.setState({ isDateTimePickerVisible: false });

 _handleDatePicked = (time) => {
        const selected1 = time.getHours() + ':' + time.getMinutes();
        this.setState({ value1: selected1 })
        this._hideDateTimePicker();
    };

render() {
        return (
            <ScrollView style={styles.container}>

                <View style={styles.dataStyle}>
                    <Text style={styles.textStyle}>valu1 </Text>
                    <Text style={styles.textStyle2}> {this.state.selected1} </Text>
                    <TouchableOpacity style={styles.iconStyle}>
                        <Icon name='edit' color='#212B51' size={25} onPress={this.renderDateTimeModals} />
                    </TouchableOpacity>
                </View>
                <View style={styles.dataStyle}>
                    <Text style={styles.textStyle}>Value2 </Text>
                    <Text style={styles.textStyle2}> {this.state.selected2} </Text>
                    <TouchableOpacity style={styles.iconStyle}>
                        <Icon name='edit' color='#212B51' size={25} onPress={this._showDateTimePicker} />
                    </TouchableOpacity>
                </View>
                <View style={styles.dataStyle}>
                    <Text style={styles.textStyle}>Value3 </Text>
                    <Text style={styles.textStyle2}> {this.state.selected3} </Text>
                    <TouchableOpacity style={styles.iconStyle}>
                        <Icon name='edit' color='#212B51' size={25} onPress={this._showDateTimePicker} />
                    </TouchableOpacity>
                </View>

                <TouchableOpacity
                    style={[styles.buttonContainer, styles.loginButton]}>
                    <Text style={styles.loginText}> Submit </Text>
                </TouchableOpacity>

                 <DateTimePicker
                    isVisible={this.state.isDateTimePickerVisible}
                    onConfirm={this._handleDatePicked}
                    onCancel={this._hideDateTimePicker}
                    mode={'time'}
                    is24Hour={false}
                />
            </ScrollView>
        );
    }

I want 5 different value picked and want to display them all. Please help Thanks in advance


text:
Q: Python3 print statement doesn't work as expected I am using Python 3.2.2
>>> s = 'hhh'
>>> print s
SyntaxError: invalid syntax
>>> print(s)
hhh
>>> print 2*2
SyntaxError: invalid syntax
>>> print(2*2)
4

Why do I have to use print("...") to print something?  If I dno't it complains with 'SyntaxError'.

A: As of python 3.0, print is a function. See:
http://docs.python.org/release/3.0.1/whatsnew/3.0.html#print-is-a-function


text:
Q: Using Events over the LAN with SuperClassic? I have an application that uses Events from the server to do some processing. Everything worked fine while the firebird superserver was running on the same machine, but now, I had to move firebird on a multicore machine so I used SuperClassic. The application that waits for the events runs on another machine on the same LAN. Is there any way to use the events in this way?
I'm using Firebird 2.5, 64bits, SuperClassic.
TIA

A: Events works the same way in Superserver x SuperClassic x Classic. I recommend you to edit firebird.conf and uncomment the line with the parameter RemoteAuxPort, and set it to a port that you are sure is not being used by another application, and is open in your firewall.
PS: You also should know that, unfortunately, the events implementation in FB is weak, so you cannot trust it 100%.


text:
Q: How To Calculate Running balance using SQL If I have total qty = 100. and it has been shipped in 4 phases line 40, 10, 25, 25 that equals to 100. when I am running this query:
Someone Helped me with this query. I want the same runnable for DB2.
SET totalQty = -1;
SELECT
  IF(@totalQty<0, pl.quantity, @totalQty) AS totalQty,
  pr.invoiceqty,
  @totalQty:=(@totalQty - pr.invoiceqty) AS balance
FROM
  purchaseorderline pl, replenishmentrequisition pr

I am getting result like this :
--total qty--   --invoice qty-- --balance qty--
100 40  60
100 10  90
100 25  75
100 25  70

The result I want :
--total qty--   --invoice qty-- --balance qty--
100 40  60
60  10  50
50  25  25
25  25  00

A: It would be good enough, if you provided some sample data in a table form and not just what you get on it.
WITH MYTAB (PHASE_ID, QTY) AS
(
-- Your initial data as the result of
-- your base SELECT statement
VALUES
  (1, 40)
, (2, 10)
, (3, 25)
, (4, 25)
)
SELECT
  QTY + QTY_TOT - QTY_RTOT  AS "total qty"
, QTY                       AS "invoice qty"
, QTY_TOT - QTY_RTOT        AS "balance qty"
FROM
(
  SELECT
    PHASE_ID
  , QTY
  -- Running total sum
  , SUM (QTY) OVER (ORDER BY PHASE_ID)  AS QTY_RTOT
  -- Total sum
  , SUM (QTY) OVER ()                   AS QTY_TOT
  FROM MYTAB
)
ORDER BY PHASE_ID

total qty
invoice qty
balance qty

100
40
60

60
10
50

50
25
25

25
25
0

A: A variation of Marks answer is:
WITH MYTAB (PHASE_ID, QTY) AS
(
    -- Your initial data as the result of
    -- your base SELECT statement
    VALUES (1, 40)
         , (2, 10)
         , (3, 25)
         , (4, 25)
)
SELECT QTY_TOT  AS "total qty"
     , QTY      AS "invoice qty"
     , coalesce(lead(QTY_TOT) over (order by phase_id),0) AS "balance qty"
FROM
( SELECT PHASE_ID
       , QTY
       -- Running total sum
       , SUM (QTY) OVER (ORDER BY PHASE_ID desc)  AS qty_tot
  FROM MYTAB
)
ORDER BY PHASE_ID

It uses lead at the outer level instead of sum over the entire window at the inner level
Fiddle


text:
Q: Read Large XML String from TSQL FOR XML Statement in C# .NET Have a SQL command with FOR XML that returns a single long XML as SqlString.  My problem is reading the long XML string into .NET C#.
The following only reads the first 2033 characters
    SqlDataReader rdr = command.ExecuteReader();
    if (rdr.HasRows)
    {
        rdr.Read();
        Debug.WriteLine(rdr[0].ToString().Length.ToString());
    }

I have also tried command.ExecuteScalar and rdr.GetString and still only get the first 2033 characters.   I have changed the sort and it still truncates at 2033 so it is not likely caused by a bad character.   Tried rdr.GetSqlXml and get an error message cannot cast SqlString to SqlCachedBuffer.
If I limit the SQL to return less than 2033 character I do get the complete valid XML.  So I don't think it is an XML parsing issue rather just a truncation.  I don't need any XML parsing - it is valid XML from the TSQL statement that I need as string.
How can I read the full XML (as text)?
The TSQL works.
    select top 10 docSVsys.sID, docSVsys.docID
      , (select top 10 value + '; '
          from docMVtext with (nolock) where docMVtext.sID = docSVsys.sID
               and docMVtext.fieldID = '113'
          order by value FOR XML PATH('') ) as [To]
      from docSVsys with (nolock)
      order by docSVsys.sID
      for xml auto, root('documents')

The FOR XML PATH provides what I need and fast.  I tried a regular query and then generating the XML using Xdocument but performance is horrible with even more than 100 lines as it needs to search on sID to add the To.  I guess I could write the concatenation as a SQL function to avoid the FOR XML AUTO but that query with the FOR XML is fast and provides the exact results I need.  It is just how to retrieve the result?

A: This is a known issue, see: http://support.microsoft.com/kb/310378
Use ExecuteXmlReader instead. The underlying cause is that SQL breaks up the returned XML, so you need to read the reply differently. I've had the same issue in ADO using VBScript too.

A: Wrapping the whole result in a select seems to work for me i.e.:
select (select top 10 docSVsys.sID, docSVsys.docID
  , (select top 10 value + '; '
      from docMVtext with (nolock) where docMVtext.sID = docSVsys.sID
           and docMVtext.fieldID = '113'
      order by value FOR XML PATH('') ) as [To]
  from docSVsys with (nolock)
  order by docSVsys.sID
  for xml auto, root('documents'))


text:
Q: SSN Validation in MVC2 I have a business requirement where in i need to display SSN Field into three separate text boxes and if any one of the textbox is blank and user clicks save, I need to display a common error message on top of the SSN Field saying- "SSN is required field". I have added required field attribute on the view model on all these fields so i am getting three edit messages saying SSN is required. how to present only one edit in this case ?
I am using ASP.NET MVC 2
My view model is like this
[Required]
SSN_FirstThreeDigits
[Required]
SSN_SecondTwoDigits
[Required]
SSN_ThirdFourDigits

Any suggestions
Thanks
Subu

A: SSNValidator.com now has an API for validating social security numbers. Data elements include whether or not the number was issued, approximate date of issuance, state of issuance and if it was used in a death claim. Go to the site and click the API/Batch Processing links for details.

A: The Mvc.ValidationTookit Alpha Release: Conditional Validation with MVC 3 can do this.

A: You may need a custom model binder. Please have a look at this article and see how he validates date of birth


text:
Q: how to centralize layout in center and top with two buttons I have a layout it has a frame layout which will show image and on that image I want to show two buttons on the top of screen. On the background of these two screen there is a transparent horizontal bar which I am setting as the background of the Relative or LinearLayout.
and then I want to put two buttons over it which has a good distance between them and I want the background of relative layout just get end after the right/left edge of buttons. In other case I do not want the bar to fill the whole width. What I want here , I am posting here in the image. check out the link for better understanding that what I want.  I have done this but this is not so much flexible as on some devices It looks odd.
and If I use the weight and weight some then the width of button images stretch which looks very odd as my images stretch in width. I have images in square form.
Here is what I am trying :
<LinearLayout
    android:id="@+id/LinearLayout1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/transparent_image"
    android:layout_gravity="center_horizontal">

    <ImageButton
        android:id="@+id/btn_gallery"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:background="@android:color/transparent"
        android:src="@drawable/btn_gallery"
        />
    <TextView
        android:layout_width="20dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"/>

    <ImageButton
        android:id="@+id/btn_share"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:background="@android:color/transparent"
        android:src="@drawable/btn_share" />
</LinearLayout>

A: set layout_width to match_parent.
and add android:gravity ="center" to both button.

A: try this to make a better alignment as per ur reference.
 <LinearLayout
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="2"
      android:layout_marginLeft="10dp"
       android:layout_marginRight="10dp"
android:background="@android:color/transparent"
    android:layout_gravity="center_horizontal">

    <RelativeLayout

     android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_weight="1"
        android:gravity="center"
    >
    <ImageButton
        android:id="@+id/btn_gallery"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1"

        android:layout_marginRight="10dp"
        android:background="@android:color/transparent"
        android:src="@drawable/ic_launcher"
        />
   </RelativeLayout>
<RelativeLayout

     android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginRight="5dp"
        android:layout_weight="1"
        android:gravity="center"
    >
    <ImageButton
        android:id="@+id/btn_share"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1"

        android:layout_marginLeft="10dp"
        android:background="@android:color/transparent"
        android:src="@drawable/ic_launcher" />
    </RelativeLayout>
</LinearLayout>

A: Use this code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_marginLeft="20dp"
    android:layout_marginRight="20dp"
    android:orientation="horizontal"
    android:layout_height="60dp" >

    <Button
        android:id="@+id/button1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_weight="0.1"
        android:text="Button" />

    <Button
        android:id="@+id/button2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_weight="0.1"
        android:text="Button" />
</LinearLayout>

</LinearLayout>


text:
Q: Using Flask as a Webhook for my Test Script I have to create a test script that basically has to send a request to a TCP server which will start performing (Or queuing) an action and then it will respond with a basic acknowledgement that the request was received. The third party will perform the action and after a few seconds (5 to 10) it will make an async call to my flask webhook to report the result of the action, then the test script will evaluate the response and continue with another action/test.
My biggest challenge is how to wait for that webhook request to proceed with the test.
I have thought of a cycle with a timeout that will check if the webhook was called every x seconds, but this will mean a waste time and resources.
Any suggestions for a notification method between my Test Script and the webhook?


text:
Q: Median Filter Super efficient implementation I am looking for a Ansi C implementation of a fast/efficient median filter. Any pointers?
So far, I have found the following implementation, which is good but I am curious on faster ones. I only need for 1 dimension.

A: I needed to extract a signal from very noisy CPU consumption data. Here's the Jeff McClintock median filter...
Initialize the average and median to zero, then for each sample 'inch' the median toward the input sample by a small increment. Eventually it will settle at a point where about 50% of the input samples are greater, and 50% are less than the median.
 The size of the increment should be proportional to the actual median. Since we don't know the actual median, I use the average as an rough estimate. The step size is calculated as 0.01 times the estimate. Smaller step sizes are more accurate, but take longer to settle.
float median = 0.0f;
float average = 0.0f;

// for each sample
{
    average += ( abs(sample) - average ) * 0.1f; // rough running average magnitude.
    median += _copysign( average * 0.01, sample - median );
}


text:
Q: In non-dimensionalization, what does it mean when one "assumes" a quantity has been scaled relative to another quantity? I'm trying to replicate the results of a paper, and they use the quantity $l$ to denote the length of the recirculation zone behind a cylinder for a problem regarding fluid flow past a cylinder. Early on in the paper, they say that all lengths are scaled by the distance between two plane walls (which is constant and equal to 1), but later on, they say "we shall assume that $l$ has been scaled relative to the cylinder diameter $d$." If I don't scale $l$ by the cylinder diameter, and just take the actual length of the recirculation zone, I wind up getting matching results as the ones in the paper, but if I do, the results turn out different. My question is whether "we shall assume" is supposed to mean that one does not need to scale $l$.
Here is a link to the paper: http://booksc.org/book/20991845/ccc1e3
If you have access, here's another link: https://www.cambridge.org/core/journals/journal-of-fluid-mechanics/article/bifurcation-for-flow-past-a-cylinder-between-parallel-planes/E7171D05010DC795CAA96EC3BBA7B2CB


text:
Q: Setting value via Javascript sets focus to textbox in IE10 I have the following Textbox
<asp:TextBox runat="server" ID="txtSeleID" Columns="12" MaxLength="14"
             onfocus="javascript:SetSearchText();"
             onchange="javascript:SetSearchText();"></asp:TextBox>
<asp:RegularExpressionValidator id="REV_SeleID" runat="server"
             ErrorMessage="ID must contain up to 12 numbers."
             Display="Dynamic" ControlToValidate="txtSeleID"
             ValidationExpression="ID...|^\s*(\d{1,12}|\d{4}-\d{4}|\d{3}-\d{4}|\d{2}-\d{4}|\d{1}-\d{4}|\d{1}-\d{4}-\d{4}|\d{2}-\d{4}-\d{4}|\d{3}-\d{4}-\d{4}|\d{4}-\d{4}-\d{4})\s*$" CssClass="ValidationError" SetFocusOnError="True">(!)
</asp:RegularExpressionValidator>

and the below javascript :
function SetSearchText() {
var Tbox = document.getElementById("<%=txtSeleID.ClientID%>");
if (Tbox.value == "ID...") {
    Tbox.value = "";
    Tbox.className = "";
}
}
$(document).ready(function () {
var Tbox = document.getElementById("<%=txtSeleID.ClientID%>");
if (Tbox.value.length == 0) {
    Tbox.className = "quickEnter";
    Tbox.value = "ID...";
}
if (Tbox.value == "ID...")
    Tbox.className = "quickEnter";
});

Here is the button:
<asp:ImageButton EnableViewState="false" id="SubmitBtn" runat="server"
    ImageUrl='<%#Page.ResolveUrl("~/images/btn_submit.gif")%>'
    onclick="Submit_Click" ToolTip="Submit" />

The issue is that when I click on my submit button, it calls the SetSearchText() function and sets the value to "".  In IE 10, it sets the focus to this textbox and I have to hit my submit button again to get it to submit.
If I comment out the setting of the value, the focus issue doesn't occur.
How can I prevent the browser from forcing a focus to my textbox when attempting to submit?
EDIT: Added the regular expression validator to the code section.
EDIT: I found this issue that was having a similar issue, but I don't see a resolution.  In this one, he is using html tags.  I'm using ASP tags so I can't as easily change the input type.

A: I ended up doing a workaround by checking for the browser version.  If IE 10/11, I don't add the text to the input field.
$(document).ready(function () {
    var lexidTbox = document.getElementById("<%=txtSeleID.ClientID%>");
    //workaround for IE10/11 issue
    var showLegalText = true;

// IF THE BROWSER IS IE10
if (navigator.appVersion.indexOf("MSIE 10") !== -1) {
    showLegalText = false;
}

// IF THE BROWSER IS IE11
if (navigator.userAgent.indexOf("Trident") !== -1 && navigator.userAgent.indexOf("rv:11") !== -1)
{
    showLegalText = false;
}

if (showLegalText) {
    if (lexidTbox.value.length == 0) {
        lexidTbox.className = "quickEnter";
        lexidTbox.value = "ID...";
    }
    if (lexidTbox.value == "ID...")
        lexidTbox.className = "quickEnter";
}

});
To be sure, I do not care for this workaround because it's dependent on checking IE versions, but this is the only way I could find to solve this issue.  This prevents the line Tbox.value = ""; from being run, which avoids the issue I'm having.


text:
Q: Javascript regex not working in IE 6-9: "Function expected" error I have the following code:
function parseDate(s) {
var date = new Date(s);
if (!isValidDate(date)) {
    //iso 860 date parser, as some browsers do not support this via new Date yet
    var re=/(\d\d\d\d)\D?(\d\d)\D?(\d\d)\D?(\d\d)\D?(\d\d\D?(\d\d\.?(\d*))?)(Z|[+-]\d\d?(:\d\d)?)?/;
    var a=re(s).slice(1).map(function(x,i){
        if (i==6 && x) x=parseInt(x,10)/Math.pow(10,x.length)*1000; // convert to milliseconds
        return parseInt(x,10)||0;
    });
    date = new Date(Date.UTC(a[0],a[1]-1,a[2],a[3]-(a[7]||0),a[4],a[5],a[6]));
}
return date;
};

function isValidDate(d) {
  if ( Object.prototype.toString.call(d) !== "[object Date]" )
       return false;
  return !isNaN(d.getTime());
}

This works in all browsers but IE6-9. There I get the error:
SCRIPT5002: Function expected
And it points to this line:
        var a=re(s).slice(1).map(function(x,i){

Anyone know what is wrong with that and how to fix it?
Thanks,
Wesley
Edit:
if I change the code to this:
function parseDate(s) {
var date = new Date(s);
if (!isValidDate(date)) {
    //iso 860 date parser, as some browsers do not support this via new Date yet
    var re=/(\d\d\d\d)\D?(\d\d)\D?(\d\d)\D?(\d\d)\D?(\d\d\D?(\d\d\.?(\d*))?)(Z|[+-]\d\d?(:\d\d)?)?/;
    var a = re.exec(s);
    if (a) {
        a = a.slice(1);
        a.map(function(x,i){
            if (i==6 && x) x=parseInt(x,10)/Math.pow(10,x.length)*1000; // convert to milliseconds
            return parseInt(x,10)||0;
        });
        document.getElementById('test1').innerHTML = (a[0] + ' ' + a[1] + ' ' + a[2] + ' ' + a[3] + ' ' + a[4] + ' ' + a[5] + ' ' + a[6] + ' ' + a[7]);
        date = new Date(Date.UTC(a[0],a[1]-1,a[2],a[3]-(a[7]||0),a[4],a[5],a[6]));
    }
 }
 return date;
};

It still doesn't work (complains about .map in IE) but interestingly also doesn't work in safari (and perhaps other browsers). Any reason why?
You'll note that the output (document.write from the new function is:
2008 11 01 20 39:57.78 57.78 78 -06:00
From the old function:
2008 11 1 20 39 57 780 -6

A: According to regular-expressions.info, you should be using re.exec(s) rather than re(s). The page also mentions re.test(s), but that just returns true or false, re.exec(s) actually returns the matches, which appears to be what you want.

A: Regarding .map
The .map() array method is one of the new additions provided by ECMAScript 5; the latest official version of JavaScript (5.0 as December 2009 and now 5.1 as of June 2011). Few (if any) browsers fully support version 5 yet (and certainly not IE6). You can bet that it will be a while before you can rely on browsers to support all the new functionalities (such as Array.map()).
Regarding the Date regex
Unfortunately JavaScript does not allow regexes to be specified using free-spacing mode. This makes longish regexes such as this one difficult to read. To shed some light on the reason why your algorithm isn't working, I've added comments to your regex, which indicate what the capture groups are really capturing. Here it is in PHP syntax:
$re_iso8601_date_needs_work = '%# Original Date regex
    (\d\d\d\d)\D?  # $1: Year.
    (\d\d)\D?      # $2: Month.
    (\d\d)\D?      # $3: Day.
    (\d\d)\D?      # $4: Hour.
    (              # $5: Minute and second. ???
      \d\d\D?      # Minute.
      (            # $6: Optional second.
        \d\d\.?    # Second (whole portion).
        (\d*)      # $7: Second (fractional portion).
      )?           # Second is optional.
    )              # End $5: minute and second.
    (              # $8: Optional timezone alternatives.
      Z            # Either UTC/Zulu.
    | [+-]\d\d?    # Or offset from UTC. Hours and
      (:\d\d)?     # $9: optional minutes.
    )?             # Timezone is optional.%x';

Hint: The fractional seconds are in $7 not $6. And why are you capturing both minutes and seconds in group $5?
Hope this helps! :)


text:
Q: How to handle user timezones preference with Django PostgreSQL? I am new to Django timezones. I need my users to select their timezone from a list so I can store it in PostgreSQL database. My questions are:

*

*What is the best way to generate a list of timezones for the user to
select from?

*What is the best data structure to store the selected
timezone to the database?


text:
Q: Cannot read properties of undefined (Inside a Constructor) I'm building a library app from The Odin Project, and  this error occurs when I try to change read status for Not Read read using a click event.
the error occurs on line 88, reading status value. How can I fix that?
thank you.

console.log(
  "What is the toggle initial value?...",
  myLibrary[parseInt(retrieveBookToToggle)].status
);

let myLibrary = [];
const btnAdd = document.querySelector("btn-add");

//Object Constructor
class Book {
  constructor(title, author, pages, status) {
    this.title = title;
    this.author = author;
    this.pages = pages;
    this.status = status;
  }

  //Add a new book to array
  function addBookToLibrary(title, author, pages, status) {
    let book = new Book(title, author, pages, status);
    myLibrary.push(book);
    displayBooksOnPage()
  }

  //Display array to card
  function displayBooksOnPage() {
    const books = document.querySelector(".books-container");

    //remove displayed cards before loop array
    const removeDivs = document.querySelectorAll(".card");
    console.log("Show me the node count of the current card divs........", removeDivs);
    for (let i = 0; i < removeDivs.length; i++) {
      removeDivs[i].remove();
    }

    //Loop Library array and display to the cards
    let index = 0;
    myLibrary.forEach(myLibrarys => {
      const card = document.createElement("div");
      card.classList.add("card");
      books.appendChild(card);

      //remove book button
      const removeBookButton = document.createElement("button");
      removeBookButton.classList.add("remove-book-button");
      removeBookButton.textContent = "Remove Book";
      console.log("show me my currentnarray objects inside of foreach........", myLibrary);

      //link data attribute of the remove button to the array and card
      removeBookButton.dataset.linkedArray = index;
      index++;
      console.log("show me dataset link back to the array...", removeBookButton.dataset.linkedArray);
      card.appendChild(removeBookButton);

      //start event listener/remove array item from array and card from parent div via data link
      removeBookButton.addEventListener("click", removeBookFromLibrary);

      function removeBookFromLibrary() {
        let retrieveBookToRemove = removeBookButton.dataset.linkedArray;
        console.log("attempting to remove array item via data attribute...", parseInt(retrieveBookToRemove));
        myLibrary.splice(parseInt(retrieveBookToRemove), 1);
        card.remove();
        displayBooksOnPage;
      }

      const readStatusButton = document.createElement("button");
      readStatusButton.classList.add("read-status-button");
      readStatusButton.textContent = "Change Status";

      readStatusButton.dataset.linkedArray = index;
      console.log("show dataset link back to the array for read status button", readStatusButton.dataset.linkedArray);
      card.appendChild(readStatusButton);

      readStatusButton.addEventListener("click", toggleReadStatus);

      function toggleReadStatus() {
        let retrieveBookToToggle = readStatusButton.dataset.linkedArray;
        Book.prototype = Object.create(Book.prototype);
        const toggleBook = new Book();
        console.log("what's the toggle initial value? ", myLibrary[parseInt(retrieveBookToToggle)].status);
        if (myLibrary[parseInt(retrieveBookToToggle)].status == "Read") {
          toggleBook.status = "Not Read";
          myLibrary[parseInt(retrieveBookToToggle)].status = toggleBook.status;
        } else if (myLibrary[parseInt(retrieveBookToToggle)].status == "Not Read") {
          toggleBook.status = "Read";
          myLibrary[parseInt(retrieveBookToToggle)].status = toggleBook.status;
        }
        displayBooksOnPage();
      }

      for (let key in myLibrarys) {
        const para = document.createElement("p");
        para.textContent = (`${myLibrarys[key]}`);
        card.appendChild(para);
      }
    })
  }

  const addBookButton = document.querySelector(".btn-add");
  addBookButton.addEventListener("click", displayTheForm);

  function displayTheForm() {
    document.getElementById("books-form").style.display = "";
  }

  const submitButton = document.querySelector(".btn-add");
  submitButton.addEventListener("click", intakeFormData);

  function intakeFormData() {
    let Title = document.getElementById("title").value;
    let Author = document.getElementById("author").value;
    let Pages = document.getElementById("pages").value;
    let Status = document.getElementById("status").value;

    if ((Title == "") || (Author == "") || (Pages == "") || (Status == "")) {
      return;
    }

    addBookToLibrary(Title, Author, Pages, Status);

    document.getElementById("add-book").reset();
  }

  const clearButton = document.getElementById("btn-reset");
  clearButton.addEventListener("click", clearForm());

  function clearForm() {
    document.getElementById("add-book").reset();
  }


text:
Q: Errors while dredging a pre-setup glmmTMB using fitTMB() in R I'm using a specifically designed glmmTMB to run a weighted binomial model with random effects. The dredge() function from MuMIn is normally compatible with glmmTMB but I am receiving an error.
Reproducible example using the iris dataset. Note the models show convergence warnings due to being randomly generated but still run. My own model is set up the exact same way and does converge when run like so.
library(TMB)
library(glmmTMB)
library(MuMIn)
library(tidyverse)

#Set up the data to fit a negative binomial model
data(iris)
df <- iris %>%
  mutate(used=rep(c(0,1),times=75)) #random binomial response variable

# Create the model according to Muff et al. (2020)
## Link: https://conservancy.umn.edu/bitstream/handle/11299/204737/fisher_rsf_and_ssf.html?sequence=27&isAllowed=y
df$weights <- ifelse(df$used == 1, 1, 1000)

# Set up the model, but do not yet fit it
TMBStruc.ex <- glmmTMB(used~
                      Sepal.Length +
                      Sepal.Width +
                      Petal.Length +
                      Petal.Width +
                      (1|Species) +
                      (0+Sepal.Length|Species) +
                      (0+Sepal.Width|Species) +
                      (0+Petal.Length|Species) +
                      (0+Petal.Width|Species),
                    data=df, family=binomial, weight=weights, doFit=FALSE)

# Fix the standard deviation of the first random term, which is the (1|id) component
# in the above model equation
TMBStruc.ex$parameters$theta[1] = log(1e3)

# Tell glmmTMB not to change the first entry of the vector of variances,
# and give all other variances another indicator to make sure they can be freely estimated
TMBStruc.ex$mapArg = list(theta=factor(c(NA,1:4))) #The 1:X value has to be the number of fixed terms

m <- glmmTMB:::fitTMB(TMBStruc.ex) #This is successful
summary(m)

dredge(m) #Not successful

#I get the following error:
## Error in seq_len(ncols) :
##   argument must be coercible to non-negative integer
## In addition: Warning messages:
##   1: In while (CLASS == "list") { :
##       the condition has length > 1 and only the first element will be used
##   2: In seq_len(ncols) : first element used of 'length.out' argument

I've tried running the dredge directly with success (shown below), so it has to do with the way I've set it up.
TMBStruc.ex2 <- glmmTMB(used~
                         Sepal.Length +
                         Sepal.Width +
                         Petal.Length +
                         Petal.Width +
                         (1|Species) +
                         (0+Sepal.Length|Species) +
                         (0+Sepal.Width|Species) +
                         (0+Petal.Length|Species) +
                         (0+Petal.Width|Species),
                       data=df, family=binomial, weight=weights) #This is successful
dredge(TMBStruc.ex2) #This is successful

Is there a way to resolve the errors I've found and run the dredge with all the presets and arguments intact?

A: This seems to work fine if we pass start and map directly to glmmTMB (as is possible since version 1.0.0 of glmmTMB):
m <- glmmTMB(used~
                      Sepal.Length +
                      Sepal.Width +
                      Petal.Length +
                      Petal.Width +
                      (1|Species) +
                      (0+Sepal.Length|Species) +
                      (0+Sepal.Width|Species) +
                      (0+Petal.Length|Species) +
                      (0+Petal.Width|Species),
                      data=df,
                      family=binomial,
                      weight=weights,
                      start = list(theta=c(log(1e3), rep(0,4))),
                      map = list(theta=factor(c(NA, 1:4)))
                      )

summary(m)
dredge(m)


text:
Q: Java installation issues on Ubuntu Trying to install Java (JDK 6) on my new Ubuntu system and getting some bizarro errors.  This is my first time ever using any flavor of Linux and so I'm sure it's a user issue (permissions or otherwise).
I downloaded the BIN file directly off Oracle's site (Java SE 6u23 for 64-bit Linux). This defaulted to downloading to /home/myUserName/Downloads.
From there I moved the file to /opt/java, which was a directory I created, because (as a Linux novice) that made sense to be the directory where Java should go.
I then ran the following 2 commands, per instruction I found online for running BINs:
chmod +x jdk-6u23-linux-x64.bin
sudo ./jdk-6u23-linux-x64.bin

Now, in my /opt/java directory I see both the BIN file and the jdk1.6.0_23 directory that seems to be intact upon inspection.
But, when I open a new terminal and run java -version, I get:
The program 'java' can be found in the following packages:
 - gcj-4.4-jre-headless
 - gcj-4.5-jre-headless
 - openjdk-6-jre-headless
Try: sudo apt-get install
What is going on here?!?
(1) Was I wrong to try and make /opt/java my Java directory?
(2) Did I run the wrong commands?
(3) Is Java 1.6.0_23 even installed on my machine?
(4) What are all those gcj-xxx-headless targets?!?!
Thanks for any input!

A: Was I wrong to try and make /opt/java my Java directory?
Not really. Many Java developers install multiple JDK installations and always use /opt/jdk1.6.0_23 or similar paths. The bin file you downloaded is not an installer, but merely an extractor. It does not install the java binaries into system folders like /bin.
I usually download the JDK and execute it from within my home folder and afterwards move it to /opt and performing an chown.
Did I run the wrong commands?
Not really. In case you wanted to install a separate JDK, you did it correctly. In case you wanted system integration, you would be better off to use the distribution-specific packages, such as the one installed via aptitude install sun-java6-jdk or alike.
The bin you downloaded is imho more flexible, since I can use it to install multiple verisons of Java on the same system. I know this is something you don't often do on Linux machines.
If you want to use the java binary on command line, you'd have to manually set up the PATH and JAVA_HOME environment variables. I think on Ubuntu that's /etc/environment or /etc/profile or something like that.
Is Java 1.6.0_23 even installed on my machine?
Not really. See above answers.
What are all those gcj-xxx-headless targets?!?
The GCJ is the Gnu Compiler for Java. Obviously, it includes a Java Development Kit and a Java Runtime Environment.

A: Why downloading a bin, when you can simply:
sudo apt-get install sun-java6-jdk

If there isn't any special reason why you'd want that specific version from the site, you should use apt-get because it will take care of all the stuff like PATH variable, etc.

A: Please follow below steps to install oracle java:
Download the latest Java SE SDK version.
http://www.oracle.com/technetwork/java/javase/downloads/index.html
Untar the Archive:
tar -xzvf jdk-8-linux-x64.tar.gz
mv jdk1.8.0 /opt
cd /opt/jdk1.8.0

This step registers the downloaded version of Java as an alternative, and switches it to be used as the default:
update-alternatives --install /usr/bin/java java /opt/jdk1.8.0/bin/java 1
update-alternatives --install /usr/bin/javac javac /opt/jdk1.8.0/bin/javac 1
update-alternatives --install /usr/lib/mozilla/plugins/libjavaplugin.so mozilla-javaplugin.so /opt/jdk1.8.0/jre/lib/amd64/libnpjp2.so 1
update-alternatives --set java /opt/jdk1.8.0/bin/java
update-alternatives --set javac /opt/jdk1.8.0/bin/javac
update-alternatives --set mozilla-javaplugin.so /opt/jdk1.8.0/jre/lib/amd64/libnpjp2.so

Test
To check the version of Java you are now running
java -version

Output
java version "1.8.0"
Java(TM) SE Runtime Environment (build 1.8.0-b132)
Java HotSpot(TM) 64-Bit Server VM (build 25.0-b70, mixed mode)

To check the browser plugin browse to http://www.java.com/ and click "Do I have Java?"
Ref: https://askubuntu.com/questions/437776/ubuntu-13-04-unable-to-install-jdk7

A: You simply have put the JDK binaries in a directory. Although by convention /opt/java or /opt/jdk is often used, these are not directories that are automatically recognized by the system.
You can however update your PATH environment variable to include the /opt/java/bin dir, or symlink (ln -s) /opt/java/bin/java in one of the directories on your system that are included in your path like /usr/bin/

A: The JDK you installed from Sun/Oracle is the original JDK. The "headless" JDK is the open source alternative.
When you run the JDK BIN file, it simply extracts the archive. When you entered the java -version command, it found the FOSS Java, not the Java you had extracted in /opt. As somebody else had mentioned, developers keep multiple versions of the JDK. If you wish to use the Oracle's Java, then you need link /usr/bin/java to /opt/jdk1.6.0_23/bin/java.
sudo ln -s /usr/bin/java /opt/jdk1.6.0_23/bin/java

For this to work, the existing java command should be first delinked from the "headless" JDK. (Do the following before the previous command.)
sudo mv /usr/bin/java /usr/bin/java_old

This assumes that there is a link or executable named java in /usr/bin. Use the which command to be sure.
which java

A: To add a new pathname to the existing PATH variable, you need to type this in Terminal:
PATH=`echo $path`:/your/new/path
export PATH
If you had lost your original PATH variable, you could restore by entering this:
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
export PATH

A: Try:
rm -rf /usr/bin/javac
rm -rf /usr/bin/jar

ln -s /home/jdk1.6.0_13/bin/javac /usr/bin/javac
ln -s /home/jdk1.6.0_13/bin/jar /usr/bin/jar

This way, your linux can find java && javac in /usr/bin