text:
Q: What do people mean when they talk about serialization in Unity? I hear people talking about serializing variables among things in their unity projects and quite don't understand it. I see them using
[SerializeField]

and don't know why or what it does.

A: I looked up the definition of data serialization: Serialization is the process of converting the state information of an object into a form that can be stored or transmitted.
During serialization, objects write their current state to temporary or persistent storage. Later, the object can be recreated by reading or deserializing the state of the object from the store.
Objects are created as the program runs, and then reclaimed when unreachable, with a short lifespan. But what if we want to store the contents of the object permanently?
Convert it into a sequence of bytes and save it on a storage medium. Then serialization is required. [SerializeField] is to force Unity to serialize a private field. This is an internal Unity serialization function. Sometimes we need to Serialize a private or protected attribute. In this case, the [SerializeField] attribute can be used.
The above is some information I found, I hope it is correct and can bring you some help

A: Say, you have a field _speed and you want to set it using inspector. It means we want it to be serialized - stored somewhere in a human-readable and flexible format(e.g. xml), not directly in code. So when you edit fields in inspector, you edit the serialized data. During compilation, it's being deserialized and assigned to a field. This is how serialization/desearialization works. It is used to store non-static or just big amounts of data. In case of Unity it is used to show you everything in inspector. Transform has position and scale variables serialized and you can edit them.
In Unity there are two common ways to make fields assignable in inspector: using public fields or using [SerializedField] attribute for private ones.
Making fields public just to edit them with inspector is bad practice. If you can edit field in inspector, it means every other component can too, which is insecure. There is no good architecture that allows such things. If you want other components to edit the field, make it a property or make a set method. If you just need to assign fields by hand, don't use public fields. Avoid them.
When you use the [SerializeField] attribute, you create a private field that is accessible to this component only and you can assign it in inspector at the same time. If you need other components to read it, you can make a public property without set (public float Speed => _speed;).
This all is not an obligatory usage. Just good practice.

A: Any values set in the Unity inspector for any public fields or private/protected fields that use the attribute [SerializeField] are saved with the current scene file.
If you open up a Unity.scene file you will find a hierarchy of data that matches the scene hierarchy along with lists of what script or component classes are attached to that game object and what the field values of those classes/components should be.
When loading a level in Unity, the scene file is deserialized meaning that a program walks the data structure creating game objects. It then creates component and script class instances attached to those components and initializes them with the serialized data in the scene file. After that you end up with a level more or less the same as it was when saved in the unity editor.
In addition to your own Monobehaviour scripts having this ability, all the default unity components work this way. Transform uses serialized Vector3s for position, rotation and scale. MeshFilter components serialize a reference to a mesh asset and the MeshRenderer component references Materials that are used by the GPU to draw the mesh etc etc.
In short, serialisation is a process by which computers transform data so that it can be written to a file (or sent across a network via a protocol stream) and then later transformed back into the original set of objects it was to begin with (or as close as matters).


text:
Q: WordPress article text issue I have changed the text area by editing the max-width from 696 to 1300
    .entry-content,
.entry-summary {
    margin-top: 34px;
    max-width: 1300px;
    width: 100%;

But that made two issues

*

*The post footer on the left upper corner overlaps with it, so my text starts only after the post footer. I don't really understand what I have done, but I know that I want the text to start right next to the footer and after the footer it extended.

*the text can exceed the page which enable the right/left scroll. How to make the text don't exceed the page?

I think that the problem is very clear using all mentioned above but feel free to visit the post that is in the screenshot
http://www.abdorefky.com/testing-homepage-margins/

A: The content div shares a CSS class with .entry-content, which appears to be overriding .entry-summary
Try updating your .entry-content CSS.
There is a padding-left: 100px; under .entry-content, which is indenting your content.

A: the reason why it went down is because when you increased the width from 696px to 1300px, it's containing div (.entry-wrap) cannot contain it anymore since its only 1272px wide. So it has to bring down that div below the footer and even add a scroll bar. May I know what you intend to do?

redpajama_set_name: RedPajamaStackExchange


text:
Q: the data is not pushed into mysql table

connection.query("SELECT email, password FROM authenticate where email=?", email,
    function (error, result) {
      if (error) {
        throw error;
      } else {
        if (result.length == 0) {
          console.log('name not available');
          res.sendFile(path.join(__dirname + "/public/applyFailure.html"));
        } else if (result[0].password == password) {
          console.log(userData);
          connection.query("INSERT INTO userapplications SET ? ", userData,
            function (error, result, fields) {
              if (error){
                throw error;
              }
              else{
                console.warn("insertion successful");
                res.sendFile(path.join(__dirname + "/public/applySuccess.html"));
              }
            });
        } else {
          console.log('invalid user and password');
          res.sendFile(path.join(__dirname + "/public/apply.html"))
        }
      }
    });
  connection.end();

error:

Cannot enqueue Query after invoking quit.

The database gets connected for some reason the data doesn't get added into the table.
I'm a beginner.

A: I think it's because of async nature of NodeJS. Try to concatenate the connection.end() with connection.query().
Like:
connection.query("your_code_here).end();

A: Move your connection.end(); inside callback like below.

connection.query("SELECT email, password FROM authenticate where email=?", email,
    function (error, result) {
      if (error) {
        connection.end();
        throw error;
      } else {
        if (result.length == 0) {
          console.log('name not available');
          res.sendFile(path.join(__dirname + "/public/applyFailure.html"));
        } else if (result[0].password == password) {
          console.log(userData);
          connection.query("INSERT INTO userapplications SET ? ", userData,
            function (error, result, fields) {
              if (error){
                connection.end();
                throw error;
              }
              else{
                console.warn("insertion successful");
                res.sendFile(path.join(__dirname + "/public/applySuccess.html"));
                connection.end();
              }
            });
        } else {
          console.log('invalid user and password');
          res.sendFile(path.join(__dirname + "/public/apply.html"))
          connection.end();
        }
      }
    });
  connection.end();

something like this, you can make changes.


text:
Q: TRR_TO_NUMBER is not defined in STRING_FUNCTION Snowflake I have a problem with my function ;( What function should do ? It should check if the string is a string or if it's number. So I have created a UDF
CREATE OR REPLACE FUNCTION tring_function(s string)
    RETURNS string
    LANGUAGE JAVASCRIPT
    AS
    $$
    if(isNan(S)) {
    return 'not a number';
    } else {
    return S ;
    }
    $$
    ;

I have no idea what I'm doing wrong ;(
The error message :

"JavaScript execution error: Uncaught ReferenceError: isNan is not defined in STRING_FUNCTION at ' if(isNan(S)) {' position 4 stackstrace: STRING_FUNCTION line: 2
"

A: The function is isNaN and not isNan:
CREATE OR REPLACE FUNCTION string_function(s string)
    RETURNS string
    LANGUAGE JAVASCRIPT
    AS
    $$
    if(isNaN(S)) {
    return 'not a number';
    } else {
    return S ;
    }
    $$
    ;

Output:

Another way is usage of TRY_TO_NUMBER which is built-in.


text:
Q: How to stop sending requests to dispatch_async requests for ringing? I click the button to beep and as the background thread there is a welcome message appears on the view controller, the beep is continuously going on until i close the application.
How can i suspend the queue for further execution when welcome message arrives on the view controller?
I tried  calling from another view controller dispatch_suspend(dispatch_get_main_queue()); when welcome screen comes in but the beep is continuously going on in background. Can somebody have hint to stop queue from executing or just clean the queue?
dispatch_async(dispatch_get_main_queue(), ^{
    NSInteger timeintervalForBeep;
    if (_bu.buModel == BuTwo) {
        timeintervalForBeep = 7;
    } else {
        timeintervalForBeep = 2;
    }

    _findBeepTimer = [NSTimer scheduledTimerWithTimeInterval:timeintervalForBeep
                                                      target:self
                                                    selector:@selector(makeBeep)
                                                    userInfo:nil
                                                     repeats:YES];
    // Fire it once immediately.
    [_findBeepTimer fire];
});

A: in the makeBeep function, invalidate the timer by adding the following codes:
[_findBeepTimer invalidate];
_findBeepTimer = nil;


text:
Q: How to use A4 instead of letterpaper? I am working with a template which uses letterpage. Yet I need it to be A4.
\documentclass[10pt,letterpaper]{article}
\usepackage[letterpaper,margin=0.75in]{geometry}
\usepackage[utf8]{inputenc}
\usepackage{mdwlist}
\usepackage[T1]{fontenc}
\usepackage{textcomp}
\usepackage{tgpagella}
\pagestyle{empty}
\setlength{\tabcolsep}{0em}

How do I change it?

A: The article class has an option for A4 (210 mm x 297 mm) paper:
\documentclass[a4paper]{article}

other possible options for page size are:

*

*a5paper - A5: 148 mm x 210 mm, that is half of A4, basically

*b5paper - B5: 250 mm x 176 mm

*letterpaper - Letter: 215.9 mm x 279.4 mm

*legalpaper - Legal: 215.9 mm x 355.6 mm

A: You should also have a look to KOMA script, instead of the default article class:
\documentclass[a4paper,10pt]{scrartcl}


text:
Q: Why does one of my finaries fail with version `GLIBC_2.27' not found I am cross-compiling by binaries identically by CMake clauses like
add_executable(mybinary1 mybinary1.c util_temp.c)
target_link_libraries(mybinary1 m)

add_executable(mybinary2 mybinary2.c util_temp.c)
target_link_libraries(mybinary2 m)

Unfortunately, one of them fails when running on target platform:
/mybinary2: /lib/arm-linux-gnueabihf/libm.so.6: version `GLIBC_2.27' not found (required by ./mybinary2)

First binary runs well.
ldd shows
# ldd mybinary2
./mybinary2: /lib/arm-linux-gnueabihf/libm.so.6: version `GLIBC_2.27' not found (required by ./mybinary2)
    linux-vdso.so.1 (0x7ed1d000)
    /usr/lib/arm-linux-gnueabihf/libarmmem.so (0x76fa2000)
    libm.so.6 => /lib/arm-linux-gnueabihf/libm.so.6 (0x76f27000)
    libc.so.6 => /lib/arm-linux-gnueabihf/libc.so.6 (0x76de6000)
    /lib/ld-linux-armhf.so.3 (0x76fcc000)
# ldd mybinary1
    linux-vdso.so.1 (0x7ee09000)
    /usr/lib/arm-linux-gnueabihf/libarmmem.so (0x76ece000)
    libm.so.6 => /lib/arm-linux-gnueabihf/libm.so.6 (0x76e53000)
    libc.so.6 => /lib/arm-linux-gnueabihf/libc.so.6 (0x76d12000)
    /lib/ld-linux-armhf.so.3 (0x76efb000)

What does it mean and how to solve it? Can I compile against specific version of a library? Why does it refer GLIBS indirectly, via libm?
If I do
target_link_libraries(mybinary2 m -static)

it starts to work but binary becomes x20 larger.
I also tried
__asm__(".symver realpath,realpath@GLIBC_2.19");
int main(int argc, char *argv[])

in mybinary2.c with no effect.
target_link_libraries(mybinary2 m -static-libgcc -static-libstdc++)

in CMakeLists.txt with no effect.
target_link_libraries(mybinary2 m libc.so.6:2.19)

with error message
[build] /usr/lib/gcc-cross/arm-linux-gnueabihf/7/../../../../arm-linux-gnueabihf/bin/ld: cannot find -llibc.so.6:2.19

Is latter syntax correct? How to see, which version (and of what) is on my system?
I tried commands like
ld -llibc

but neither work.
On my target computer (it is Raspberry Pi with old version of OS):
# ldd --version
ldd (Debian GLIBC 2.19-18+deb8u10) 2.19
Copyright (C) 2014 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.
Written by Roland McGrath and Ulrich Drepper.

I don't know how to use cross ldd on source computer.

A: Based on what your target computer outputs via ldd --version and based on the error (which also explains why a static link works):
You have a GLIBC version mismatch, i.e. you compile it using GLIBC 2.27 but on the target computer you have GLIBC 2.19. You either need to crosscompile with a lower version than you are currently using or upgrade glibc on the target computer.
EDIT:  To clarify which errors and general info I mean:
1)
# ldd mybinary2
./mybinary2: /lib/arm-linux-gnueabihf/libm.so.6: version `GLIBC_2.27' not found (required by ./mybinary2)

*

# ldd --version
ldd (Debian GLIBC 2.19-18+deb8u10) 2.19

EDIT2: Did a quick search and assuming you are crosscompiling on debian you could use the following command to get available package versions:
apt-cache policy myPackage

Where myPackage will most likely be libc6-dev-armhf-cross for your current needs.
EDIT3: As Andrew Henle pointed out. The easiest solution is to directly compile your project on the target device (or a compilation environment that is identical to the one on the target). Consider the above only if the target device is limiting you in doing so.


text:
Q: PHP merge 2 arrays similar to SQL INNER JOIN I want to merge 2 arrays and obtain a single array, but merging them based on array 1 [id_dueno] = array 2 [id].
It will be an equivalent of using JOIN ON in MYSQL.
I cant just array_merge(array1,array2). Sometimes I receive many arrays so I have to merge based on IDs
ARRAY 1
    Array
    (
        [0] => Array
            (
                [id] => 1
                [nombre_propiedad] => casa
                [id_dueno] => 2
                [direccion] => direccion 321
                [id_arrendatario] => 1
                [rol] => 10-12
            )

        [1] => Array
            (
                [id] => 2
                [nombre_propiedad] => Edificio
                [id_dueno] => 1
                [direccion] => direccion 123
                [id_arrendatario] => 2
                [rol] => 47-18
            )
)

ARRAY 2
Array
(
    [0] => Array
        (
            [id] => 1
            [nombre_dueno] => dueño1
            [ciudad_dueno] => TEMUCO
            [direccion_dueno] => Vicuna Mackena 123
            [rut_dueno] => 11118000-0
            [ultimo_recibo] => 41
        )

    [1] => Array
        (
            [id] => 2
            [nombre_dueno] => duenño2
            [ciudad_dueno] => TEMUCO
            [direccion_dueno] => Vicuña Mackenna 321
            [rut_dueno] => 111314-6
            [ultimo_recibo] => 3
        )
)

Desired result
Array
    (
        [nombre_propiedad] => casa
        [id_dueno] => 2
        [direccion] => direccion 321
        [id_arrendatario] => 1
        [rol] => 10-12
        [id] => 2
        [nombre_dueno] => duenño2
        [ciudad_dueno] => TEMUCO
        [direccion_dueno] => Vicuña Mackenna 321
        [rut_dueno] => 111314-6
        [ultimo_recibo] => 3
    )


text:
Q: How to return to bookmarked hash-bang URLs within a single page application? I understand the HTML5 History API and how it enables to back and forward buttons within a single page application (SPA).
But given the URL displayed by the API, how can I return to application state when given the faux URL via a bookmark or emailed URL?  For instance...
If my SPA loads from http://dacracot.org/myApp, the user may navigate around until the URL as morphed to http://dacracot.org/myApp#!ec2f209f25e11.  The user decide they want this to be their start point within the SPA from now on and bookmarks it.  Furthermore, they think it is a good start point for their coworkers and email the URL to them.
So when my SPA loads, I can trap the hash-bang marker #!ec2f209f25e11, but now what?  What mechanism do I have available that puts them at the same click stream that they expect?  Do I have to create a route table with every display option?  This (I hope) is not my only option.

A:
Do I have to create a route table with every display option?

More or less.
Since the fragment identifier is only available on the client, you need client-side logic that can use the URL to determine the state that the page should be in when the user asks to load it.


text:
Q: Child process is not terminated I have a small utility that need to use fork() and wait(), however, I am facing an issue that the child process is not being terminated after the parent program is running. Any idea how I can fix it?
int test(void)
{
    pid_t PID;
    PID = fork();

    if (PID == 0) {

            sprintf(execmd, "/root/test);
            system(execmd);

            sprintf(filename, "test_results.txt);

            FILE *fp = fopen(filename, "r");

            fscanf (fp, "%s%s%s%s%s", &A, &B, &C, &D, &E);
            printf ("A=%s B=%s C=%s D=%s E=%s\n", A, B, C, D, E);

            fclose (fp);
    }
    else    // *** Parent Process ***
    {
            int status;
            wait(&status);
    }

    return 0;
}

A: At the very beginning: your code should not compile at all, as you do not close your strings:
sprintf(execmd, "/root/test);
system(execmd); //         ^ missing quote!

(By the way, why don't you simply call system("/root/test");? At least from the code shown, I do not see any reason why you would need a copy...)
Then see wait documentation:

The wait() function shall suspend execution of the calling thread until status information for one of the terminated child processes of the calling process is available, or until delivery of a signal whose action is either to execute a signal-catching function or to terminate the process. If more than one thread is suspended in wait() or waitpid() awaiting termination of the same process, exactly one thread shall return the process status at the time of the target process termination. If status information is available prior to the call to wait(), return shall be immediate.
Return Value
If wait() or waitpid() returns because the status of a child process is available, these functions shall return a value equal to the process ID of the child process for which status is reported. If wait() or waitpid() returns due to the delivery of a signal to the calling process, -1 shall be returned and errno set to [EINTR]. If waitpid() was invoked with WNOHANG set in options, it has at least one child process specified by pid for which status is not available, and status is not available for any process specified by pid, 0 is returned. Otherwise, (pid_t)-1 shall be returned, and errno set to indicate the error.

So - if wait returns, you first should check if the process id was actually returned, otherwise you might re-enter into wait.
Then, if wait does not return, your child process is still running. I don't see why your process should be blocked because of the file handling (well, you do not perform any error checking, though, but that's a different matter unrelated to your problem), so most likely your child process is caught in the call to system.
What you now need is a timeout mechanism. My proposition is now as follows:

*

*create a pipe for self-triggering events

*install a signal handler for SIGCHLD using sigaction

*in the signal handler, do the wait and write a single byte to your pipe

*in your main function, where you currently wait for your child process, you would now first select or poll for your pipe with a timeout. If timeout occurs, send a signal to your child process (you could do that twice, first sending SIGTERM to allow your child to terminate gracefully, and if that does not help, send SIGKILL afterwards.

Alternative: If on linux, have a look at signalfd - you are not portable then, but get the same work done easier (select/poll for your fd and on success, you can call wait in the main function again).
Additionally, I recommend to re-structure your program a little: system will internally call fork and execve again, so you actually create another child process.
So I'd rather do it this way:
// preparations as described above

if (PID == 0)
{
    execl("/root/test", ""); // won't return unless on error!
    // some error handling?
    return -1;
}

// parent process
if(PID < 0)
{
    // error, the child process could not be created!
    return -1;
}

// select/poll
if(timeout)
{
    kill(PID, SIGTERM);
    // select/poll
    if(timeout)
        kill(PID, SIGKILL);
}

//***************************************************
// if using signalfd:
    int status;
    wait(&status);
    // yet to be done: check return value, status, errno
    // you might need a loop...
// otherwise, prefer doing this in the signal handler
// however, the following out put MUST NOT be done there, as
// file handling is not async safe!
// just set some global flag there if the process terminated successfully!
//***************************************************

if(child_was_successful)
{
    FILE* fp = fopen("test_results.txt", "r");
    if(fp) // only if successful!
    {
        // missing declarations (presumably global), adding them here:
        char A[32], B[32], C[32], D[32], E[32];
        // some fixes:
        // 1. checking return value
        // 2. arrays already decay to pointers when being passed
        //    -> you do not need to take the address of again!
        // 3. adding max length to your arrays prevents fscanf
        //    from writing beyond your array boundaries
        if(fscanf (fp, "%31s%31s%31s%31s%31s", A, B, C, D, E) == 5)
        //                                     ^ no ampersand!
        //               ^ 31: need to leave space for terminating 0 character
        {
            printf ("A=%s B=%s C=%s D=%s E=%s\n", A, B, C, D, E);
        }

        fclose (fp);
    }
}


text:
Q: Java CRUD class generator for Intellij Idea Is there a way to automaticaly generate CRUD class for Hibernate Entity in Spring MVC using the IntelliJ Idea IDE? I found some possibility to generate in NetBeans, I would need something similar for Intellij too. Thx in advance for your help.
Generate JSF2 CRUD's - Can I create the bean and xhtml automatically for any entity?

A: You can create your own templates in IntelliJ IDEA:

Go to: Settings > IDE Settings > File and Code Templates as below:

And then when you create a new class you can just select the template that you would like to use:


text:
Q: Fix \parbox on upper bound of \makebox right now I'm designing the titlepage for my thesis. The logo of my university should be in the upper left corner, then I want a vertical line starting at the top of the logo and ending at the bottom of the page. In the lower right corner should be more text.
I tried to realize this with nested boxes. Here is my MWE:
\documentclass[12pt,a4paper]{scrartcl}
\usepackage[ngerman]{babel}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{geometry}

\begin{document}
    \begin{titlepage}
      \newgeometry{margin=2cm, headheight = 0cm, centering=true}
      \fbox{
        \makebox[\textwidth]{
          \parbox[b]{0.3819\textwidth}{
                \hspace{0.01\textwidth}\hspace{1em}\vbox{%
                    \raggedright
                    \rule{0.85\linewidth}{3cm}

                }
            }%

            \rule{1pt}{0.99\textheight}

            \begin{minipage}[t]{0.6181\textwidth}
                \begin{minipage}[b]{10cm}%{%
                    \raggedleft
                {\noindent\Large Text}\\[\baselineskip]
                \end{minipage}
          \end{minipage}
        }%outer makebox
      }
    \end{titlepage}
\end{document}

It's pretty obvious, that the rule is the problem. Can someone help me? Thanks, FFoDWindow

A: Using the tikz-package you could create your titlepage like this:
\documentclass[12pt,a4paper]{scrartcl}
\usepackage[ngerman]{babel}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{geometry}
\usepackage{tikz}

\begin{document}

\begin{titlepage}

\newgeometry{margin=2cm, headheight = 0cm, centering=true}
\begin{tikzpicture}[remember picture,overlay]
\node[anchor=north west,yshift=-2cm,xshift=2cm] at (current page.north west)
    {\rule{0.3819\linewidth}{3cm}};
\end{tikzpicture}
\hspace{0.3819\linewidth}\rule{1pt}{0.99\textheight}
\parbox[t]{0.6181\textwidth}{\raggedleft\Large Text}

\end{titlepage}
\end{document}

A: I think you can vastly simplify the code:
\documentclass[12pt,a4paper]{scrartcl}
\usepackage[ngerman]{babel}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{geometry}
\usepackage{graphicx}

\begin{document}

\begin{titlepage}
\newgeometry{margin=2cm, headheight = 0cm}%,headsep=0pt}
\setlength{\fboxsep}{0pt}
\setlength{\parindent}{0pt}
\vspace*{-\baselineskip}
\vspace*{-\topskip}
\vspace*{-\fboxrule}

\hspace*{-\fboxrule}%
\fbox{%
  \begin{minipage}[t][\textheight]{0.3819\textwidth}
    \centering
    \vspace{0pt}% set the reference point to the top
    \includegraphics[width=\dimexpr\textwidth-2em]{example-image}%
  \end{minipage}%
  \hspace{-.5pt}\vrule width 1pt\hspace*{-.5pt}%
  \begin{minipage}[t][\dimexpr\textheight-.4pt][b]{0.6181\textwidth}
  \raggedleft
  \Large Text

  \vspace*{\baselineskip}
  \end{minipage}%
}% end of \fbox
\hspace*{-\fboxrule}

\vspace*{-\fboxrule}
\end{titlepage}
\end{document}


text:
Q: Implementing JTreeTable in swing I would like to implement a JTreeTable. I saw the example in the official java website. I am a beginner to java and i am not able to understand that example. I have the tree node and child names as a string. How do i implement it?

A: there are (only products I tried)
free

*

*SwingX

*NetBeans Outline, illustrated here

*excellent workaround by aephyr

*simple code example here
non-free

*

*JIDE Grids
maybe more information you can find here


text:
Q: Type of variable that contains type, not instance I work with sequalize models. They are classes. When I register them some data is attached to them. So I need store them. I store them in a list. But when I retrieve a model to a variable, a little confuse appears. What does the variable have to have a type to store the type?

A: I am not sure exactly what you need because you have not posted any code demonstrating your issue.  It's quite possible that all you need is to use the typeof type query on your class constructor:
class Foo { ... }
class Bar { ... }
class Baz { ... }
var instances: (Foo | Bar | Baz)[] = [new Foo(), new Baz(), new Foo()];
var classes: (typeof Foo | typeof Bar | typeof Baz)[] = [Foo, Baz, Foo];

Or maybe you want to specify a constructor generically, which you can do as follows:
type Constructor<T = {}> = {
  new (...args: any[]): T;
  readonly prototype: T;
}
var classes: (Constructor<Foo|Bar|Baz>)[] = [Foo, Baz, Foo];

I hope that helps.  If you need more, please add more details to your question.  Good luck!


text:
Q: How Can I Make X Axis and Y Axis Exchange and use multiple X Axes in ZedGraph Controls I want to draw a graph with multiple vertical curves, each curve corresponds to a horizontal Axis and all these curves share a horizonal vertical Axis. Two approaches may be possible:
1. Make X Axis vertical and make Y Axis horizontal, and then use multiple Y Axes, but how to make X Axis and Y Axis exchange?
2. Use multiple X Axes, but it seems that the ZedGraph only support not more than 2 X Axes. If I want to draw more than two curves, what should I do then?


text:
Q: java reflection :Avoid warning unchecked call to getConstructor(Class>...) as a member of the raw type Class I have read this post
java: unchecked call to getConstructor(java.lang.Class<?>...)
for (Map.Entry<String, Class> entry : connectionRepository.entrySet()) {
            if (/*someconditionhere*/) {
                try {
                    cwsConnection = (CWSConnection)entry.getValue().getConstructor().newInstance();
                    break;
                } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
                    logger.error("Could not Create instance of CWSConnection for site version:\"{}\" Error:\"{}\"", entry.getKey(), e.getMessage(), e);
                }
            }
        }

While compiling this piece of code I am getting a warning

warning: [unchecked] unchecked call to getConstructor(Class...) as a member of the raw type Class

I just wanted to get the default constructor of CWSConnection, therefore, I should not pass any parameters to getConstructor(Class...) method.
Is there any better approach to get the default constructor(The one without arguments)
(I know @SupressWarning annotation will suppress this warning.)

A: Just change your loop declaration to
for (Map.Entry<String, Class<?>> entry : connectionRepository.entrySet()) {

You've got this error because you use parametrised Class as a raw type. Here you can read about generics and wildcards. You can use Class<?> and avoid this error. But cast to CWSConnection is still required. You can avoid it by owning a Map<String, Class<CWSConnection>> instead of Map<String, Class<?>>.

A: The method
Class.newInstance()

calls the default constructor of the class. But I don't think this help you with the warnings, because your Class is still a raw type.


text:
Q: How does the way we define cos or tan have anything to do with degrees of the angle?
So sine of angle $A$ is just a ratio. It is the ratio of the length of the opposite or perpendicular of angle $A$ and the hypotenuse.
Cosine of angle $A$ is also just a ratio. It is the ratio of the length of base of $A$ and the hypotenuse.
Tangent of angle $A$ is the ratio of the length of the perpendicular to $A$ and length of the base of $A$.
So far so good. These are just ratios.
Sine of $A$ makes sense since it determines how big angle $A$ is.
But the cosine of angle $A$ or tangent of $A$ is not intuitive to me.
For example in what way the length of base of $A$ and the hypotenuse's length affect the angle of $A$? Their length doesn't seem relevant to how many degrees it has. Same for tangent.
Can someone please help me on this?

A: Here's a somewhat different way to define these functions that might make the relationships to sides of triangles clearer.
Consider the unit circle with center $O$ and two rays from $O$ that intersect the circle at points $A$ and $B$, with an acute angle $\theta=\angle AOB$ between them, as shown below.

Instead of defining the trigonometric functions as ratios of sides of triangles, define them as the lengths of certain line segments as follows:

*

*$\sin\theta = \overline{BC}$, the altitude to $\overrightarrow{OA}$ from $B$.

*$\tan\theta=\overline{AD}$, the length of the segment tangent to the circle at $A$ that intersects $\overrightarrow{OB}$ at $D$.

*$\sec\theta=\overline{OD}$, the distance to the intersection of $\overrightarrow{OB}$ with the tangent to the circle at $A$.

The "co" functions are the lengths of the corresponding line segments drawn on the other side of $\overrightarrow{OB}$, using the ray $\overrightarrow{OE}$, which is perpendicular to $\overrightarrow{OA}$.
$\triangle{OCB}$ is congruent to $\triangle{BFO}$, so $\overline{BF}=\overline{OC}$. Moreover, $\overline{OB}=1$, so we have the familiar ratios of sides of a right triangle for the sine and cosine.
Now, $\triangle{OCB}$ and $\triangle{OAD}$ are similar, so $\overline{AD}:\overline{BC}::\overline{OA}:\overline{OC}$ and $\overline{OA}=1$, and we have $$\tan\theta=\overline{AD}={\overline{BC}\over\overline{OC}}={\sin\theta\over\cos\theta}.$$ From these same triangles and the previous equation we find that $$\sec\theta = {\tan\theta\over\sin\theta} = \frac1{\cos\theta}.$$
The remaining two functions can be related to $\triangle{OCB}$ and the other functions via similar considerations.
If we change the radius of the circle, it's clear that the lengths of all of these line segments change proportionally, i.e., the ratios of their lengths to the radius are constant across similar triangles. Since we're taking a radius as the hypotenuse of the triangle, this also means that their ratios to the hypotenuse are constant for a given angle, which leads to the more familiar definitions of these functions as ratios of sides of a right triangle.

A: Every right angle with have distinct sides a, b, and hypotenuse h, always with the condition $a^2 + b^2 = h^2$.  Each triangle with an (a,b,h) sides will have a distinct angle with with a one-to-one coorespondence between angle $\theta$ and the set of $(a/h, b/h, 1)$ where $(a/h, b/h, 1)$ represents a class of similar right triangles-- similar up to a scaling factor.
$a/h$ is unique to the angle.  We can that $sin$.  $b/h$ is unique to the angle we call that $cos$.  $a/b = (a/h)/(b/h)$ is also unique.  That is $tan$.
====
You say you understand that $A/H$ determines how big the angle is. But $B/H = \sqrt{1 - A/H}$ by the pythagorean theorem.  If one determines how big the angle is, the other has to also determine how big it is.
Also if you just flip the triangle sideways, the height becomes the base, and the base becomes the height.  So whatever was true about the height of one must be true about the base of the other.
Now if $A/H$ determines how big the angle is, so must $\frac{A/H}{\sqrt{1 - A/H}} = \frac{A/H}{B/H} = A/B = \tan$.


text:
Q: Maximal regular sequences of different length This question is Exercise 1.2.20 in the book: Winfried Bruns, H. Jürgen Herzog, Cohen-Macaulay Rings, Cambridge University Press, 1998.

Let $k$ be a field and $R=k[[X]][Y]$. Deduce that $X, Y$ and $1-XY$ are maximal $R$-regular sequences.

I can not get why $1-XY$ is a maximal $R$-regular sequence. How to check the maximal condition?

A: Since $R$ is an integral domain, it follows that $1-XY$ is a non-zerodivisor in $R$. From this topic we know that $(1-XY)$ is a maximal ideal in $R$, so $1-XY$ can't be extended to an $R$-sequence since $(1-XY,a)=R$ for any $a\in R$, $a\notin(1-XY)$.


text:
Q: PHP Not catching ajax request I am having request like this:
$(function(){
    $("#novaProfaktura").click(function(){
        $.ajax({
          type: "POST",
          url: "../Pages/Program.php",
          data: { action: "testing" },
          success: function()
          {
              alert("Ajax done"); //Testing purpose
          }
        });
        location.reload();
    });
});

And then in my body I have php like this:

    <?php
    echo("Php running
");
    if($_SERVER['REQUEST_METHOD'] == 'POST')
    {
        echo("Post running
");
        if($_POST['action'] = "testing")
        {
            echo("Action running
");
        }
    }

    ?>

What I am getting from this is alert message so I assume ajax is set up properly and getting Php running but it doesn't pass if($_SERVER['REQUEST_METHOD'] == 'POST'
As you can see jQuery code is running on div click.
What am I doing wrong?
EDIT: I have used function(data) and it seems to work BUT it doesn't return only echoed data but WHOLE page with echo. I used document.write() and it rewrite whole page but how to get particular echo value?

A: Answer for this was to instead of this:
success: function()
{
    alert("Ajax done"); //Testing purpose
}

use this:
success: function(data)
{
    alert("Ajax done"); //Testing purpose
    document.getDocumentById('emptyDiv').innerHTML = data;
}

Now as data you are getting all HTML text from document you are running function from so instead of url: "../Pages/Program.php" I used separated file url: "../Php/Testing.php" and inside that file I have
 only this code:
<?php
    echo("Testing");
?>

A: $_POST['action'] = "testing"

This is variable assignment
$_POST['action'] == "testing"

This is comparison. You want this.
$_POST['action'] === "testing"

This is better because it's type matching too, it must be a string.


text:
Q: Groovy type conversion In Groovy you can do surprising type conversions using either the as operator or the asType method. Examples include
Short s = new Integer(6) as Short
List collection = new HashSet().asType(List)

I'm surprised that I can convert from an Integer to a Short and from a Set to a List, because there is no "is a" relationship between these types, although they do share a common ancestor.
For example, the following code is equivalent to the Integer/Short example in terms of the
relationship between the types involved in the conversion
class Parent {}
class Child1 extends Parent {}
class Child2 extends Parent {}

def c = new Child1() as Child2

But of course this example fails. What exactly are the type conversion rules behind the as operator and the asType method?

A: I believe the default asType behaviour can be found in: org.codehaus.groovy.runtime.DefaultGroovyMethods.java
org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.java.
Starting from DefaultGroovyMethods it is quite easy to follow the behavior of asType for a specific object type and requested type combination.

A: According to what Ruben has already pointed out the end result of:
Set collection = new HashSet().asType(List)

is
Set collection = new ArrayList( new HashSet() )

The asType method recognizes you are wanting a List and being the fact HashSet is a Collection, it just uses ArrayList's constructor which takes a Collection.
As for the numbers one, it converts the Integer into a Number, then calls the shortValue method.
I didn't realize there was so much logic in converting references/values like this, my sincere gratitude to Ruben for pointing out the source, I'll be making quite a few blog posts over this topic.


text:
Q: How to compile Tensor Flow with SSE and AVX instructions on Windows? With the latest version of Tensor Flow now on windows, I am trying to get everything working as efficiently as possible. However, even when compiling from source, I still can't seem to figure out how to enable the SSE and AVX instructions.
The default process:
https://github.com/tensorflow/tensorflow/tree/r0.12/tensorflow/contrib/cmake
has no mention of how to do this.
The only reference I have found has been using Google's Bazel:
How to compile Tensorflow with SSE4.2 and AVX instructions?
Does anyone know of an easy way to turn on these advanced instructions using MSBuild? I hear they give at least a 3X speed up.
To help those looking for a similar solution, this is the warning I am currently getting looks like this:
https://github.com/tensorflow/tensorflow/tree/r0.12/tensorflow/contrib/cmake
I am using Windows 10 Professional on a 64 bit platform, Visual Studio 2015 Community Edition, Anaconda Python 3.6 with cmake version 3.6.3 (later versions don't work for Tensor Flow)

A: Well, I tried to fix that, but I am not sure if it really worked.
In CMakeLists.txt you will find the following statements:
if (tensorflow_OPTIMIZE_FOR_NATIVE_ARCH)
  include(CheckCXXCompilerFlag)
  CHECK_CXX_COMPILER_FLAG("-march=native" COMPILER_OPT_ARCH_NATIVE_SUPPORTED)

On MSVC platform, the test failes because MSVC doesn't support -march=native flag. I modified the statements like below:
if (tensorflow_OPTIMIZE_FOR_NATIVE_ARCH)
  include(CheckCXXCompilerFlag)
  CHECK_CXX_COMPILER_FLAG("-march=native" COMPILER_OPT_ARCH_NATIVE_SUPPORTED)
  if (COMPILER_OPT_ARCH_NATIVE_SUPPORTED)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -march=native")
  else()
    CHECK_CXX_COMPILER_FLAG("/arch:AVX" COMPILER_OPT_ARCH_AVX_SUPPORTED)
    if(COMPILER_OPT_ARCH_AVX_SUPPORTED)
      set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /arch:AVX")
    endif()
  endif()
endif()

By doing this, cmake would check if /arch:AVX is available and use it. Accordinf to MSDN and MSDN, SSE2 support is enabled by default for x86 compiling but not available for x64 compiling. For x64 compiling you can choose to use AVX or AVX2. I used AVX above because my CPU only supports AVX, youcan try AVX2 if you have a compatible CPU.
By compiling use the above CMakeLists.txt, the compiling preocedure was much slower than official release, and warning about 'AVX/AVX2' disappeared, but warning about SSE/SSE2/3/4.1/4.2 still exists. I think these warnings can be ignored because there's no SSE support for x64 MSBuild.
I am testing the new pip package now. It maybe faster than before, but I don't want to write a new benchmark ...
Any one who is interested in this, please test if the new package is really faster.
I did all these on the lasted git master branch, 2017-3-12. The pip package name shows that it was tensorflow 1.0.1

A: I think you would have to add /arch:avx2 to compiler flags.
One way to do it is to modify your CMakeCache.txt in your build folder. Looking for a line CMAKE_CXX_FLAGS:STRING and modify it to

CMAKE_CXX_FLAGS:STRING=/DWIN32 /D_WINDOWS /W3 /GR /EHsc /arch:AVX2 /fp:fast

However, according to this issue on github. /arch:avx2 is broken at the moment (at HEAD).

A: Tensorflow make a mistake on flag "tensorflow_WIN_CPU_SIMD_OPTIONS".
It is a Flag, not a Boolean.
Before Fix Image
After Fix Image

How to Fix it
"Tensorflow-github/tensorflow/contrib/cmake/CMakeLists.txt" Line 34,there is:
option(tensorflow_WIN_CPU_SIMD_OPTIONS "Enables CPU SIMD instructions")

Replace it wtih
set(tensorflow_WIN_CPU_SIMD_OPTIONS "/arch:AVX" CACHE STRING "Enables CPU SIMD instructions" )

Then, clear the cmake cache (location), and reconfigure.
You will find tensorflow_WIN_CPU_SIMD_OPTIONS is a Flag with Input area instead of checkbox.

tensorflow_WIN_CPU_SIMD_OPTIONS
"/arch:AVX" or "/arch:AVX2" is available


text:
Q: What Are The Consequences of Using "Deprecated Code" In Flutter? I recently upgraded to Flutter 2.0. I have dozens of Flatbuttons that are now deprecated. It's going to take me a few days to fix them all. What are the consequences of shipping an update before then with deprecation warnings? The app still builds and runs fine.

A: Basically this code will be deleted in future releases of flutter/flutter packages. Most of the time, api's get deprecated when a bug that requires a completely new implementation that will break compatibility or a better implementation that will break compatibility.
Therefore, you can use deprecated code but you should be very careful as they are not maintained and might stop working or deleted in the future. So as long as you are not updating versions you should be fine but it is highly unadvisable.

A: The problem is that your code will be updated and the flutter will no longer support this widget.
But flutter 2.0 has a tool to help with that. Run the command on your terminal to see what has been depreciated and needs to be updated.
dart fix --dry-run

And execute this other command for fix the depreciated items.
dart fix --apply

For more details about fix, click here


text:
Q: gradle publishing project-version-PLAIN.war file instead of project-version.war When I run "gradle build", it generates a build/libs/project-version.war file which is able to run by itself with "java -jar" command. But when I run "gradle artifactoryPublish", it saves on the artifactory repository a "project-version-plain-war" file which does not have tomcat embedded.
I am following this instruccions https://www.jfrog.com/confluence/display/JFROG/Gradle+Artifactory+Plugin
The lines added to the gradle.build are something like this:
plugin "maven-publish"
plugin "com.jfrog.artifactory"
artifactory {
...
}

subprojects {
  plugin "war"
  group = group
  version = version

  publishing {
    publications {
      MavenPublication(MavenPublication) {
        from components.web
      }
    }
    repositories{
      maven { url "https://artifactory-server" }
    }
  }
}

help is appreciated

A: Using from components.web means that you are publishing the artifact produced by the war task. You need to publish the artifact produced by the bootWar task. You can do so by changing the publication to use artifact bootWar instead:
publishing {
  publications {
    MavenPublication(MavenPublication) {
      artifact bootWar
    }
  }
  repositories{
    maven { url "https://artifactory-server" }
  }
}

This is described in the reference documentation for Spring Boot's Gradle plugin.


text:
Q: keep getting message "Bot profile pictures should be PNG and less than 30kB" while creating a new bot I'm trying to add Skype channel to my bot in bot framework.
I followed the instruction and finished the following 2 steps:
1. Open the Microsoft Developer Portal and create a new app. Note your Application ID.
2. Press Generate Password to get an Application Secret.
Now I'm stuck at the 3rd step:
3. Sign in to the Skype Bot Portal using your Microsoft Account, click My Bots, and register a new bot using your Application ID.
https://developer.microsoft.com/en-us/skype/bots
Actually I have my logo fitting the criteria, but it still prompt the error message "Bot profile pictures should be PNG and less than 30kB" so that I cannot create the skype bot. Does anyone have similar experience?

A: Got the same problem. In my case it helped to convert image from RGBA to RGB.
It can for instance be done via Imagemagick's convert utility:
# Okay, your icon is in RGBA
$ file logo.png
logo.png: PNG image data, 150 x 150, 8-bit/color RGBA, non-interlaced

# Convert it
$ convert logo.png +matte logo-rgb.png

# And it's in RGB
$ file logo-rgb.png
logo-rgb.png: PNG image data, 150 x 150, 8-bit colormap, non-interlaced

A: I was having same issue. I did a "save for web" in photoshop and chose "preset: PNG-24"
That fixed it for me.


text:
Q: Condition must have static type of bool I am not able to use a future bool here. Is there any way I can use a future bool in this type of condition, or is there a better way to do this?
 Widget _buildRow(String pair) {

    final Future<bool> alreadySaved = DBHelper.getAllEmployees().then((value) => value.contains(pair));
    print("Already saved $alreadySaved");
    print(pair);
    return FutureBuilder(
      future: DBHelper.getAllEmployees(),
      builder: (context, AsyncSnapshot<List<FavrtTableModel>> snapshot) =>
      snapshot.connectionState == ConnectionState.waiting ? Center(
        child: Icon(Icons.more_horiz),
      ):IconButton(
        icon: new  Icon(
          alreadySaved ? Icons.favorite : Icons.favorite_border,
          color:alreadySaved? Colors.red : Colors.white,
        ),onPressed: (){
        setState(() {
          if (alreadySaved) {
            _saved.remove(pair);
            _deleteEmployee(pair);
          } else {
            _saved.add(pair);
            _insert(pair);

          }
        });
      },
      ),
    );
  }

A: Use in initState() like
 bool alreadySaved = false;

  @override
  void initState() {
    super.initState();
    String pair = "pair_value";
    DBHelper.getAllEmployees().then((value) {
      setState(() {
        alreadySaved = value.contains(pair);
      });
    });
  }


text:
Q: How To Hide Add Through Javascript I have write a script which hide the ads but they are still running on the background but not displaying.
All i need is little bit of help through which i can fix this

// in the area advertisement code will be posted

through this add running in the header. but showing i want to hide but they should still run in the background

A: write position:relative; instead of display:relative;


text:
Q: NestJS - typeorm - OneToOne onDelete CASCADE For a project i need the OneToOne relationship of Typeorm.
This project is based on NestJS and Postgresql.
With the following two entities:
@Entity()
export class Order {
    @PrimaryColumn()
    id: number;

    @OneToOne(() => OrderPaymentDetails, { cascade: true, onDelete: 'CASCADE' })
    @JoinColumn()
    payment_details: OrderPaymentDetails
}

and
@Entity()
export class OrderPaymentDetails {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    description: string
}

The desired behavior is as follows: When I delete an Order entity, I want the associated OrderPaymentDetails entity to be deleted too.
When i save a command in the database, there is no problem, but when i delete an order, the associated OrderPaymentDetails is not deleted either.
If i go the other way and delete the OrderPaymentDetails, the associated order is deleted.
What I tried:

*

*I tried to put the onDelete: 'cascade' field on the OrderPaymentDetails entity.

*I tried with OneToMany, ManyToOne and ManyToMany relationships.

*I tried to add an Order field in the OrderPaymentDetails entity.

But none of these solutions work.
Does anyone have a solution for me ?
Thomas


text:
Q: generateDataKey error Signature expired on AWS KMS? I am working with my client so I cloned git repo and built application which use AWS KMS to generate data key.
All is works well on live server but when I got failed on my local environment.
Here is code snippet and result of error.
const AWS = require('aws-sdk');
AWS.config.update({region:'eu-central-1'});
const kms = new AWS.KMS({ apiVersion: '2014-11-01' });

kms.generateDataKey({
 KeyId: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
 KeySpec: 'AES_256',
}).promise()
.catch(err => {
 console.error('generateDataKey error', err.message, err.stack);
 throw err;
})
.then(data => {
 console.log(data);
});

Is there a way to fix this error?

"GenerateDataKey error Signature expired...."

A: When you send a request signed using the AWS SigV4 protocol (to KMS or any other AWS service), the requests include a timestamp from when the signature was generated. The tolerance is 5 minutes. This mechanism is in place to make replay attacks harder (they essentially have a smaller window to be peformed). More information here.
Since the same request is working fine on your server, but failing locally, I think the clock on your local workspace is off by more than five minutes.


text:
Q: I can't parsed my google 'local state address' variable to news api url was already obtain the user address through geocoding reverse, but somehow the 'state' variable can't parsed to the news api url. The getWeatherData function works well since it was 'researched' and 'inspired' from someone. But the for getNewsData function I can't parsed the address variable into the url. Please help guys.
  $(document).ready(function getWeather() {

  var lat;
  var lon;
  var state;
  var timevar;

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(success, error);

  } else {
    alert("Geolocation services are not supported by your web browser.");
  }

  function success(position) {
    lat = position.coords.latitude;
    lon = position.coords.longitude;

    timevar = new Date().toISOString().slice(0,10);
    // var state;

    var reversegeocodingapi = "https://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lon+"&key=mykey";
    $.getJSON(reversegeocodingapi, function(place) {
      for (var i=0; i<place.results[0].address_components.length; i++) {
        if (place.results[0].address_components[i].types[0]==="locality") {
          var city = place.results[0].address_components[i].long_name;
          $("#city").html(city.toUpperCase());
        }
        if (place.results[0].address_components[i].types[0]==="administrative_area_level_1") {
          var state = place.results[0].address_components[i].long_name;
          $("#state").html(state.toUpperCase());
          }
      }
    }); //end getJSON
    getWeatherData(lat, lon);
    getNewsData(state,timevar);
  } //end success

  function error() {
    var alerted = localStorage.getItem('alerted') || '';
    if (alerted != 'yes') {
     alert("Sorry, I don't know where you are, abort local news/weather service.");
     localStorage.setItem('alerted','yes');
    }

  }

  function getWeatherData(latitude, longitude) {
    var weatherapiurl = "https://api.forecast.io/forecast/mykey/"+lat+","+lon+"?callback=?"
    $.getJSON(weatherapiurl, function(weatherdata) {
      var tempf = Math.round(weatherdata.currently.temperature);
      $("#temp").html(tempf + "°");
      var tempc = Math.round(((weatherdata.currently.temperature)-32)/(9/5));
      var feelslikef = Math.round(weatherdata.currently.apparentTemperature);
      $("#feels-like").html("Feels Like: " + feelslikef + "°F");
      var feelslikec =
      ...........
      ...........
      });//end f click
    }); //end getJSON
  }; //end getWeatherData

  function getNewsData(localstate,date0,date1) {

    // timevar = new Date().toISOString().slice(0,10);
    var url = 'https://newsapi.org/v2/everything?q='+state+'&from='+timevar+'&to='+timevar+'&sortBy=popularity&apiKey=mykey/'+'?callback=?';
    // var url = 'https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=mykey';

    var xhttp = new XMLHttpRequest();

    xhttp.onreadystatechange = function() {
        if ( this.readyState == 4 && this.status == 200 ) {
            var data = JSON.parse(xhttp.responseText).articles;

            console.log(data);

            var articles = data.map(mapToArticle);
            var contentDiv = document.getElementById('content');

            contentDiv.innerHTML = createTemplate(articles);
        }
    }

    xhttp.open("GET", url, true);
    xhttp.send();

    function mapToArticle(item) {
        return {
            url: item.url,
            title: item.title,
            author: item.author,
            date: item.publishedAt,
            img: item.urlToImage ? item.urlToImage : null,
            description: item.description
        };
    }

    function formatTime(timestr) {
      return timestr.substr(0, 10);
    }

    function createTemplate(articles) {
        return articles.reduce(function(tmpl, article) {
            tmpl += `

${article.title}

${formatTime(article.date)}

by ${article.author}

${article.description}

                        read more

            `;

            return tmpl;
        }, '');
    }
  }

}); //end ready

A: getJSON is an asynchronous call yet you are trying to use the result of it outside the callback meaning that you are trying to access the state variable before anything has been assigned to it. Just move you function calls inside the callback and you should be right.
$.getJSON(reversegeocodingapi, function(place) {
  for (var i=0; i<place.results[0].address_components.length; i++) {
    if (place.results[0].address_components[i].types[0]==="locality") {
      var city = place.results[0].address_components[i].long_name;
      $("#city").html(city.toUpperCase());
    }
    if (place.results[0].address_components[i].types[0]==="administrative_area_level_1") {
      var state = place.results[0].address_components[i].long_name;
      $("#state").html(state.toUpperCase());
      }
  }
  getWeatherData(lat, lon);
  getNewsData(state,timevar)
}); //end getJSON


text:
Q: UIWebView stringByEvaluatingJavaScriptFromString wrap tag with other tag Let's say I have an HTML like this:

<form>
<input type="button"  id="Signature8"  pdfFieldName="Signature8"  onclick="document.location='pdz://signatureTapped?name=Signature8'" />
</form>

and I want to replace it programmatically with

<form>

<input type="button"  id="Signature8"  pdfFieldName="Signature8"  onclick="document.location='pdz://signatureTapped?name=Signature8'" />

</form>

in Objective-C with a UIWebView. What I did so far, is come up with this:
-(void) injectCode:(NSString*) code intoWebView:(UIWebView*) webView withEndCode:(NSString*) endCode {
  NSString* innerhtml = [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.forms[0].%@.outerHTML", self.identifier]];
  NSString* newCode = [NSString stringWithFormat:@"document.forms[0].%@.outerHTML=%@%@%@", self.identifier, code, innerhtml, endCode];
  [webView stringByEvaluatingJavaScriptFromString:newCode];
  NSLog(@"%@", [webView stringByEvaluatingJavaScriptFromString:@"document.body.outerHTML"]);
}

which should be called like this:
  [f injectCode:[NSString stringWithFormat:@"", f.identifier, f.identifier] intoWebView:self.webView withEndCode:@""];

(whereas f is an object that contains the name, identifier, etc. of that Signature8 field).
The problem is: this doesn't work. When I debug through it, I can see innerhtml filled, I can see that newCode is actually correct (to me at least) and I thought that the line that assigns outerHTML with newCode and all that should replace the whole HTML accordingly. To verify, I logged it out to the console. Yeah.. nothing changed at all.
Can anyone tell me what I'm doing wrong here? I cannot use jQuery or any other framework really, as the code should get its HTML forms from third parties and they do not have to use jQuery or anything like that.

A: You are just missing the quotes around the new html:
NSString* newCode = [NSString stringWithFormat:@"document.forms[0].%@.outerHTML=\"%@%@%@\";", self.identifier, code, innerhtml, endCode];

Remember outerHTML is expecting a string.

A: Well unfortunately not, but I found a solution with a proxy that can modify the HTML on the fly before I get it. Works as well :-)


text:
Q: GetOpenFileName function in ms project VBA I'm trying to use the GetOpenFileName function, in vba for ms project. Is it available only in excel? no option to use it in ms project?
Thanks.

A: I had the same issue apparently the "GetOpenFineName" function works in Excel but is not supported in MS Projects. You will have to write it yourself.
To make it easier, below you can find code you have to copy past at the top of your program in MS project. Then you can use GetOpenFileName in the code you are writing yourself in your program.
Good luck.
Private Type OPENFILENAME
    lStructSize As Long
    hwndOwner As Long
    hInstance As Long
    lpstrFilter As String
    lpstrCustomFilter As String
    nMaxCustFilter As Long
    nFilterIndex As Long
    lpstrFile As String
    nMaxFile As Long
    lpstrFileTitle As String
    nMaxFileTitle As Long
    lpstrInitialDir As String
    lpstrTitle As String
    Flags As Long
    nFileOffset As Integer
    nFileExtension As Integer
    lpstrDefExt As String
    lCustData As Long
    lpfnHook As Long
    lpTemplateName As String
End Type

Private Const OFN_ALLOWMULTISELECT = &H200
Private Const OFN_CREATEPROMPT = &H2000
Private Const OFN_EXPLORER = &H80000
Private Const OFN_FILEMUSTEXIST = &H1000
Private Const OFN_HIDEREADONLY = &H4
Private Const OFN_NOCHANGEDIR = &H8
Private Const OFN_NODEREFERENCELINKS = &H100000
Private Const OFN_NONETWORKBUTTON = &H20000
Private Const OFN_NOREADONLYRETURN = &H8000
Private Const OFN_NOVALIDATE = &H100
Private Const OFN_OVERWRITEPROMPT = &H2
Private Const OFN_PATHMUSTEXIST = &H800
Private Const OFN_READONLY = &H1
Private Const OFN_SHOWHELP = &H10

Private Declare Function GetOpenFileNameA Lib "comdlg32.dll" _
    (OFN As OPENFILENAME) As Boolean

Private Declare Function GetSaveFileNameA Lib "comdlg32.dll" _
    (OFN As OPENFILENAME) As Boolean

Private Const ALLFILES = "All Files"

Function MakeFilterString(ParamArray varFilt() As Variant) As String
    ' Creates a filter string.
    ' Returns "" if there are no arguments.
    ' Expects an even number of argumenten (filter name, extension).
    ' Adds *.* if the number of arguments is odd.

    Dim strFilter As String
    Dim intRes As Integer
    Dim intNum As Integer

    intNum = UBound(varFilt)
    If intNum <> -1 Then
        For intRes = 0 To intNum
            strFilter = strFilter & varFilt(intRes) & vbNullChar
        Next
        If intNum Mod 2 = 0 Then
            strFilter = strFilter & "*.*" & vbNullChar
        End If

        strFilter = strFilter & vbNullChar
    End If

    MakeFilterString = strFilter
End Function

Private Sub InitOFN(OFN As OPENFILENAME)
    With OFN
        ' Initialize fields
        .hwndOwner = 0
        .hInstance = 0
        .lpstrCustomFilter = vbNullString
        .nMaxCustFilter = 0
        .lpfnHook = 0
        .lpTemplateName = 0
        .lCustData = 0
        .nMaxFile = 511
        .lpstrFileTitle = String(512, 0)
        .nMaxFileTitle = 511
        .lStructSize = Len(OFN)
        If .lpstrFilter = "" Then
            .lpstrFilter = MakeFilterString(ALLFILES)
        End If
        .lpstrFile = .lpstrFile & String(512 - Len(.lpstrFile), 0)
    End With
End Sub

Private Sub ProcessOFN(OFN As OPENFILENAME)
    With OFN
        .lpstrFile = Left$(.lpstrFile, InStr(.lpstrFile, vbNullChar) - 1)
    End With
End Sub

Private Function OpenDialog(OFN As OPENFILENAME) As Boolean
    ' Display the Open dialog.
    Dim intRes As Integer
    InitOFN OFN
    intRes = GetOpenFileNameA(OFN)
    If intRes Then
        ProcessOFN OFN
    End If
    OpenDialog = intRes
End Function

Private Function SaveDialog(OFN As OPENFILENAME) As Boolean
    ' Display the Save As dialog.
    Dim intRes As Integer
    InitOFN OFN
    intRes = GetSaveFileNameA(OFN)
    If intRes Then
        ProcessOFN OFN
    End If
    SaveDialog = intRes
End Function

Private Function GetOpenFileName(Optional FileFilter As String, Optional FilterIndex As Long, Optional Title As String = "Select a File") As String
    Dim OFN As OPENFILENAME
    With OFN
        If FileFilter <> "" Then
            .lpstrFilter = Replace(FileFilter, ",", vbNullChar) & vbNullChar
        End If
        .nFilterIndex = FilterIndex
        .lpstrTitle = Title
    End With
    If OpenDialog(OFN) Then
        GetOpenFileName = OFN.lpstrFile
    End If
End Function

Private Function GetSaveAsFileName(InitialFileName As String, Optional FileFilter As String, Optional FilterIndex As Long, Optional Title As String = "Select a File") As String
    Dim OFN As OPENFILENAME
    With OFN
        .lpstrFile = InitialFileName
        If FileFilter <> "" Then
            .lpstrFilter = Replace(FileFilter, ",", vbNullChar) & vbNullChar
        End If
        .nFilterIndex = FilterIndex
        .lpstrTitle = Title
    End With
    If SaveDialog(OFN) Then
        GetSaveAsFileName = OFN.lpstrFile
    End If
End Function


text:
Q: I am using Windows 7 and I get a 169.254.x.x ip address Can you help me guys with my problem? I am using Windows 7 and I get 169.254.x.x IP address. What would be the problem? Can you please gave me a step-by-step procedure?
Here's what I have tried:

*

*ipconfig /all got us a 169.254.x.x ip address and no default gateway

*ipconfig /release gave us the same number

*ipconfig /renew failed

*also tried to check cable and done hard reset for both modem and router, still not working

A: A 169.254.x.x means the computer has physical ethernet Link, but cannot get an IP address from your router. You can try following things:

*

*use another ethernet cable

*try use wifi if available

*use another computer or smartphone to check if the router is working, and check router log for errors

*if you know the IP of the router, set a static IP on your computer.

A: You are set up for a DHCP server but the DHCP server was not found so your system defaults to Automatic Private IP Addressing (APIPA). Normally your router would provide your DHCP IP addressing unless you have a static IP. If your router was provided by your ISP then I suggest you contact your Internet Provider.

A: Go into both the system that is getting the 169.X.X.X address and the router and set yourself a private address, because what it is is the DHCP isn't working. I've run into this before and the only way I know to fix it without tossing the router is to set a static for the PC in question.

*

*To do so first go into the router and see what kind of addressing you are using. Most have a 192.168.1.x addressing schema.

*There should be a place in the router to set up static routes, usually under "LAN IP Setup" or the like. Sorry I can't be more precise but every router is different.

*Once you have set up a static route for that system you then go Start > Control Panel > Network and Sharing Center.

*On the left you'll see "Change Adapter Settings", click on this.

*Once you are on the screen with your adapter right click and choose properties.

*In this screen choose "Internet Protocol Version 4 (TCP/IP V4)" and hit properties. pick "choose the following address" and input the address you chose on the router, the subnet will be 255.255.255.0 if its a 192 address and the gateway will be the address of the router. For the DNS you an use the one given by the ISP or any of the free ones, if you need a couple Comodo Secure DNS is 195.46.39.39 and OpenDNS is 208.67.222.222.
There you go, hope this helps.

A: Like others have mentioned, you computer can get an address from your DHCP server.
To overcome this challenge, you can set a static IP or try other methods as posted here.If you are sure your router is working fine and doesn't need a reset, You can try this. The idea is to make your computer able to send dhcp request message once it connects to a network.

*

*Disconnect from your WiFi network and enter the following commands in
your terminal (run as admin same as elevated command prompt)

*Type ipconfig /flushdns #This purges the DNS resolver cache.

*Type ipconfig /registerdns #This Refreshes your DHCP leases and
re-registers DNS names. (Note you are still offline)

*Then Turn on Wi-Fi or plug in LAN cable. if it does not work, start
with ipconfig /release and repeat the two commands above.

A: I found after checking cables, among other things it turned out despite the fact I could wirelessly connect to my router, a router reset actually resolved the problem.
A dead giveaway that the issue was the router was that even when setting a static ip I couldn't ping my router using LAN only. Another dead giveaway was that on the router I specifically dedicated an ip to the LAN connection outside of my DHCP range. EG: DHCP should have returned the dedicated IP address, but instead was giving the junk address, whereas my wireless card using DHCP was retrieving it's own dedicated address perfectly fine.
Connect to your router (possibly w/ another computer) and dedicate an IP address to each device you'd like to test (outside of the DHCP range so you'll have a definitive confirmation DHCP worked and recognized your device's MAC address), similarly do the same w/ a wireless device, then make sure all of them are using DHCP. If some wireless vs wired device is working where another is not, (EG DHCP is definitely working) your router may be at fault.
If you find this is the case, know your frustration isn't in vain because even if you manually configured the right IP to start with your router effectively was a brick the entire time, no amount of software steps would've solved the issue.
Note: as far as I can tell it seems other people with this sort of issue complain about cabling, which is why I brought it up. Whereas for me it turned out my router was on the fritz, I have no idea but it could be a bad cable/port that could cause this.
If worst comes to worst, you may need to find an old router to see if it has the same issue.
If the absolute worst comes to worst, you may need a new lan card...
TLDR: 169.254.x.x are addresses given when your device fails to retrieve an ip address from a DHCP server (your router). EG. If you've gotten so far as to find out you're being handed a 169.254.x.x address, you're more than likely having a hardware problem, either

*

*find out if a wireless device or card works w/ DHCP enabled (your router for some reason is no longer handling DHCP requests via lan or...potentially more like in my case) or

*set a static ip and see if you can bypass the issue by ignoring
DHCP, you can avoid ip collisions w/ arp -a (you may need a second device).

A: On the modem when I added a new set of Subnet Pools covering additional IPs, this problem solved for my Lenovo T420 with Windows7

A: Run anti-malware software such as Malwarebytes Anti-malware.
Be as an administrator in the command prompt window, type the following:-
1) ipconfig /release (this command may or may not fail, proceed even if it fails)
2) netsh winsock reset
3) netsh int ip reset
4) Reboot your computer.
Good luck!


text:
Q: OpenSSH Server start failed with result 'timeout' I need a second openssh server source modified and running on debian.
The modifications I made on the source code are not really relevant, anyway they amplify the logs.
I compiled the modified openssh-7.4p1 with
./configure --prefix=/opt --enable-pam --with-pam
make ; make install

Then I created /lib/systemd/system/ssh-mod.service :
[Unit]
Description=OpenBSD Secure Shell server modified to log
After=network.target auditd.service sshd.service
#ConditionPathExists=!/opt/etc/sshd-mod_not_to_be_run
ConditionPathExists=!/etc/ssh/sshd_not_to_be_run

[Service]
EnvironmentFile=-/opt/etc/default/ssh
ExecStart=/opt/sbin/sshd -D -f /opt/etc/sshd_config $SSHD_OPTS
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure
RestartPreventExitStatus=255
Type=notify

[Install]
WantedBy=multi-user.target
Alias=sshd-mod.service

And /opt/etc/sshd_config is a standard ssh configuration file with the following lines:
Port 22
LogLevel INFO
ChallengeResponseAuthentication no
UsePAM yes
PrintMotd no
PidFile /var/run/sshd-mod.pid

Now I launched the service with:
$ sudo systemctl start ssh-mod

the command loops indefinetly, so I wait until the error message:
Job for ssh-mod.service failed because a timeout was exceeded.
See "systemctl status ssh-mod.service" and "journalctl -xe" for details.

then I check the status:
$ sudo systemctl status ssh-mod

● ssh-mod.service - OpenBSD Secure Shell server modified to log
    Loaded: loaded (/lib/systemd/system/ssh-mod.service; enabled; vendor preset: enabled)
    Active: activating (start) since Mon 2017-09-04 10:19:50 UTC; 12s ago
  Main PID: 15701 (sshd)
     Tasks: 1 (limit: 4915)
    CGroup: /system.slice/ssh-mod.service
            └─15701 /opt/sbin/sshd -D -f /opt/etc/sshd_config

Sep 04 10:19:50 mymachine systemd[1]: ssh-mod.service: Service hold-off time over, scheduling restart
Sep 04 10:19:50 mymachine systemd[1]: Stopped OpenBSD Secure Shell server modified to log.
Sep 04 10:19:50 mymachine systemd[1]: Starting OpenBSD Secure Shell server modified to log...
Sep 04 10:19:50 mymachine sshd[15701]: Server listening on 0.0.0.0 port 22.
Sep 04 10:19:50 mymachine sshd[15701]: Server listening on :: port 22.

$ journalctl -xe

Sep 04 10:19:50 mymachine systemd[1]: ssh-mod.service: Start operation timed out. Terminating.
Sep 04 10:19:50 mymachine sshd[15549]: Received signal 15; terminating.
Sep 04 10:19:50 mymachine systemd[1]: Failed to start OpenBSD Secure Shell server modified to log.
-- Subject: Unit ssh-mod.service has failed
-- Defined-By: systemd
-- Support: https://www.debian.org/support
--
-- Unit ssh-mod.service has failed.
--
-- The result is failed.
Sep 04 10:19:50 mymachine systemd[1]: ssh-mod.service: Unit entered failed state.
Sep 04 10:19:50 mymachine systemd[1]: ssh-mod.service: Failed with result 'timeout'.
Sep 04 10:19:50 mymachine systemd[1]: ssh-mod.service: Service hold-off time over, scheduling restart
Sep 04 10:19:50 mymachine systemd[1]: Stopped OpenBSD Secure Shell server modified to log.
-- Subject: Unit ssh-mod.service has finished shutting down
-- Defined-By: systemd
-- Support: https://www.debian.org/support
--
-- Unit ssh-mod.service has finished shutting down.
Sep 04 10:19:50 mymachine systemd[1]: Starting OpenBSD Secure Shell server modified to log...
-- Subject: Unit ssh-mod.service has begun start-up
-- Defined-By: systemd
-- Support: https://www.debian.org/support
--
-- Unit ssh-mod.service has begun starting up.
Sep 04 10:19:50 mymachine sshd[15701]: Server listening on 0.0.0.0 port 22.
Sep 04 10:19:50 mymachine sshd[15701]: Server listening on :: port 22.

Actually the service results as 'activating' but I can login on port 22 (the other server is listening to another port), so the shell seems working.
I have no clue what is causing this, the logs are not so explicit.
What am I missing? Why is the service hung?
Please tell me if you need more informations.
I followed the steps on the RedHat documentation.

A: I'm seeing the same behavior on another systemd system (Ubuntu 16.04.3 LTS, but provided by an HPC vendor that may have made modifications.)
From what I can tell, the problem is that Type=notify, and sshd isn't or can't send notification messages using sd_notify(3) or similar to systemd.  So systemd never gets the message that it's started.
What I have done for now is to create an override in /etc/systemd/system/ssh.service (as a copy of /lib/systemd/system/ssh.service)  and change Type from notify to forking.  Then remove the -D from ExecStart, so sshd will fork its daemon.
Then systemctl daemon-reload, and restart ssh to make sure it's working.
The proper fix is to get the ssh service to work with Type=notify again, but I'm out of time for this today.  Hope this is helpful to someone.


text:
Q: Software raid mdadm not adding spare I just discovered the same problem on two brand new and identical servers installed only about 9 months ago. I was unable to write to the disk on both of them, because the system had marked it read-only. Logs indicated there was some sort of disk error on both.
Note that I'm running KVM with several guests on each of these servers. The guests were all running fine, but the problem was in the KVM host. This probably doesn't matter, but maybe it pertains. Both systems have only two drives with software raid1 and LVM on top. Each KVM guest has its own LVM partition as well.
Both systems were showing a degraded RAID1 array when looking at /proc/mdstat.
So I rebooted one of the systems, and it told me I needed to manually run fsck. So I did so. It appeared to fix the problems and a reboot brought the system back up normally. The same process worked on the 2nd server as well.
Next I ran mdadm --manage /dev/md0 --add /dev/sdb1 to add the failed drive back into the array. This worked fine on both servers. For the next hour or so, looking at /proc/mdstat showed progress being made on the drives syncing. After about an hour, one system finished, and /proc/mdstat showed everything working nicely with [UU].
However, on the other system, after about 1.5 hours, the system load skyrocketed and nothing was responsive. A few minutes later, everything came back. But looking at /proc/mdstat now shows the following:
root@bond:/etc# cat /proc/mdstat
Personalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [raid10]
md0 : active raid1 sda1[2] sdb1[1]
      293033536 blocks [2/1] [_U]

unused devices: <none>

As you can see, it appears to be no longer syncing. The percentage completed, time remaining, etc. is no longer show. However, running mdadm --detail /dev/md0 shows this:
root@bond:/etc# mdadm --detail /dev/md0
/dev/md0:
        Version : 00.90
  Creation Time : Mon Nov 30 20:04:44 2009
     Raid Level : raid1
     Array Size : 293033536 (279.46 GiB 300.07 GB)
  Used Dev Size : 293033536 (279.46 GiB 300.07 GB)
   Raid Devices : 2
  Total Devices : 2
Preferred Minor : 0
    Persistence : Superblock is persistent

    Update Time : Fri Sep 10 23:38:33 2010
          State : clean, degraded
 Active Devices : 1
Working Devices : 2
 Failed Devices : 0
  Spare Devices : 1

           UUID : 4fb7b768:16c7d5b3:2e7b5ffd:55e4b71d
         Events : 0.5104310

    Number   Major   Minor   RaidDevice State
       2       8        1        0      spare rebuilding   /dev/sda1
       1       8       17        1      active sync   /dev/sdb1

The bottom line seems to indicate that the spare is rebuilding. Why is it a spare? The system is reporting both devices as clean. It has stayed like this for hours. The drives are small and fast 300GB 10K RPM VelociRaptors, so I would think it would have sync'ed by now. Attempting to re-add says the device is busy:
root@bond:/etc# mdadm /dev/md0 --re-add /dev/sda
mdadm: Cannot open /dev/sda: Device or resource busy

Running dmesg on the "good" server shows this at the end:
[ 4084.439822] md: md0: recovery done.
[ 4084.487756] RAID1 conf printout:
[ 4084.487759]  --- wd:2 rd:2
[ 4084.487763]  disk 0, wo:0, o:1, dev:sda1
[ 4084.487765]  disk 1, wo:0, o:1, dev:sdb1

On the "bad" server, those last 4 lines are repeated hundreds of times. On the "good" server, they only show once.
Are the drives still syncing? Will this "rebuild" finish? Do I just need to be more patient? If not, what should I do now?
UPDATE:
I just rebooted, and the drive started syncing all over again. After almost 2 hours, the same thing happened as described above (still get a [_U]).  However, I was able to see the dmesg logs before the RAID1 conf printout chunks consumed it all:
[ 6348.303685] sd 1:0:0:0: [sdb] Unhandled sense code
[ 6348.303688] sd 1:0:0:0: [sdb] Result: hostbyte=DID_OK driverbyte=DRIVER_SENSE
[ 6348.303692] sd 1:0:0:0: [sdb] Sense Key : Medium Error [current] [descriptor]
[ 6348.303697] Descriptor sense data with sense descriptors (in hex):
[ 6348.303699]         72 03 11 04 00 00 00 0c 00 0a 80 00 00 00 00 00
[ 6348.303707]         22 ee a4 c7
[ 6348.303711] sd 1:0:0:0: [sdb] Add. Sense: Unrecovered read error - auto reallocate failed
[ 6348.303716] end_request: I/O error, dev sdb, sector 586065095
[ 6348.303753] ata2: EH complete
[ 6348.303776] raid1: sdb: unrecoverable I/O read error for block 586065024
[ 6348.305625] md: md0: recovery done.

So maybe the question I should be asking is "How do I run fsck on a spare disk in a raid set?"

A: I'm unclear on whether you actually replaced the failed drive(s)?  Because your symptoms would make sense to me if you'd re-added the faulty drive, in which case there's a good chance the drive has locked up.  If you did re-add the faulty drive, are there subsequent errors in /var/log/messages or dmesg?
(Incidentally, I'd strongly recommend against ever re-addeding a faulty drive to a RAID array.  If the fault corrupted data on the platter you may find that when you add it back to the array, the resync leaves the corrupted file on the disc, and next time you read the files, it'll be a crapshoot as to whether you get good or bad data, depending on which disk responds first; I have seen this happen in the wild.)

A: Using mdadm --details will list a drive as spare while it's rebuilding.  After rebuild is complete it will no longer show as spare.
[ 6348.303711] sd 1:0:0:0: [sdb] Add. Sense: Unrecovered read error - auto reallocate failed
[ 6348.303716] end_request: I/O error, dev sdb, sector 586065095
[ 6348.303753] ata2: EH complete
[ 6348.303776] raid1: sdb: unrecoverable I/O read error for block 586065024
[ 6348.305625] md: md0: recovery done.

The first line, states there was reallocation failure, and the data was not read.  The following three lines are pointing out that the data could not be read, and lists the sectors that are unreadable.
As Rodger pointed out, the drive is bad, don't re-add it.  It's never a good idea to re-add a drive that failed.  Pull the drive and replace it.  If you wish, run diagnostics on the failed drive but only after it's been pulled and replaced.

A: First- yes get rid of any disk that is throwing read errors that end up in the log file.  This means the bad block relocation has failed and/or the drive is close to dying.
I suggest to rescue your data you use a Linux rescue CD such as http://ubuntu-rescue-remix.org/ to use ddrescue.  This can do an image copy to a new disk's partition, and will do lots of retries etc to try to recover your partition. Mount a USB drive or another partition
mkdir /tmp/x && mount /dev/sdd1 /tmp/x

to hold the ddrescue log file- then you can stop the ddrescue (ctrl-C) and restart it later from the same point.
Make a partition on the new disk a bit bigger than the old disk. You don't have to use the whole disk!
Boot the rescue CD with "nodmraid" as a kernel boot parameter. If using ubuntu live CD then install RAID and LVM if you're using it
  apt-get install mdadm lvm2 gddrescue

you will need to be on the internet for this to work). Otherwise use the ubuntu rescue CD for the ddrescue step. I swapped between the rescue CD for ddrescue runs, and the live CD for the grub and fsck work.
Assuming /dev/sdb is your failing source disk, and /dev/sdx is your new disk, and /mnt/x is a USB key or a partition on another disk that has been mounted.  You need the ddrescue log file, really! As it tracks how ddrescue is going, and allows it to be interrupted.
As per http://www.forensicswiki.org/wiki/Ddrescue

  ddrescue --no-split /dev/sdb /dev/sdX imagefile /mnt/x/logfile

then

  ddrescue --direct --max-retries=3 /dev/sdb /dev/sdX /mnt/x/logfile

then

  ddrescue --direct --retrim --max-retries=3 /dev/sdb /dev/sdX /mnt/x/logfile

Don't be afraid to Ctrl-C the process if it is taking hours to recover a single sector.  Just go on to the next step (step 1 should succeed no matter what).  The last step tries to recover the last crumbs of usable data.
You will also have to do
  mdadm --create /dev/md99 --level-1 --raid-devices=2 missing /dev/sdX

to make a new RAID array using the new disk, this writes a new RAID superblock on the partition (in the last 64K to 128K at the end of the partition).
Remove your old failing disk /dev/sdb from the system so it is not visible to linux.
Make your source RAID disk accessible.  You may have to use the "nodmraid" parameter to the kernel booting kernel, as I had problems with the ubuntu rescue CD, and ended up using the Ubuntu live CD (10.4) where nodmraid is in F6 Options.  You should just need to use
 mdadm --assemble /dev/md99 /dev/sdX

Then fsck or do whatever check you need to do to the data on the md99 RAID array (I used vgscan then was able to see the LVM LVs to run the check against).  I use XFS for mythtv but xfs_check command crashed my system, but xfs_repair was OK.
Mount the /boot directory from your new /dev/sdX
  mount /dev/mapper/my_vg/root_lv /tmp/x

then put a new GRUB boot record on the new /dev/sdX RAID disk (only if you boot from RAID!)
  grub-setup -d /tmp/x/boot/grub /dev/sdX

now you have an (almost) bootable RAID array.  You may also do the setup using GRUB itself, or use dd to copy the first 446 bytes of /dev/sdb to /dev/sdX.  ONLY the first 446 bytes, the rest of the 1st sector is your partition table, which you will stuff up mightily if you copy more!  You may also have to do the same for the 1st sector in your partition /dev/sdX1 (say). Back up any sectors you are going to overwrite, also using dd.
If using grub2 and you're booting from RAID, you will find that the RAID array UUID has changed so your boot will fail.  Edit the boot command line (e in Grub startup panel) to remove splash and quiet, so you can see what is happening.  Then after the failed boot you are left in initramfs.
mdadm --assemble /dev/md99 /dev/sdX

then check /proc/mdstat to make sure the array is there. If it is then just "exit" and hopefully your GRUB boot stanza will work OK (mine was set to use LVM so it just found the LVs on the RAID device once there was any RAID device there, it just searched for the LV).  Once you are booted up then you are almost done.
The initrd image file (gzipped cpio file) contains a copy of mdadm.conf used during the boot process, visible and editable as /etc/mdadm/mdamdm.conf during the boot process. If you can get your system booted normally just update the initramfs using
  update-initramfs -u

If you can't get the system booted because of the mismatched UUID in the mdadm.conf file
Be aware that your destination device /dev/sdX may appear as /dev/sdY when you boot a different way (Grub, rescue, real boot).
By the way, unless you are using RAID5 and are really interested in block alignment, I'd use a partition for your RAID array, you don't have to use a whole disk (esp if you are replacing a 1TB disk with a 2TB one).  You can always add another partition and a 2nd RAID array later to use up the whole 2TB.
Phew! Done!


text:
Q: Couldn't import Django when launching test server When running the command:
python manage.py runserver

To launch a test server, I get the following error:
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?
Steps I took to get this error:
1) I downloaded the Django project from my Linux VPS (without the virtual environment). I am using Windows 10 on this current system.
2) I created a new virtual environment in that folder using:
virtualenv myprojectenv

3) The env was created successfully, I now have the following folders/files:
myproject
myprojectenv
static
manage.py

4) I activate the env (myprojectenv\scripts\activate), success - my commandline changes to
(myprojectenv) C:\ (path to my folder)
5) I install Django using
pip install django
Django successfully installed, when checking the version, it returns 2.1.1:
python -c "import django; print(django.get_version())
2.1.1

6) I go back to the main dir where manage.py is, I try to run the test server with
python manage.py runserver

And I get the error (specified above). So, what have I done wrong here? I have the env folder correctly in that directory, Django installed. It still can't find it.
I thought the problem may be with my Django files, but no. When I start a new project from the myprojectenv env using
django-admin startproject mysite

The mysite folder gets created - I go into that folder (where manage.py is) and I try to launch the test server again. It still can't find Django! Any help is appreciated.

A: --- make all of them in order
virtualenv example
source example/bin/activate
cd example
pip install django
django-admin.py startproject mysite
cd mysite
python manage.py runserver
--It have to work 100%


text: Q: Обернуть сайт. Heroku Подскажите куда копать нубу. Нужно чтобы определённый сайт на котором есть js  скрипты выполняющиеся на стороне клиента постоянно был открыт с моими параметрами. Что-то вроде постоянно открытой вкладки браузера,на моем сервере или на хероку.


text:
Q: How can I turning that number of string? public static void Main(string[] args)
{
    Console.WriteLine("Enter string: ");
    string st= Console.ReadLine();
    Console.WriteLine(Alpha(st));
}

public static string Alpha(string str)
{
    int[] nums = new int[str.Length / 2]; // 4 5 2
    string num = "";
    string nw = "";
    string harfler = " ";
    string[] harflerr = new string[str.Length / 2]; // A B C

    for(int i = 0; i < str.Length; i += 2)
    {
        harfler += str[i].ToString();
    }
    for(int i = 1; i < str.Length; i+=2)
    {
        num += str[i].ToString();
    }
    for(int i = 0; i < num.Length; i++)
    {
        nums[i] += num[i];
    }
    for(int i = 0; i < harflerr.Length; i++)
    {
        harflerr[i] += harfler[i];
    }
    for(int i = 0; i < harflerr.Length; i++)
    {
       for(int j = 0; j < nums[i]; j++)
        {
            nw += harflerr[i];
        }
    }

    return nw;
}

Output must be like:
"A4B5C2" ➞ "AAAABBBBBCC"

"C2F1E5" ➞ "CCFEEEEE"

"T4S2V2" ➞ "TTTTSSVV"

"A1B2C3D4" ➞ "ABBCCCDDDD"

Why doesn't nums [i] // for example return as many as 4 // in the nums [i] part.

A: I would suggest using regular expression for this because of two reasons. First is that what happens when user input something like A12B7 or A1BC4? Your approach will fail because you're assuming that every letter will have only one digit following it.
Second reason is pure readability. It's easier to filter everything out using regular expressions than doing it by hand, character by character.

So first define your regex like this one: (?'pair'[A-Za-z]{1}\d{0,})
Having this expression will retrieve pairs that have letter and possibly a number following. Then you can iterate through all of the pairs and just create new string for each.
string result = "";
foreach(string pair in pairs)
{
    char character = pair[0];
    int length = 1;
    if (pair.Length > 1)
    {
        length = int.Parse(pair.Substring(1));
    }
    result += new String(character, length);
}
Console.WriteLine(result);

You can test this online on rextester


text:
Q: insert value to next cell using vba I am trying to fetch data from a webpage. My VBA code is as below
m = 0
For Each htmlele1 In doc.getElementsByClassName("resultsbranch")
    m = m + 1
    companyname = htmlele1.getElementsByTagName("h2")
    Address = htmlele1.getElementsByTagName("span")
    If Address.getAttribute("itemprop") = "myaddress" Then
        Range("D" & i).Value = companyname.innerText + "," + Address.innerText
    End If
    Teliphone = htmlele1.getElementsByClassName("teldata")
    If Teliphone.getAttribute("itemprop") = "tel" Then
        Range("E" & i).Value = Teliphone.innerText
    End If
    'i = i + 1
    'Debug.Print i
Next

On the first iteration, values are get inserted to columns D,E
on second iteration I want to insert data To F,H .
On 3 rd iteration I,J
On 4th iteration K,L
So on up to nth iteration
How can i do this ?

A: Instead of:
Range("D" & i).Value
Range("E" & i).Value

Use:
Cells(i, (m*2 + 3)).Value
Cells(i, (m*2 + 4)).Value

Or use another counter... As you like... Hope that helps.


text:
Q: Getting data from node js module to server.js file I am trying to get data from a function in a node module, that returns a json object, and show the json object in a router in my server.js file.
I am trying to export it like this:
    // Export the function
    exports.getTweets = function() {
        var tweetResult = {};
        twitter.get(
            '/statuses/user_timeline.json',
            { screen_name: 'twitter', count: 5},
            function (error, tweets) {
                tweetResult = tweets;
            }
        );
        return tweetResult;
    };

And here is my server.js file, with the route that should return the json object
tweets      = require("./twitter_stream.js"),

// set up the route for the json object
app.get("/tweets.json", function (req, res) {
    console.log(tweets.getTweets());
});

I haven't been able to get anything but an empty object.

A: You need to pass a callback to the getTwitter function to receive the twitter result. The variable tweetResult is null when the  code  return tweetResult; is invoked.
Please check the code below to see how to use the callback in your code:
exports.getTweets = function(callback) {
        twitter.get(
            '/statuses/user_timeline.json',
            { screen_name: 'casperpschultz', count: 5},
            function (error, tweets) {
                //invoke the callback function passing the tweets
                callback(tweets);

            }
        );
    };

Code to invoke the getTweets function passing a callback function:
app.get("/tweets.json", function (req, res) {
    //invoke getTweets passing a callback function by parameter
    tweets.getTweets(function(tweets){
         console.log(tweets);
     });
});

Node.js works in an asynchronous way with callback, here is a good reference that explains it.


text:
Q: ng-click no funciona con ng-view he empezado a crear una pagina. tiene cabecera y main, el main carga las vistas y funciona perfectamente, pero quiero que cuando se carguen las vistas secundarias se esconda la cabecera, aquí el index:

    <link rel="stylesheet" href="css/estilo.css">
    <link rel="stylesheet" href="css/sistemas.css">
    <link rel="stylesheet" href="css/desarrollo.css">
    <link rel="stylesheet" href="css/personal.css">
    <link rel="stylesheet" href="css/profesional.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

y aquí el js:
var app = angular.module('app', [ 'ngRoute', 'ngAnimate']);
app.config(function($routeProvider, $locationProvider){
$locationProvider.hashPrefix('');
$routeProvider
    .when('/', {
        templateUrl: 'views/main.html'
    })
    .when('/sistemas', {
        templateUrl: 'views/sistemas.html'
    })
    .when('/desarrollo', {
        templateUrl: 'views/desarrollo.html'
    })
    .when('/profesional', {
        templateUrl: 'views/profesional.html'
    })
    .when('/personal', {
        templateUrl: 'views/personal.html'
    })
    .otherwise({
        redirectTo: '/'
    });
});

app.controller('mainController', function($scope){
$scope.showTitle = function() {
var ver = $scope.ver;
    if (ver == true) {
        ver=false;
    }
    else {
        ver=true;
    }
return ver;
}
});

Si lo pongo en cualquier otra section funciona perfectamente, pero parece que el ng-view interfiere con el funcionamiento del ng-click, ¿a alguien más le ha pasado?
*editado: disculpad por haberlo puesto en inglés al principio, casi todos los posts que he visto de AngularJS(Angular 1) estaban en inglés.

A: Solucionado, un amigo me ayudó con esto, es un problema de ámbito, hay que declarar la variable en $rootscope, desde app.run


text:
Q: How to prove that $B$ is positive definite when $\|A-B\|\leq\lambda_\min(A)$ for some positive definite $A$? Denote by $\mathbb R^{n \times n}$ the vector space of $n \times n$ matrices with real entries.
For $A \in \mathbb R^{n \times n}$, the notation $A\succ 0$ means that $A$ is symmetric and positive definite.
Question:
Suppose $A,B \in \mathbb R^{n \times n}$ are such that $A\succ0,\, B=B^T$ and that $\|A-B\|\leq\lambda_\min(A)$, where $\lambda_\min(A)$ is the smallest eigenvalue of $A$. Prove that $B\succ0$.

A: Hint: it suffices to show that the lowest eigenvalue of $A - B$ is positive.  Note that for a symmetric matrix $M$, the lowest eigenvalue can be expressed as
$$
\lambda_{min}(M) = \min_{\|x\| = 1} x^TMx
$$
and that
$$
\|M\| = \max_{\|x\| = 1} \left|x^TMx \right|
$$

I've combined several ideas to get that last equality.  From the usual results regarding the Rayleigh quotient, we have
$$
\lambda_{min}(M) = \min_{\|x\| = 1} x^TMx \\
\lambda_{max}(M) = \max_{\|x\| = 1} x^TMx
$$
For arbitrary matrices, we have
$$
\|A\| = \max_{\|x\| = 1}\|Ax\|= \sqrt{\max_{\|x\| = 1} x^TA^TAx}
$$
So, for symmetric $M$, we have
$$
\|M\| = \sqrt{\max_{\|x\| = 1} x^TM^2x} = \sqrt{\lambda_{max}(M^2)}
$$
Note, however, that the eigenvalues of $M^2$ are simply $\lambda^2$ for all eigenvalues $\lambda$ of $M$.  Thus, we have
$$
\|M\| = \sqrt{\lambda_{max}(M^2)} = \max\{|\lambda|: \lambda \text{ is an eigenvalue of } M\} = \max_{\|x\| = 1} \left|x^TMx \right|
$$


text:
Q: Poplulate a specific column when a row is added to a datagridview I am using the following code to update the database.
int lastRow = inventoryDataGridView.Rows.Count - 1;
inventoryDataGridView.Rows[lastRow].Cells[1].Value = variableName;

However, if multiple rows are added before the database is saved then it will only save the last one. So then I tried this code.
foreach (DataGridViewRow row in this.inventoryDataGridView.Rows)
{
    row.Cells[1].Value = variableName;
}

The problem with this is that it will update every cell in the given column to include the cells that already have a value. This is not efficient. Any suggestions on how to update just the given column of the newly added rows?
Thank You.

A: This seems to serve my purpose. As soon as I start typing in the blank row it will add another row to the datagridview and populate the given column of the new row I am entering with the variableName value.
private void inventoryDataGridView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
    int lastRow = inventoryDataGridView.Rows.Count - 1;
    inventoryDataGridView.Rows[lastRow - 1].Cells[2].Value = accountNumber;
}