问:
Javascript cannot set innerHTML of button with id because it's "null"
My goal is to have a button that onclick will call a function to change the styling of the html tag and the text (or innerHTML) of the button itself. Shouldn't be that hard, right? Well...

HTML:

```<code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>New look for my site!</title>
  <link rel="stylesheet" type="text/css" href="main.css">
  <script src="change-template.js"></script>
</head>
<body>
  <aside>
    <button type="button" id="template-button" onclick="changeTemplate()">Nightmode: On</button>
  </aside>
  <main>
    <h1>New page look for my site</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  </main>
</body>
</html>
</code>```

CSS (main.css):

```<code>html{
  background: "#111";
  color: "#0F0";
}
</code>```

JS (change-template.js):

```<code>var html = document.getElementsByTagName('html')[0];
var button = document.getElementById('template-button');
var nightmode = true;

function changeTemplate(){
  //change to lighter color if black and vice versa
  if(nightmode){
    html.style.background = "#EEE";
    html.style.color = "#000";
    button.innerHTML = "Nightmode: OFF";
  }else{
    html.style.background = "#111";
    html.style.color = "#0F0";
    button.innerHTML = "Nightmode: ON";
  }
  nightmode = !nightmode;
}
</code>```

And I'm getting this error

Uncaught TypeError: Cannot set property 'innerHTML' of null
      at changeTemplate (change-template.js:10)
      at HTMLButtonElement.onclick (new-look.html:11)

So please help me it's 90 degrees and I'm sitting here on the verge of hunger stressed about this simple issue and can barely think.

答:
That is because, your script is parsed, event before the elements are available in the DOM.

When the parser encounters var button = document.getElementById('template-button'); the element is not yet available in the DOM.

Because of which your code is technically doing this.

undefined.innerHTML

Move the script tag to just above the closing body tag. This will fix the issue since the elements are available in the DOM, when they get stored in the variables.

```<code> </main>
  <script src="change-template.js"></script>
</body>
</code>```

if you still want to include your script in the head, the other way around is wrap the code in document.onload which triggers, when the DOM is ready.

```<code>document.onload = function(e) {
    // your code goes here
};
</code>```

Body:
My goal is to have a button that onclick will call a function to change the styling of the html tag and the text (or innerHTML) of the button itself. Shouldn't be that hard, right? Well...

HTML:

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>New look for my site!</title>
  <link rel="stylesheet" type="text/css" href="main.css">

    <button type="button" id="template-button" onclick="changeTemplate()">Nightmode: On</button>

New page look for my site

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

CSS (main.css):

html{
  background: "#111";
  color: "#0F0";
}

JS (change-template.js):

var html = document.getElementsByTagName('html')[0];
var button = document.getElementById('template-button');
var nightmode = true;

function changeTemplate(){
  //change to lighter color if black and vice versa
  if(nightmode){
    html.style.background = "#EEE";
    html.style.color = "#000";
    button.innerHTML = "Nightmode: OFF";
  }else{
    html.style.background = "#111";
    html.style.color = "#0F0";
    button.innerHTML = "Nightmode: ON";
  }
  nightmode = !nightmode;
}

And I'm getting this error

Uncaught TypeError: Cannot set property 'innerHTML' of null
      at changeTemplate (change-template.js:10)
      at HTMLButtonElement.onclick (new-look.html:11)

So please help me it's 90 degrees and I'm sitting here on the verge of hunger stressed about this simple issue and can barely think.

Body:
That is because, your script is parsed, event before the elements are available in the DOM.

When the parser encounters var button = document.getElementById('template-button'); the element is not yet available in the DOM.

Because of which your code is technically doing this.

undefined.innerHTML

Move the script tag to just above the closing body tag. This will fix the issue since the elements are available in the DOM, when they get stored in the variables.

 </main>
  <script src="change-template.js"></script>
</body>

if you still want to include your script in the head, the other way around is wrap the code in document.onload which triggers, when the DOM is ready.

document.onload = function(e) {
    // your code goes here
};


来源: stackexchange

问:
Usage of raw_input in python
I am having so much trouble with this python script:

```<code>import time
print "Loading Interface"
time.sleep(0.5)
print "Loaded Interface"
time.sleep(1)
question_one = raw_input = "Request: Enter your name: "
question_two = raw_input = "Request: Enter your password: "
time.sleep(1)
print "Searching for %s with the password %s in our database." % (question_one, question_two)
</code>```

Could anyone tell me what I am doing wrong?

答:
for one, its not clear what you're asking. also, you have the program delay on purpose when it's not really loading... not sure why you would want to do that. and you're not actually calling raw_input, you're just assigning a variable to it. instead, try this:

```<code>question_one=raw_input("Request: enter your name: ")
</code>```

this ^^^ will actually ask the user a question.

ContentLicense: CC BY-SA 3.0

Title: Usage of raw_input in python

Body:
I am having so much trouble with this python script:

import time
print "Loading Interface"
time.sleep(0.5)
print "Loaded Interface"
time.sleep(1)
question_one = raw_input = "Request: Enter your name: "
question_two = raw_input = "Request: Enter your password: "
time.sleep(1)
print "Searching for %s with the password %s in our database." % (question_one, question_two)

Could anyone tell me what I am doing wrong?

Body:
for one, its not clear what you're asking. also, you have the program delay on purpose when it's not really loading... not sure why you would want to do that. and you're not actually calling raw_input, you're just assigning a variable to it. instead, try this:

question_one=raw_input("Request: enter your name: ")

this ^^^ will actually ask the user a question.


问:
Structure for an array of bits in C
It has come to my attention that there is no builtin structure for a single bit in C. There is (unsigned) char and int, which are 8 bits (one byte), and long which is 64+ bits, and so on (uint64_t, bool...)

I came across this while coding up a huffman tree, and the encodings for certain characters were not necessarily exactly 8 bits long (like 00101), so there was no efficient way to store the encodings. I had to find makeshift solutions such as strings or boolean arrays, but this takes far more memory.

But anyways, my question is more general: is there a good way to store an array of bits, or some sort of user-defined struct? I scoured the web for one but the smallest structure seems to be 8 bits (one byte). I tried things such as int a : 1 but it didn't work. I read about bit fields but they do not simply achieve exactly what I want to do. I know questions have already been asked about this in C++ and if there is a struct for a single bit, but mostly I want to know specifically what would be the most memory-efficient way to store an encoding such as 00101 in C.

答:
You can make you own bit array in no time.</p>

```<code>#define ba_set(ptr, bit)   { (ptr)[(bit) >> 3] |= (char)(1 << ((bit) & 7)); }
#define ba_clear(ptr, bit) { (ptr)[(bit) >> 3] &= (char)(~(1 << ((bit) & 7))); }
#define ba_get(ptr, bit)   ( ((ptr)[(bit) >> 3] & (char)(1 << ((bit) & 7)) ?  1 : 0 )
#define ba_setbit(ptr, bit, value) { if (value) { ba_set((ptr), (bit)) } else { ba_clear((ptr), (bit)); } }

#define BITARRAY_BITS  (120)

int main()
{
    char mybits[(BITARRAY_BITS + 7) / 8];
    memset(mybits, 0, sizeof(mybits));

    ba_setbit(mybits, 33, 1);
    if (!ba_get(33))
        return 1;
    return 0;
};
</code>```

Title: Structure for an array of bits in C

Body:
You can make you own bit array in no time.

#define ba_set(ptr, bit)   { (ptr)[(bit) >> 3] |= (char)(1 << ((bit) & 7)); }
#define ba_clear(ptr, bit) { (ptr)[(bit) >> 3] &= (char)(~(1 << ((bit) & 7))); }
#define ba_get(ptr, bit)   ( ((ptr)[(bit) >> 3] & (char)(1 << ((bit) & 7)) ?  1 : 0 )
#define ba_setbit(ptr, bit, value) { if (value) { ba_set((ptr), (bit)) } else { ba_clear((ptr), (bit)); } }

#define BITARRAY_BITS  (120)

int main()
{
    char mybits[(BITARRAY_BITS + 7) / 8];
    memset(mybits, 0, sizeof(mybits));

    ba_setbit(mybits, 33, 1);
    if (!ba_get(33))
        return 1;
    return 0;
};


问:
How can I handle File drag and drop with a window overlay and multiple drop zones?
I'd like to be able to detect when a user drags a file into the window and pop up an overlay over the whole app that shows the various folders the user could upload the file to.

So far, I understand that I can listen to the window for "dragenter" and show my overlay, and listen to the overlay for "dragleave" to hide it, but the problem seems to be that dragging over the drop zones causes the overlay's dragleave event to fire, which makes the overlay hide (which makes the window dragenter event show the overlay, and so on).

I'm using Dropzone.js for my folder dropzones. I've looked around and seen similar problems to mine, but none that solved this problem.

Edit: I found a solution (of sorts) elsewhere on StackOverflow: jQuery Drag-and-Drop Flickering on Hover (Webkit only)

The solution is to check the event on dragleave and, if the pageX and pageY are both 0, then it means the dragleave was because the user left the window, rather than dragged over one of the dropzones.

答:
The dragleave event fires very quick than we thought so we can delay the process.

```<code> Dropzone.autoDiscover = false;
$("div#upload").dropzone({
    url: "upload.php",
    addRemoveLinks:true,
    paramName:"composeUpload",
    init: function() {
        myDropZone = this;
        this.on('dragover', function(e,xhr,formData){
           $('.overlay').fadeIn();
          stopLoading(); //stops local file opens
            return false;
        });
      this.on('dragleave', function(e,xhr,formData){
           setTimeout(function(){
             $('.overlay').fadeIn();
           },8000);
        });
    }
});
</code>```

if you drop files on empty div or a overlay the browser will open the file locally so we have to stop the default

```<code>function stopLoading(){
   window.addEventListener("dragover",function(e){
    e = e || event;
    e.preventDefault();
   },false);
  window.addEventListener("drop",function(e){
    e = e || event;
    e.preventDefault();
  },false);
}
</code>```

I don't this is the answer you looking for but definitely it will give you a idea.thanks.

Body:
The dragleave event fires very quick than we thought so we can delay the process.

 Dropzone.autoDiscover = false;
$("div#upload").dropzone({
    url: "upload.php",
    addRemoveLinks:true,
    paramName:"composeUpload",
    init: function() {
        myDropZone = this;
        this.on('dragover', function(e,xhr,formData){
           $('.overlay').fadeIn();
          stopLoading(); //stops local file opens
            return false;
        });
      this.on('dragleave', function(e,xhr,formData){
           setTimeout(function(){
             $('.overlay').fadeIn();
           },8000);
        });
    }
});

if you drop files on empty div or a overlay the browser will open the file locally so we have to stop the default

function stopLoading(){
   window.addEventListener("dragover",function(e){
    e = e || event;
    e.preventDefault();
   },false);
  window.addEventListener("drop",function(e){
    e = e || event;
    e.preventDefault();
  },false);
}

I don't this is the answer you looking for but definitely it will give you a idea.thanks.


问:
Rstudio-Manipulating data in a list
for a school project, I have a data set that set as a list.file. when I access the data is appears as such, note:for this I am accessing the second pos in the list, I have about 200 pos in total:

malefiles[2]

[[1]]

version..1

1     n_points: 22

2                {

3  328.444 275.496

4  434.921 275.029

5  331.713 401.121

6  427.449 400.187

7  271.936 270.826

8  356.464 254.014

9  388.221 255.882

10 494.698 268.491

11 263.997 274.095

12 301.825 277.831

13 349.459 277.364

14 411.104 278.298

15 459.673 277.831

16 515.246 276.897

17  368.606 340.41

18  355.53 351.151

19 391.957 350.217

20 374.253 395.527

21 374.253 416.925

22 373.276 483.314

23  280.342 404.39

24 499.835 402.522

25               }

What I have been trying to do was pull the two numbers based on the line they are in  for all elements in the list but I don't know where to start. I have no experience with R, but my professor asked to have it in R. this is a AI project .

答:
edit:

Ok, you need the rows 3-24 of each element in a list. I've created a list with 4 elements, each of these with 30 rows:

```<code>set.seed(772017)

lapply(c(1:4), function(x) {
  paste(round(runif(30, min = 200, max = 900)),
        round(runif(30, min = 200, max = 900)), sep = " ")
}
) -> a.list
</code>```

I'd suggest you to use the apply functions, they are like loops in R but are usually faster. The inner function sapply extracts rows 3-24 of a given element in the list and returns a vector. The outer function lapply extracts each element in the list.

```<code>lapply(seq_along(a.list), function(x) {
  sapply(c(3:24), function(y){
    a.list[[x]][y]
})
}
)
</code>```

Title: Rstudio-Manipulating data in a list

Body:
edit:

Ok, you need the rows 3-24 of each element in a list. I've created a list with 4 elements, each of these with 30 rows:

set.seed(772017)

lapply(c(1:4), function(x) {
  paste(round(runif(30, min = 200, max = 900)),
        round(runif(30, min = 200, max = 900)), sep = " ")
}
) -> a.list

I'd suggest you to use the apply functions, they are like loops in R but are usually faster. The inner function sapply extracts rows 3-24 of a given element in the list and returns a vector. The outer function lapply extracts each element in the list.

lapply(seq_along(a.list), function(x) {
  sapply(c(3:24), function(y){
    a.list[[x]][y]
})
}
)


问:
`@` Symbol in mysql variable names
I have started maintaining  a bunch of mysql stored procs. Some variables (created with decalare statements) are accessed with the @ symbol and others without it. Whats the difference</p>

答: A variable with the <strong>@</strong> at the beginning is session variable. It exists until the session  end. </p>

ContentLicense: CC BY-SA 2.5

Title: `@` Symbol in mysql variable names

Body: A variable with the @ at the beginning is session variable. It exists until the session  end.


问:
EasyPHP Dashboard Unable to load
I have installed EasyPHP web server "EasyPHP-Webserver-14.1b2"

After installation i am able to access the dashboard 127.0.0.1:10000

however, after restarting my computer, i could not access the dashboard. it just keep loading and loading

答:
To manually start the dashboard use this command:</p>

```<code>"C:\Program Files (x86)\EasyPHP-Devserver-17\eds-dashboard\eds-dashboard.exe" -S 127.0.0.1:1111 -c eds-dashboard.ini
</code>```

Title: EasyPHP Dashboard Unable to load

Body:
To manually start the dashboard use this command:

"C:\Program Files (x86)\EasyPHP-Devserver-17\eds-dashboard\eds-dashboard.exe" -S 127.0.0.1:1111 -c eds-dashboard.ini


答:
I believe you mean that the problem is that the raw import prompt does not work. This is because raw_import is a function, and the (optional) argument can be the import prompt (see: https://docs.python.org/2/library/functions.html#raw_input)

i.e. this should work:

```<code>import time
print "Loading Interface"
time.sleep(0.5)
print "Loaded Interface"
time.sleep(1)
question_one = raw_input ("Request: Enter your name: ")
question_two = raw_input ("Request: Enter your password: ")
time.sleep(1)
print "Searching for %s with the password %s in our database." % (question_one, question_two)
</code>```

Title: Usage of raw_input in python

Body:
I believe you mean that the problem is that the raw import prompt does not work. This is because raw_import is a function, and the (optional) argument can be the import prompt (see: https://docs.python.org/2/library/functions.html#raw_input)

i.e. this should work:

import time
print "Loading Interface"
time.sleep(0.5)
print "Loaded Interface"
time.sleep(1)
question_one = raw_input ("Request: Enter your name: ")
question_two = raw_input ("Request: Enter your password: ")
time.sleep(1)
print "Searching for %s with the password %s in our database." % (question_one, question_two)


问:
I don't understand how to use document.getElementById(‘id’).onclick
I'm learning javascript right now and I am just building a simple menu that will show when the nav button is clicked.

I don't understand how to use the document.getElementById(‘id’).onclick when in a separated js file that is linked to my html. Reading around I think I understand that my problem is that you cannot call onclick out the blue because the DOM element are not yet defined.. or something alone those line. I just don't understand then how to proceed.

If I add within my button html tag onclick="function()" it works, but it don't when I add it within my separate js file. I'm using the W3school tutorial found here.

Here is my code

```<code><nav>
      <button class="nav-button" id="nav">
        <div class="menu-button"></div>
        <div class="menu-button"></div>
        <div class="menu-button"></div>
      </button>
      <div class="dropdown-menu" id="dropdown">
        <a href="#">Hello</a>
        <a href="#">Hello</a>
        <a href="#">Hello</a>
      </div>
    </nav>

.nav-button {
  background: none;
  border: none;
  margin-left: 1em;
  padding-top: 12px;
  cursor: pointer;
}

.menu-button {
  background-color: #fff;
  width: 30px;
  height: 4px;
  margin-bottom: 5px;
  border-radius: 5px;
}

.dropdown-menu {
  margin-top: 7px;
  width: 100px;
  background-color: #fff;
  display: none;
}

.showDropDown {
  display: block;
}

function showDropDown() {
  document.getElementById('dropdown').classList.toggle("showDropDown");
}

document.getElementById("nav").onclick = function showDropDown()
</code>```

Here is a codepen

Thanks for your help!

答:
1.create myjavascript.js file in same folder where your page html is.

2.copy the javascript code in myjavascript.js "only code not tag "

4.paste this at the end of your html page

```<code><SCRIPT language="javascript" src="myjavascript.js" type="text/javascript"></SCRIPT>
</code>```

This is the way to reference your code javascript in your html file.

Body:
I'm learning javascript right now and I am just building a simple menu that will show when the nav button is clicked.

I don't understand how to use the document.getElementById(‘id’).onclick when in a separated js file that is linked to my html. Reading around I think I understand that my problem is that you cannot call onclick out the blue because the DOM element are not yet defined.. or something alone those line. I just don't understand then how to proceed.

If I add within my button html tag onclick="function()" it works, but it don't when I add it within my separate js file. I'm using the W3school tutorial found here.

Here is my code

      <button class="nav-button" id="nav">

      </button>

        Hello
        Hello
        Hello

.nav-button {
  background: none;
  border: none;
  margin-left: 1em;
  padding-top: 12px;
  cursor: pointer;
}

.menu-button {
  background-color: #fff;
  width: 30px;
  height: 4px;
  margin-bottom: 5px;
  border-radius: 5px;
}

.dropdown-menu {
  margin-top: 7px;
  width: 100px;
  background-color: #fff;
  display: none;
}

.showDropDown {
  display: block;
}

function showDropDown() {
  document.getElementById('dropdown').classList.toggle("showDropDown");
}

document.getElementById("nav").onclick = function showDropDown()

Here is a codepen

Thanks for your help!

Body:
1.create myjavascript.js file in same folder where your page html is.

2.copy the javascript code in myjavascript.js "only code not tag <script></script>"

4.paste this at the end of your html page

<SCRIPT language="javascript" src="myjavascript.js" type="text/javascript"></SCRIPT>

This is the way to reference your code javascript in your html file.


问:
What is the range for PTRACE_TRACEME?
If I have a code like this:

```<code>void child() {
    do_something();
    ptrace(PTRACE_TRACEME, 0, 0, 0);
    do_some_other_things();
}
</code>```

then will do_something() be traced by the parent?

I found in the linux documentation, there were not such thing. It only said this should be called in the tracee.

PTRACE_TRACEME

Indicate that this process is to be traced by its parent.  A
process probably shouldn't make this request if its parent
isn't expecting to trace it.  (pid, addr, and data are
ignored.)

答:
See How Debuggers Work Part 1 for a better explanation, but in summary, no, it will not trace the do_something() function until the tracee receives a signal.

In the description of the ptrace call from that same man ptrace you quoted:

A  process  can  initiate  a  trace  by  calling  fork(2)  and having
  the resulting child do a
  PTRACE_TRACEME, followed (typically) by an execve(2).  Alternatively, one process may commence
  tracing another process using PTRACE_ATTACH or PTRACE_SEIZE.

While  being  traced, the tracee will stop each time a signal is delivered, even if the signal
         is being ignored.  (An exception is SIGKILL, which has its usual effect.)  The tracer will  be
         notified at its next call to waitpid(2) (or one of the related "wait" system calls); that call
         will return a status value containing information that indicates the cause of the stop in  the
         tracee.

When the tracee calls exec, it receives a signal, that's why it stops.

To illustrace, tracer program mainer.c with no bells or whistles:

```<code>//mainer.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/ptrace.h>
#include <sys/user.h>
#include <unistd.h>

int main(int argc, char ** argv)
{
        pid_t child_pid;
        char * programname = argv[1];

        child_pid = fork();
        if (child_pid == 0)
        {
                ptrace(PTRACE_TRACEME, 0, 0, 0);
                execl(programname, programname, NULL);
        }

        else if (child_pid > 0)
        {
            int status;

            wait(&status);

            while (WIFSTOPPED(status))
            {
                    struct user_regs_struct regs;
                    ptrace(PTRACE_GETREGS, child_pid, 0, &regs);
                    unsigned instr = ptrace(PTRACE_PEEKTEXT, child_pid, regs.eip, 0);
                    printf("EIP = 0x%08x, instr = 0x%08x\n", regs.eip, instr);

                    ptrace(PTRACE_SINGLESTEP, child_pid, 0, 0);

                    wait(&status);
            }

        }
}
</code>```

When the tracee hits exec, it will receive a signal and pass control to the parent, who is waiting.
Assembly program to trace, there's just way too much going on when tracing a C program to extract anything useful:

```<code>; hello.asm
section .text
    global _start

_start:
    mov edx,len1
    mov ecx,hello1
    mov ebx,1
    mov eax,4

    int 0x80

    mov edx,len2
    mov ecx,hello2
    mov ebx,1
    mov eax,4

    int 0x80

    mov eax,1
    int 0x80

section .data
    hello1 db "Hello",0xA
    len1 equ $ - hello1

    hello2 db "World",0xA
    len2 equ $ - hello2
</code>```

Running this, ./mainer hello

```<code>EIP = 0x08048080, instr = 0x00000000
EIP = 0x08048085, instr = 0x00000000
EIP = 0x0804808a, instr = 0x00000000
EIP = 0x0804808f, instr = 0x00000000
EIP = 0x08048094, instr = 0x00000000
Hello
EIP = 0x08048096, instr = 0x00000000
EIP = 0x0804809b, instr = 0x00000000
EIP = 0x080480a0, instr = 0x00000000
EIP = 0x080480a5, instr = 0x00000000
EIP = 0x080480aa, instr = 0x00000000
World
EIP = 0x080480ac, instr = 0x00000000
EIP = 0x080480b1, instr = 0x00000000
</code>```

If we modify mainer.c so the child process calls do_something() before it's exec the result of the trace is the exact same. This is just how I modified it, you can confirm yourself if you like that the results are the same.

```<code>#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/ptrace.h>
#include <sys/user.h>
#include <unistd.h>

int do_something(void)        //added this function
{
        printf("Doing something");
        return 0;
}

int main(int argc, char ** argv)
{
        pid_t child_pid;
        char * programname = argv[1];

        child_pid = fork();
        if (child_pid == 0)
        {
                ptrace(PTRACE_TRACEME, 0, 0, 0);
                do_something();      //added this function call
                execl(programname, programname, NULL);
        }

        else if (child_pid > 0)
        {
            int status;

            wait(&status);

            while (WIFSTOPPED(status))
            {
                    struct user_regs_struct regs;
                    ptrace(PTRACE_GETREGS, child_pid, 0, &regs);
                    unsigned instr = ptrace(PTRACE_PEEKTEXT, child_pid, regs.eip, 0);
                    printf("EIP = 0x%08x, instr = 0x%08x\n", regs.eip, instr);

                    ptrace(PTRACE_SINGLESTEP, child_pid, 0, 0);

                    wait(&status);
            }

        }
}
</code>```

So the tracee won't stop until it receives a signal, which is what happens when it calls exec, and calling functions doesn't generate a signal for the tracee, but there are other ways to send a signal to the tracee and begin tracing, although they are not as tidy as exec and wait.

Title: What is the range for PTRACE_TRACEME?

Body:
If I have a code like this:

void child() {
    do_something();
    ptrace(PTRACE_TRACEME, 0, 0, 0);
    do_some_other_things();
}

then will do_something() be traced by the parent?

I found in the linux documentation, there were not such thing. It only said this should be called in the tracee.

PTRACE_TRACEME

Indicate that this process is to be traced by its parent.  A
process probably shouldn't make this request if its parent
isn't expecting to trace it.  (pid, addr, and data are
ignored.)

Body:
See How Debuggers Work Part 1 for a better explanation, but in summary, no, it will not trace the do_something() function until the tracee receives a signal.

In the description of the ptrace call from that same man ptrace you quoted:

A  process  can  initiate  a  trace  by  calling  fork(2)  and having
  the resulting child do a
  PTRACE_TRACEME, followed (typically) by an execve(2).  Alternatively, one process may commence
  tracing another process using PTRACE_ATTACH or PTRACE_SEIZE.

While  being  traced, the tracee will stop each time a signal is delivered, even if the signal
         is being ignored.  (An exception is SIGKILL, which has its usual effect.)  The tracer will  be
         notified at its next call to waitpid(2) (or one of the related "wait" system calls); that call
         will return a status value containing information that indicates the cause of the stop in  the
         tracee.

When the tracee calls exec, it receives a signal, that's why it stops.

To illustrace, tracer program mainer.c with no bells or whistles:

//mainer.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/ptrace.h>
#include <sys/user.h>
#include <unistd.h>

int main(int argc, char ** argv)
{
        pid_t child_pid;
        char * programname = argv[1];

        child_pid = fork();
        if (child_pid == 0)
        {
                ptrace(PTRACE_TRACEME, 0, 0, 0);
                execl(programname, programname, NULL);
        }

        else if (child_pid > 0)
        {
            int status;

            wait(&status);

            while (WIFSTOPPED(status))
            {
                    struct user_regs_struct regs;
                    ptrace(PTRACE_GETREGS, child_pid, 0, &regs);
                    unsigned instr = ptrace(PTRACE_PEEKTEXT, child_pid, regs.eip, 0);
                    printf("EIP = 0x%08x, instr = 0x%08x\n", regs.eip, instr);

                    ptrace(PTRACE_SINGLESTEP, child_pid, 0, 0);

                    wait(&status);
            }

        }
}

When the tracee hits exec, it will receive a signal and pass control to the parent, who is waiting.
Assembly program to trace, there's just way too much going on when tracing a C program to extract anything useful:

; hello.asm
section .text
    global _start

_start:
    mov edx,len1
    mov ecx,hello1
    mov ebx,1
    mov eax,4

    int 0x80

    mov edx,len2
    mov ecx,hello2
    mov ebx,1
    mov eax,4

    int 0x80

    mov eax,1
    int 0x80

section .data
    hello1 db "Hello",0xA
    len1 equ $ - hello1

    hello2 db "World",0xA
    len2 equ $ - hello2

Running this, ./mainer hello

EIP = 0x08048080, instr = 0x00000000
EIP = 0x08048085, instr = 0x00000000
EIP = 0x0804808a, instr = 0x00000000
EIP = 0x0804808f, instr = 0x00000000
EIP = 0x08048094, instr = 0x00000000
Hello
EIP = 0x08048096, instr = 0x00000000
EIP = 0x0804809b, instr = 0x00000000
EIP = 0x080480a0, instr = 0x00000000
EIP = 0x080480a5, instr = 0x00000000
EIP = 0x080480aa, instr = 0x00000000
World
EIP = 0x080480ac, instr = 0x00000000
EIP = 0x080480b1, instr = 0x00000000

If we modify mainer.c so the child process calls do_something() before it's exec the result of the trace is the exact same. This is just how I modified it, you can confirm yourself if you like that the results are the same.

#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/ptrace.h>
#include <sys/user.h>
#include <unistd.h>

int do_something(void)        //added this function
{
        printf("Doing something");
        return 0;
}

int main(int argc, char ** argv)
{
        pid_t child_pid;
        char * programname = argv[1];

        child_pid = fork();
        if (child_pid == 0)
        {
                ptrace(PTRACE_TRACEME, 0, 0, 0);
                do_something();      //added this function call
                execl(programname, programname, NULL);
        }

        else if (child_pid > 0)
        {
            int status;

            wait(&status);

            while (WIFSTOPPED(status))
            {
                    struct user_regs_struct regs;
                    ptrace(PTRACE_GETREGS, child_pid, 0, &regs);
                    unsigned instr = ptrace(PTRACE_PEEKTEXT, child_pid, regs.eip, 0);
                    printf("EIP = 0x%08x, instr = 0x%08x\n", regs.eip, instr);

                    ptrace(PTRACE_SINGLESTEP, child_pid, 0, 0);

                    wait(&status);
            }

        }
}

So the tracee won't stop until it receives a signal, which is what happens when it calls exec, and calling functions doesn't generate a signal for the tracee, but there are other ways to send a signal to the tracee and begin tracing, although they are not as tidy as exec and wait.

ContentLicense: CC BY-SA 4.0


问:
How do you define a Dashboard view in Jenkins Job Builder
First, I would settle for a good example of a simple view definition in Jenkins Job Builder. The documentation seems woefully inadequate.

All I can find is this (which is two sentences with an incomplete example)

https://docs.openstack.org/infra/jenkins-job-builder/definition.html?highlight=view#views

But, what I really want to know is if it is possible to define a Dashboard view (https://wiki.jenkins.io/display/JENKINS/Dashboard+View) via Jenkins Job Builder. I can't find anything that says you can, so I assume it is not possible. But, as mentioned before, the documentation on defining views is so sparse I can't be sure.

答:
Perhaps exploring the following part of Jenkins' config.xml helps:

```<code>  <views>
    ...
    <hudson.plugins.view.dashboard.Dashboard plugin="dashboard-view@2.9.11">
      ...
      <name>My Dashboard</name>
      ...
    </hudson.plugins.view.dashboard.Dashboard>
    ...
  </views>
</code>```

I guess the list names in YAML are the same as the element names in XML.

However, there's a counterpart to Jenkins Job Builder: Jenkins View Builder.

Body:
Perhaps exploring the following part of Jenkins' config.xml helps:

  <views>
    ...
    <hudson.plugins.view.dashboard.Dashboard plugin="dashboard-view@2.9.11">
      ...
      <name>My Dashboard</name>
      ...
    </hudson.plugins.view.dashboard.Dashboard>
    ...
  </views>

I guess the list names in YAML are the same as the element names in XML.

However, there's a counterpart to Jenkins Job Builder: Jenkins View Builder.


问:
iOS app extension to modify phone keypad
I want to extend the functionality of phone keyboard.

I can't find any documentation on whether iOS 8+ has an API to do this. If it's possible can someone point me to some docs?

答:
The link https://developer.apple.com/library/content/documentation/General/Conceptual/ExtensibilityPG/CustomKeyboard.html says

Your custom keyboard is also ineligible to type into so-called phone pad objects, such as the phone number fields in Contacts. These input objects are exclusively for strings built from a small set of alphanumeric characters specified by telecommunications carriers and are identified by having one or another of the following two keyboard type traits:

```<code>UIKeyboardTypePhonePad

UIKeyboardTypeNamePhonePad
</code>```

When a user taps in a phone pad object, the system temporarily replaces your keyboard with the appropriate, standard system keyboard. When the user then taps in a different input object that requests a standard keyboard via its type trait, your keyboard automatically resumes.

Body:
The link https://developer.apple.com/library/content/documentation/General/Conceptual/ExtensibilityPG/CustomKeyboard.html says

Your custom keyboard is also ineligible to type into so-called phone pad objects, such as the phone number fields in Contacts. These input objects are exclusively for strings built from a small set of alphanumeric characters specified by telecommunications carriers and are identified by having one or another of the following two keyboard type traits:

UIKeyboardTypePhonePad

UIKeyboardTypeNamePhonePad

When a user taps in a phone pad object, the system temporarily replaces your keyboard with the appropriate, standard system keyboard. When the user then taps in a different input object that requests a standard keyboard via its type trait, your keyboard automatically resumes.


问:
How to dynamically generate a pdf from Google's appengine?
I'd like to create an application that would run on Google's appengine.

However, this application needs to be able to generate PDFs dynamically.

How could I do this?

答:
I would recommend PyFPDF, which is a pure-Python port of the lightweight yet highly powerful PHP FPDF library. It is hardly a few dozen kilobytes.

See http://code.google.com/p/pyfpdf/

OwnerDisplayName: carrier

LastEditorDisplayName: David


问:
What's a a good way to stop a pool of threads from running?
I've been working on a project lately, and i need to manage a pair of thread pools.
What the worker threads in the pools do is basically execute some kind of pop operation to each respective queue, eventually wait on a condition variable (pthread_cond_t) if there is no available value in the queue, and once they get an item, parse it and execute operations accordingly.
What i'm concerned about is the fact that i want to have no memory leaks, and to achieve that i noticed that calling a pthread_cancel on each thread when the main process is exiting is definitely a bad idea, as it leaves a lot of garbage around.
The point is, my first thought was to use a exit flag which i can set when the threads need to exit, so that they can easily free memory and call a pthread_exit...
I guess i should set this flag, then send a broadcast signal to the threads waiting on the condition variable and check the flag right after the pop operation...

Is this really the correct way to implement a good thread pool termination? I don't feel that much confident about this...
I'm writing some pseudo-code here to explain what i'm talking about

Each pool thread will run some code structured like this:

```<code>/* Worker thread (which will run on each pool thread) */
{ /* Thread initialization */ ... }
loop {
   value = pop();
   { /* Mutex lock because of the shared flag */ ... }
   if (flag) {{ /* Free memory and unlock mutex */ ... } pthread_exit(); }
   { /* Unlock the mutex */ ... }
   { /* Elaborate value */ ... }
}
return NULL;
</code>```

And there will be some kind of pool_stopRunning() function which will look like:

```<code>/* pool_stopRunning() function code */
{ /* Acquire flag mutex */ ... }
setFlag(flag);
{ /* Unlock flag mutex */ ... }
{ /* Acquire queue mutex */ ... }
pthread_cond_broadcast(...);
{ /* Unlock queue mutex */ ... }
</code>```

Thanks in advance, i just need to be sure that there isn't a fancy-er way to stop a thread pool... (or get to know a better way, by any chance)
As always, i'm sorry if there is any typo, i'm not and english speaker and it's kind of late right now >:

答:
With respect to symmetry with setting the flag and reducing serialization, this code:

```<code>{ /* Mutex lock because of the shared flag */ ... }
if (flag) {{ /* Free memory and unlock mutex */ ... } pthread_exit(); }
{ /* Unlock the mutex */ ... }
</code>```

should look like this:

```<code>{ /* Mutex lock because of the shared flag */ ... }
flagcopy = readFlag();
{ /* Unlock the mutex */ ... }
if (flagcopy) {{ /* Free memory ... } pthread_exit(); }
</code>```

Having said that, you can (should?) factor the mutex code into the setFlag and readFlag methods.

There is one more thing. If the flag is only a boolean and it is only changed once before the whole thing shuts down (i.e., it's never unset after being set), then I would argue that protecting the read with a mutex is not required.

I say this because if the above assumptions are true and if the loop's duration is very short and the loop iteration frequency is high, then you would be imposing undue serialization upon the business task and potentially increasing the response time unacceptably.

Body:
I've been working on a project lately, and i need to manage a pair of thread pools.
What the worker threads in the pools do is basically execute some kind of pop operation to each respective queue, eventually wait on a condition variable (pthread_cond_t) if there is no available value in the queue, and once they get an item, parse it and execute operations accordingly.
What i'm concerned about is the fact that i want to have no memory leaks, and to achieve that i noticed that calling a pthread_cancel on each thread when the main process is exiting is definitely a bad idea, as it leaves a lot of garbage around.
The point is, my first thought was to use a exit flag which i can set when the threads need to exit, so that they can easily free memory and call a pthread_exit...
I guess i should set this flag, then send a broadcast signal to the threads waiting on the condition variable and check the flag right after the pop operation...

Is this really the correct way to implement a good thread pool termination? I don't feel that much confident about this...
I'm writing some pseudo-code here to explain what i'm talking about

Each pool thread will run some code structured like this:

/* Worker thread (which will run on each pool thread) */
{ /* Thread initialization */ ... }
loop {
   value = pop();
   { /* Mutex lock because of the shared flag */ ... }
   if (flag) {{ /* Free memory and unlock mutex */ ... } pthread_exit(); }
   { /* Unlock the mutex */ ... }
   { /* Elaborate value */ ... }
}
return NULL;

And there will be some kind of pool_stopRunning() function which will look like:

/* pool_stopRunning() function code */
{ /* Acquire flag mutex */ ... }
setFlag(flag);
{ /* Unlock flag mutex */ ... }
{ /* Acquire queue mutex */ ... }
pthread_cond_broadcast(...);
{ /* Unlock queue mutex */ ... }

Thanks in advance, i just need to be sure that there isn't a fancy-er way to stop a thread pool... (or get to know a better way, by any chance)
As always, i'm sorry if there is any typo, i'm not and english speaker and it's kind of late right now >:

Body:
With respect to symmetry with setting the flag and reducing serialization, this code:

{ /* Mutex lock because of the shared flag */ ... }
if (flag) {{ /* Free memory and unlock mutex */ ... } pthread_exit(); }
{ /* Unlock the mutex */ ... }

should look like this:

{ /* Mutex lock because of the shared flag */ ... }
flagcopy = readFlag();
{ /* Unlock the mutex */ ... }
if (flagcopy) {{ /* Free memory ... } pthread_exit(); }

Having said that, you can (should?) factor the mutex code into the setFlag and readFlag methods.

There is one more thing. If the flag is only a boolean and it is only changed once before the whole thing shuts down (i.e., it's never unset after being set), then I would argue that protecting the read with a mutex is not required.

I say this because if the above assumptions are true and if the loop's duration is very short and the loop iteration frequency is high, then you would be imposing undue serialization upon the business task and potentially increasing the response time unacceptably.


问:
Trouble restarting my grid loop
The program currently runs with no errors in dev tools. Everything is performing besides the last part of code. After I enter the input in the prompt the container clears but will not let me draw inside of it with the newly set variables?</p>

```<code>var row=16;
var sizeofsquare=45;

function gridLife() {
  for (var x = 0; x < row; x++){
    for (var y = 0; y < row; y++){
  $("<div class='square'></div>").appendTo(".container");
}
}
}

$(document).ready(function(){
  gridLife();
 $('.square').on('mouseenter', function() {
        $(this).css('background-color', 'black');
      });
});

$(document).ready(function(){
$('.buttons').click(function(){
  $('.container').empty();
  row = prompt ('How many sqaures would you like?');
  sizeofsquare = 720/row;
});
});
</code>```

答:
The problem is you're removing all the squares by calling $('.container').empty(), but not putting them back afterwards.  At the end of your button click handler, you should call gridLife() again to regenerate the grid elements.

However, it will still not work because only the original square elements had the mouseenter events bound.  The new squares won't have that event handler anymore.  You could fix this by calling $('.square').on again, but that's messy.  The best way is to use the optional selector argument to .on(), like this:

```<code>$('.container').on('mouseenter', '.square', function () {
    $(this).css('background-color', 'black');
});
</code>```

Now, all .square elements that ever exist within the .container element will automatically trigger that same event.

Title: Trouble restarting my grid loop

Body:
The program currently runs with no errors in dev tools. Everything is performing besides the last part of code. After I enter the input in the prompt the container clears but will not let me draw inside of it with the newly set variables?

var row=16;
var sizeofsquare=45;

function gridLife() {
  for (var x = 0; x < row; x++){
    for (var y = 0; y < row; y++){
  $("

").appendTo(".container");
}
}
}

$(document).ready(function(){
  gridLife();
 $('.square').on('mouseenter', function() {
        $(this).css('background-color', 'black');
      });
});

$(document).ready(function(){
$('.buttons').click(function(){
  $('.container').empty();
  row = prompt ('How many sqaures would you like?');
  sizeofsquare = 720/row;
});
});

Body:
The problem is you're removing all the squares by calling $('.container').empty(), but not putting them back afterwards.  At the end of your button click handler, you should call gridLife() again to regenerate the grid elements.

However, it will still not work because only the original square elements had the mouseenter events bound.  The new squares won't have that event handler anymore.  You could fix this by calling $('.square').on again, but that's messy.  The best way is to use the optional selector argument to .on(), like this:

$('.container').on('mouseenter', '.square', function () {
    $(this).css('background-color', 'black');
});

Now, all .square elements that ever exist within the .container element will automatically trigger that same event.


问:
How to put a fancybox from a marker google maps v3
I have a Google map (v3) where I'm placing several bookmarks, and I want to be able to click bookmarks and extract a Fancybox iFrame. I tried but it doesn't work</p>

```<code>var marker = new google.maps.Marker({
              position: {lat: element.COOR_varCoordenadaLatitud, lng: element.COOR_varCoordenadaLongitud},
              map: map,
              icon: image,
              shape: shape,
              title: element.COOR_varNombre,
              zIndex: element.COOR_intId
              });
marker.addListener('click', function() {
              var src='http://localhost:8000/monumento/vistaindividual/13';
              $.fancybox.open({
                href: src,
                type: 'iframe',
                padding: 0
              });
}
</code>```

答:
you need to declare the marker first then use this google maps object to add the event Click to your marker for example :</p>

```<code>var marker=new google.maps.Marker({
    position:centerPosition,
    url: '/'
});
google.maps.event.addListener(marker, 'click', function() {
              var src='http://localhost:8000/monumento/vistaindividual/13';
              $.fancybox.open({
                href: src,
                type: 'iframe',
                padding: 0
              });
});
</code>```

Body:
I have a Google map (v3) where I'm placing several bookmarks, and I want to be able to click bookmarks and extract a Fancybox iFrame. I tried but it doesn't work

var marker = new google.maps.Marker({
              position: {lat: element.COOR_varCoordenadaLatitud, lng: element.COOR_varCoordenadaLongitud},
              map: map,
              icon: image,
              shape: shape,
              title: element.COOR_varNombre,
              zIndex: element.COOR_intId
              });
marker.addListener('click', function() {
              var src='http://localhost:8000/monumento/vistaindividual/13';
              $.fancybox.open({
                href: src,
                type: 'iframe',
                padding: 0
              });
}

Body:
you need to declare the marker first then use this google maps object to add the event Click to your marker for example :

var marker=new google.maps.Marker({
    position:centerPosition,
    url: '/'
});
google.maps.event.addListener(marker, 'click', function() {
              var src='http://localhost:8000/monumento/vistaindividual/13';
              $.fancybox.open({
                href: src,
                type: 'iframe',
                padding: 0
              });
});


问:
adding label from label data frame on facet chart
I have this plot

```<code>dat = data.frame(group = c("A","A","B","B"), pct = c(.2,.3,.5,.4), subgroup = c("D","E","D","E"), x = c("Z","Z","Z","Z"))

ggplot(data = dat, aes(x = factor(x), y  =pct, fill= subgroup ))+geom_bar(position = "stack", stat = "identity")+facet_wrap(~group)
</code>```

And I want to add a label above each stacked Z that is the sum of the 2 components so I build a lable data frame and use geom_text:

```<code>LABEL = data.frame(x = c("Z","Z"),  y = c(.5,.9), group = c("A","B"))
    ggplot(data = dat, aes(x = factor(x), y  =pct, fill= subgroup ))+geom_bar(position = "stack", stat = "identity")+facet_wrap(~group)+geom_text(aes(x= x,y=y ,label=labs), data = LABEL, vjust=-.2, size = 3)
</code>```

but because subgroup is not in the dataframe I get an error

```<code> : object 'subgroup' not found
</code>```

but I DO NOT want subgroup in the data frame as the label I am plotting is for the sum of each of the subgroups.

The example above has one stacked bar per facet but the solutions should work for any number of stacked bars per facet plot.

答:
Is this what you want? </p>

```<code>dat = data.frame(group = c("A","A","B","B"),
                 pct = c(.2,.3,.5,.4),
                 subgroup = c("D","E","D","E"),
                 x = c("Z","Z","Z","Z"))

LABEL = data.frame(x = c("Z","Z"),
                   y = c(.5,.9),
                   group = c("A","B"))

ggplot(data = dat, aes(x = factor(x), y  =pct)) +
    geom_bar(aes(fill= subgroup), position = "stack", stat = "identity") +
    facet_wrap(~group) +
    geom_text(aes(x= x,y=y ,label=y), data = LABEL, vjust=-.2, size = 3)
</code>```

Body:
I have this plot

dat = data.frame(group = c("A","A","B","B"), pct = c(.2,.3,.5,.4), subgroup = c("D","E","D","E"), x = c("Z","Z","Z","Z"))

ggplot(data = dat, aes(x = factor(x), y  =pct, fill= subgroup ))+geom_bar(position = "stack", stat = "identity")+facet_wrap(~group)

And I want to add a label above each stacked Z that is the sum of the 2 components so I build a lable data frame and use geom_text:

LABEL = data.frame(x = c("Z","Z"),  y = c(.5,.9), group = c("A","B"))
    ggplot(data = dat, aes(x = factor(x), y  =pct, fill= subgroup ))+geom_bar(position = "stack", stat = "identity")+facet_wrap(~group)+geom_text(aes(x= x,y=y ,label=labs), data = LABEL, vjust=-.2, size = 3)

but because subgroup is not in the dataframe I get an error

 : object 'subgroup' not found

but I DO NOT want subgroup in the data frame as the label I am plotting is for the sum of each of the subgroups.

The example above has one stacked bar per facet but the solutions should work for any number of stacked bars per facet plot.

Body:
Is this what you want?

dat = data.frame(group = c("A","A","B","B"),
                 pct = c(.2,.3,.5,.4),
                 subgroup = c("D","E","D","E"),
                 x = c("Z","Z","Z","Z"))

LABEL = data.frame(x = c("Z","Z"),
                   y = c(.5,.9),
                   group = c("A","B"))

ggplot(data = dat, aes(x = factor(x), y  =pct)) +
    geom_bar(aes(fill= subgroup), position = "stack", stat = "identity") +
    facet_wrap(~group) +
    geom_text(aes(x= x,y=y ,label=y), data = LABEL, vjust=-.2, size = 3)


问:
PostgreSQL - Function that returns labels of any ENUM
I am trying to write a "generic" function that will return labels of any enum (in any schema)...
But I am not having much luck because I am not sure what should argument type be...

The goal would be to be able to call function like this

```<code>SELECT common.get_enum_labels('public.rainbow_colors');
SELECT common.get_enum_labels('audit.user_actions');
</code>```

This is what I have so

```<code>CREATE OR REPLACE FUNCTION common.get_enum_labels(enum_name regtype)
RETURNS SETOF text AS
$$
BEGIN
  EXECUTE format('SELECT unnest(enum_range(NULL::%s))::text AS enum_labels ORDER BY 1', enum_name);
END;
$$
LANGUAGE plpgsql
STABLE
PARALLEL SAFE
;
</code>```

Any tips would be appreciated

答:
```<code>create or replace function get_enum_labels(enum_name regtype)
  returns setof text language sql stable
as $$
  select enumlabel::text
  from pg_enum
  where enumtypid = enum_name
  order by enumsortorder
$$;
</code>```

Body:
I am trying to write a "generic" function that will return labels of any enum (in any schema)...
But I am not having much luck because I am not sure what should argument type be...

The goal would be to be able to call function like this

SELECT common.get_enum_labels('public.rainbow_colors');
SELECT common.get_enum_labels('audit.user_actions');

This is what I have so

CREATE OR REPLACE FUNCTION common.get_enum_labels(enum_name regtype)
RETURNS SETOF text AS
$$
BEGIN
  EXECUTE format('SELECT unnest(enum_range(NULL::%s))::text AS enum_labels ORDER BY 1', enum_name);
END;
$$
LANGUAGE plpgsql
STABLE
PARALLEL SAFE
;

Any tips would be appreciated


问:
PHP OOP need advice
i am building this sms notification system, which will send 10 times free sms based on certain occasion to the web's member, and after a certain member reach 10 times, the system would send a last notification system saying that "this is the last free sms notification", i am currently learning PHP OOP and trying to use an OOP aproach on this

without further a do here's my code:

```<code><?php
class SmsBonus {
//bonus_sms fields = id, member_id, counter, end_status

public static function find_member($id=0){
    //query to find a certain member
}

public function add_counter($id=0){
    //query to increment the value of counter field
}

public function status_check($id=0){
    //query to check whether the given member's counter has reach the number 10
}

public static function send_sms($id, $message){
    $found = $this->find_member($id);
    $status_check = $this->status_check($id);

    if(!empty($found) && !empty($status_check) && $found->counter == 10){
        //send the sms notification saying that this member has reach the end of the bonus period

        //update this member's end_status table to 1
    }else{
        //send the regular notification
    }
}

}
?>
</code>```

would this lines:

```<code>$found = $this->find_member($id);
$status_check = $this->status_check($id);
</code>```

work as expected (i cant test this one out because i am currently building this on local)? and is this a best practice regarding OOP aproach ? or am i doing this wrong ?

i need advice, thank you very much.

EDIT:

of course on my original code i declare the class, i am sorry that by not writing it here confuses everybody :D, i am actually looking for a kind of answer (advice) that pointed the way i should implement a best approach (best practice) on my codes (in this case methods), things that i worry about is that i don't meet the requirements such as K.I.S.S or D.R.Y.

UPDATE
i manage to do some modifications based on your suggestions, how is this looks like ?

```<code><?php
    class SmsBonus{
        //bonus_sms fields = id, member_id, counter, end_status
        protected $max_sms = 10;

        public $id;
        public $member_id;
        public $counter;
        public $end_status;

        public function find_member($id=0){
            //query to find a certain member
        }

        public function add_counter($id=0){
            //query to increment the value of counter field
        }

        public function status_check($id=0){
            //query to check whether the given member's counter has reach the number 10
        }

        public function update_status($id=0){
            //query to update when a certain member reach its sms bonus limit
        }

        protected function can_still_send_sms($member_id){
            $found          = $this->find_member($member_id);
            $status_check   = $this->status_check($id);
            return !empty($found) && $found->counter < $this->max_sms && !empty($status_check);
        }

        public function send_sms($id, $message){
            $phone  = Phone::find_member($id); //
            if ($this->can_still_send_sms($id)) {
                //send the sms notification saying that this member has reach the end of the bonus period

                $this->update_status($id);
            }else{
                //send the regular notification

                $this->add_counter($id);
            }
        }
    }
    $sms_bonus = new SmsBonus();
?>
</code>```

答:
You need to wrap your code in a class declaration

```<code>class SMSNotification {
...
}
</code>```

And you may also want to create a constructor

```<code>function __construct() {
</code>```

One reason for this is so that you can set private variables to the class when it is instantiated.

you instantiate the class like this:

```<code>$sms = SMSNotification()
</code>```

Will you be connecting this to a database for the counter increment. As what you would normally do with an oop approach is have a seperate class that handles that connection, so that if you wanted to build on this whole project then everything would be connecting to a database the same way.

The two lines of code you pasted are a bit different:

```<code>$found = $this->find_member($id);
</code>```

you have made find_member a static function (which is probably what i would have done) so that you can call the function without create a new class object.  That being said it is not of value $this as it is not part of the current instantiated class. So you will need to call it like (using my example of SMSNotification):

```<code>$found = SMSNotification::find_member($id);
</code>```

This tells php to look for a static function called find_member

The other line of code should work fine:

```<code>$status_check = $this->status_check($id);
</code>```

Title: PHP OOP need advice

Body:
i am building this sms notification system, which will send 10 times free sms based on certain occasion to the web's member, and after a certain member reach 10 times, the system would send a last notification system saying that "this is the last free sms notification", i am currently learning PHP OOP and trying to use an OOP aproach on this

without further a do here's my code:

<?php
class SmsBonus {
//bonus_sms fields = id, member_id, counter, end_status

public static function find_member($id=0){
    //query to find a certain member
}

public function add_counter($id=0){
    //query to increment the value of counter field
}

public function status_check($id=0){
    //query to check whether the given member's counter has reach the number 10
}

public static function send_sms($id, $message){
    $found = $this->find_member($id);
    $status_check = $this->status_check($id);

    if(!empty($found) && !empty($status_check) && $found->counter == 10){
        //send the sms notification saying that this member has reach the end of the bonus period

        //update this member's end_status table to 1
    }else{
        //send the regular notification
    }
}

}
?>

would this lines:

$found = $this->find_member($id);
$status_check = $this->status_check($id);

work as expected (i cant test this one out because i am currently building this on local)? and is this a best practice regarding OOP aproach ? or am i doing this wrong ?

i need advice, thank you very much.

EDIT:

of course on my original code i declare the class, i am sorry that by not writing it here confuses everybody :D, i am actually looking for a kind of answer (advice) that pointed the way i should implement a best approach (best practice) on my codes (in this case methods), things that i worry about is that i don't meet the requirements such as K.I.S.S or D.R.Y.

UPDATE
i manage to do some modifications based on your suggestions, how is this looks like ?

<?php
    class SmsBonus{
        //bonus_sms fields = id, member_id, counter, end_status
        protected $max_sms = 10;

        public $id;
        public $member_id;
        public $counter;
        public $end_status;

        public function find_member($id=0){
            //query to find a certain member
        }

        public function add_counter($id=0){
            //query to increment the value of counter field
        }

        public function status_check($id=0){
            //query to check whether the given member's counter has reach the number 10
        }

        public function update_status($id=0){
            //query to update when a certain member reach its sms bonus limit
        }

        protected function can_still_send_sms($member_id){
            $found          = $this->find_member($member_id);
            $status_check   = $this->status_check($id);
            return !empty($found) && $found->counter < $this->max_sms && !empty($status_check);
        }

        public function send_sms($id, $message){
            $phone  = Phone::find_member($id); //
            if ($this->can_still_send_sms($id)) {
                //send the sms notification saying that this member has reach the end of the bonus period

                $this->update_status($id);
            }else{
                //send the regular notification

                $this->add_counter($id);
            }
        }
    }
    $sms_bonus = new SmsBonus();
?>

Body:
You need to wrap your code in a class declaration

class SMSNotification {
...
}

And you may also want to create a constructor

function __construct() {

One reason for this is so that you can set private variables to the class when it is instantiated.

you instantiate the class like this:

$sms = SMSNotification()

Will you be connecting this to a database for the counter increment. As what you would normally do with an oop approach is have a seperate class that handles that connection, so that if you wanted to build on this whole project then everything would be connecting to a database the same way.

The two lines of code you pasted are a bit different:

$found = $this->find_member($id);

you have made find_member a static function (which is probably what i would have done) so that you can call the function without create a new class object.  That being said it is not of value $this as it is not part of the current instantiated class. So you will need to call it like (using my example of SMSNotification):

$found = SMSNotification::find_member($id);

This tells php to look for a static function called find_member

The other line of code should work fine:

$status_check = $this->status_check($id);


问:
Calling a method with (sometimes) null parameters to execute an SQL statement. C# / ASP.NET
I have a method and am trying to figure out how to handle calling that method with null parameters.

```<code>public static List<Incident> GetIncidentByTechnician(int techID)
    {
        List<Incident> incidents = new List<Incident>();

            Incident inc = null; // found incident
                                 // define connection
            SqlConnection connection = TechSupportDB.GetConnection();

            // define the select query command
            string selectQuery = "select IncidentID, CustomerID, ProductCode, TechID, DateOpened, DateClosed, Title, Description " +
                                 "from Incidents " +
                                 "where TechID = @TechID";

        SqlCommand selectCommand = new SqlCommand(selectQuery, connection);
            selectCommand.Parameters.AddWithValue("@TechID", techID);
            try
            {
                // open the connection
                connection.Open();

                // execute the query
                SqlDataReader reader = selectCommand.ExecuteReader();

                // process the result while there are incidents
                while (reader.Read())
                {
                    inc = new Incident();
                    inc.IncidentID = (int)reader["IncidentID"];
                    inc.CustomerID = (int)reader["CustomerId"];
                    inc.ProductCode = reader["ProductCode"].ToString();
                    inc.TechID = (int)reader["TechID"];
                    inc.DateOpened = (DateTime)reader["DateOpened"];
                    inc.DateClosed = (DateTime?)reader["DateClosed"];
                    inc.Title = reader["Title"].ToString();
                    inc.Description = reader["Description"].ToString();
                    incidents.Add(inc); //add to the list
                }
            }
            catch (Exception ex)
            {
                throw ex; // let the form handle it
            }
            finally
            {
                connection.Close(); // close connecto no matter what
            }
        return incidents;
    }
</code>```

it takes "techID" integer as parameter and populates a list of incidents with that technician ID. However, some incidents have null values for techID. I don't want them to be added into my list.

I tried an if(techID !=null) but that gives an error saying it will always be true. I think my sql statement is not good since "where TechID = null " doesn't return results and it should be "where TechID is null" when testing this statement in sql server management studio. Any suggestions to handle these null values?
Also my incident class is shown below. I set the techID to accept null values with int?.

```<code>    public class Incident
{
    public Incident() { }
    public int IncidentID { get; set; }
    public int CustomerID { get; set; }
    public string ProductCode { get; set; }
    public int? TechID { get; set; }
    public DateTime DateOpened { get; set; }
    public DateTime? DateClosed { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
}
</code>```

答:
According to your function prototype, techID is an integer and is not nullable:

```<code>public static List<Incident> GetIncidentByTechnician(int techID)
</code>```

This means that the SQL call will never include a null @techID, because it is assigned from the non-nullable techID:

```<code>selectCommand.Parameters.AddWithValue("@TechID", techID);
</code>```

So your select statement should only return rows with a non-null techID. It has to match, after all.

```<code>select IncidentID, CustomerID, ProductCode, TechID, DateOpened, DateClosed, Title, Description
from Incidents
where TechID = @TechID
</code>```

Therefore the reader should never return a null techID either:

```<code>inc.TechID = (int)reader["TechID"];
</code>```

Given the code sample you have provided, null TechID values should not be an issue. You should not have to add an if or amend your where clause to handle null techID values, because they will not be allowed by the c# code.

You have tried running the code as is?

Body:
I have a method and am trying to figure out how to handle calling that method with null parameters.

public static List<Incident> GetIncidentByTechnician(int techID)
    {
        List<Incident> incidents = new List<Incident>();

            Incident inc = null; // found incident
                                 // define connection
            SqlConnection connection = TechSupportDB.GetConnection();

            // define the select query command
            string selectQuery = "select IncidentID, CustomerID, ProductCode, TechID, DateOpened, DateClosed, Title, Description " +
                                 "from Incidents " +
                                 "where TechID = @TechID";

        SqlCommand selectCommand = new SqlCommand(selectQuery, connection);
            selectCommand.Parameters.AddWithValue("@TechID", techID);
            try
            {
                // open the connection
                connection.Open();

                // execute the query
                SqlDataReader reader = selectCommand.ExecuteReader();

                // process the result while there are incidents
                while (reader.Read())
                {
                    inc = new Incident();
                    inc.IncidentID = (int)reader["IncidentID"];
                    inc.CustomerID = (int)reader["CustomerId"];
                    inc.ProductCode = reader["ProductCode"].ToString();
                    inc.TechID = (int)reader["TechID"];
                    inc.DateOpened = (DateTime)reader["DateOpened"];
                    inc.DateClosed = (DateTime?)reader["DateClosed"];
                    inc.Title = reader["Title"].ToString();
                    inc.Description = reader["Description"].ToString();
                    incidents.Add(inc); //add to the list
                }
            }
            catch (Exception ex)
            {
                throw ex; // let the form handle it
            }
            finally
            {
                connection.Close(); // close connecto no matter what
            }
        return incidents;
    }

it takes "techID" integer as parameter and populates a list of incidents with that technician ID. However, some incidents have null values for techID. I don't want them to be added into my list.

I tried an if(techID !=null) but that gives an error saying it will always be true. I think my sql statement is not good since "where TechID = null " doesn't return results and it should be "where TechID is null" when testing this statement in sql server management studio. Any suggestions to handle these null values?
Also my incident class is shown below. I set the techID to accept null values with int?.

    public class Incident
{
    public Incident() { }
    public int IncidentID { get; set; }
    public int CustomerID { get; set; }
    public string ProductCode { get; set; }
    public int? TechID { get; set; }
    public DateTime DateOpened { get; set; }
    public DateTime? DateClosed { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
}

Body:
According to your function prototype, techID is an integer and is not nullable:

public static List<Incident> GetIncidentByTechnician(int techID)

This means that the SQL call will never include a null @techID, because it is assigned from the non-nullable techID:

selectCommand.Parameters.AddWithValue("@TechID", techID);

So your select statement should only return rows with a non-null techID. It has to match, after all.

select IncidentID, CustomerID, ProductCode, TechID, DateOpened, DateClosed, Title, Description
from Incidents
where TechID = @TechID

Therefore the reader should never return a null techID either:

inc.TechID = (int)reader["TechID"];

Given the code sample you have provided, null TechID values should not be an issue. You should not have to add an if or amend your where clause to handle null techID values, because they will not be allowed by the c# code.

You have tried running the code as is?


问:
Writing piece-wise functions in TensorFlow / if then in TensorFlow
How do I write a piece-wise TensorFlow function i.e. a function that has an if-statement inside it?

Current code

```<code>import tensorflow as tf

my_fn = lambda x : x ** 2 if x > 0 else x + 5
with tf.Session() as sess:
  x = tf.Variable(tf.random_normal([100, 1]))
  output = tf.map_fn(my_fn, x)
</code>```

Error:

TypeError: Using a tf.Tensor as a Python bool is not allowed. Use if t is not None: instead of if t: to test if a tensor is defined, and use the logical TensorFlow ops to test the value of a tensor.

答:
tf.select is no more working as indicated by this thread as well
https://github.com/tensorflow/tensorflow/issues/8647

Something that worked for me was tf.where

```<code>condition = tf.greater(x, 0)
res = tf.where(condition, tf.square(x), x + 5)
</code>```

Body:
How do I write a piece-wise TensorFlow function i.e. a function that has an if-statement inside it?

Current code

import tensorflow as tf

my_fn = lambda x : x ** 2 if x > 0 else x + 5
with tf.Session() as sess:
  x = tf.Variable(tf.random_normal([100, 1]))
  output = tf.map_fn(my_fn, x)

Error:

TypeError: Using a tf.Tensor as a Python bool is not allowed. Use if t is not None: instead of if t: to test if a tensor is defined, and use the logical TensorFlow ops to test the value of a tensor.

Body:
tf.select is no more working as indicated by this thread as well
https://github.com/tensorflow/tensorflow/issues/8647

Something that worked for me was tf.where

condition = tf.greater(x, 0)
res = tf.where(condition, tf.square(x), x + 5)


问:
Importing JSON into Pandas
I have to following JSON that is coming from an API (e.g. my_json). The array of entities is stored in a key called entities:

```<code>{
    "action" : "get",
    "application" : "4d97323f-ac0f-11e6-b1d4-0eec2415f3df",
    "params" : {
      "limit" : [ "2" ]
    },
    "path" : "/businesses",
    "entities" : [
        {
            "uuid" : "508d56f1-636b-11e7-9928-122e0737977d",
            "type" : "business",
            "size" : 730 },
        {
            "uuid" : "2f3bd4dc-636b-11e7-b937-0ad881f403bf",
            "type" : "business",
            "size" : 730
        } ],
  "timestamp" : 1499469891059,
  "duration" : 244,
  "count" : 2
}
</code>```

I am trying to load them into a data frame as follows:

```<code>import pandas as pd

pd.read_json(my_json['entities'], orient='split')
</code>```

I get the following error:

```<code>ValueError: Invalid file path or buffer object type: <type 'list'>
</code>```

I have tried records orientation and still doesn't work.

答:
If my_json is a dictionary as I suspect, then you can skip the pd.read_json and just do

```<code>pd.DataFrame(my_json['entities'])

   size      type                                  uuid
0   730  business  508d56f1-636b-11e7-9928-122e0737977d
1   730  business  2f3bd4dc-636b-11e7-b937-0ad881f403bf
</code>```

Title: Importing JSON into Pandas

Body:
I have to following JSON that is coming from an API (e.g. my_json). The array of entities is stored in a key called entities:

{
    "action" : "get",
    "application" : "4d97323f-ac0f-11e6-b1d4-0eec2415f3df",
    "params" : {
      "limit" : [ "2" ]
    },
    "path" : "/businesses",
    "entities" : [
        {
            "uuid" : "508d56f1-636b-11e7-9928-122e0737977d",
            "type" : "business",
            "size" : 730 },
        {
            "uuid" : "2f3bd4dc-636b-11e7-b937-0ad881f403bf",
            "type" : "business",
            "size" : 730
        } ],
  "timestamp" : 1499469891059,
  "duration" : 244,
  "count" : 2
}

I am trying to load them into a data frame as follows:

import pandas as pd

pd.read_json(my_json['entities'], orient='split')

I get the following error:

ValueError: Invalid file path or buffer object type: <type 'list'>

I have tried records orientation and still doesn't work.

Body:
If my_json is a dictionary as I suspect, then you can skip the pd.read_json and just do

pd.DataFrame(my_json['entities'])

   size      type                                  uuid
0   730  business  508d56f1-636b-11e7-9928-122e0737977d
1   730  business  2f3bd4dc-636b-11e7-b937-0ad881f403bf


问:
Binding M-<up> / M-<down> in Emacs 23.1.1
I'm trying to put in a feature that I miss from Eclipse, where Alt+[Up/Down] transposes the lines up or down, but can not for the life of me figure out how to assign to these keys properly. I am using it in -nw mode (so just in a shell window), and typically run in a screen session.

Using a global key binding, I can get it to work with letter combinations, like (kbd "M-m"), but every combination I have tried for the arrow keys just gives me a message that doesn't make sense, I always get:

```<code>"ESC <up> is undefined"
</code>```

What I have tried:

```<code>(global-set-key (kbd "M-<up>") 'transpose-line-up)
(global-set-key (kbd "<escape>-<up>") 'transpose-line-up)
(global-set-key [M-up] 'transpose-line-up)
(global-set-key [\e \M-O A] 'transpose-line-up)
</code>```

And C-h c just returns:

```<code>ESC <up> (translated from ESC M-O A) is undefined
</code>```

None of these work, either using ESC or Alt.

Any idea how I can make this work? I would prefer to have these as Alt+[Up/Down] just because that is what I am used to.

Edit

From the comments:

C-q Up prints ^[OA.

C-q M-Up prints ^[ and moves the cursor up a line.

C-h k (Alt+Up) prints ESC <up> (translated from ESC M-O A) is undefined.

Thanks for the suggestions, but they all turned out the same.

答:
The following lines work for me on macOS 10.11.6 and GNU Emacs 25.2.1:

```<code>(global-set-key (kbd "ESC <down>") 'end-of-buffer)
(global-set-key (kbd "ESC <up>") 'beginning-of-buffer)
</code>```

Body:
I'm trying to put in a feature that I miss from Eclipse, where Alt+[Up/Down] transposes the lines up or down, but can not for the life of me figure out how to assign to these keys properly. I am using it in -nw mode (so just in a shell window), and typically run in a screen session.

Using a global key binding, I can get it to work with letter combinations, like (kbd "M-m"), but every combination I have tried for the arrow keys just gives me a message that doesn't make sense, I always get:

"ESC <up> is undefined"

What I have tried:

(global-set-key (kbd "M-<up>") 'transpose-line-up)
(global-set-key (kbd "<escape>-<up>") 'transpose-line-up)
(global-set-key [M-up] 'transpose-line-up)
(global-set-key [\e \M-O A] 'transpose-line-up)

And C-h c just returns:

ESC <up> (translated from ESC M-O A) is undefined

None of these work, either using ESC or Alt.

Any idea how I can make this work? I would prefer to have these as Alt+[Up/Down] just because that is what I am used to.

Edit

From the comments:

C-q Up prints ^[OA.

C-q M-Up prints ^[ and moves the cursor up a line.

C-h k (Alt+Up) prints ESC <up> (translated from ESC M-O A) is undefined.

Thanks for the suggestions, but they all turned out the same.

Body:
The following lines work for me on macOS 10.11.6 and GNU Emacs 25.2.1:

(global-set-key (kbd "ESC <down>") 'end-of-buffer)
(global-set-key (kbd "ESC <up>") 'beginning-of-buffer)


问:
How to make so that the toolbar does not overlap?
I am trying to add a list in the main main, but the toolbar is overridden making in the execution the first element is not seen.

Any solution

The main layout

```<code>    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@android:color/holo_red_dark"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/list_elec" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
    app:backgroundTint="@android:color/holo_red_dark"
    app:srcCompat="@android:drawable/ic_input_add" />

</android.support.design.widget.CoordinatorLayout>
</code>```

The theme used in the application

```<code>  <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
</code>```

The manifest of the application

```<code> <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</code>```

答:
In your manifest you are declaring your MainActivity using NoActionBar theme, which will remove the action bar you added.

```<code><activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar"> //<-- the issue
</code>```

use another theme or remove it like :

```<code>        <activity
            android:name=".MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
</code>```

Body:
I am trying to add a list in the main main, but the toolbar is overridden making in the execution the first element is not seen.

Any solution

The main layout

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@android:color/holo_red_dark"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/list_elec" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
    app:backgroundTint="@android:color/holo_red_dark"
    app:srcCompat="@android:drawable/ic_input_add" />

</android.support.design.widget.CoordinatorLayout>

The theme used in the application

Body:
In your manifest you are declaring your MainActivity using NoActionBar theme, which will remove the action bar you added.

<activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar"> //<-- the issue

use another theme or remove it like :

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>


问:
React Jest Test Fails when setState Called in Promise
I'm trying to mock out the a service that returns promises so that I can verify it gets called with the correct parameters.  The way the service is called varies based on the state and the first call to the service sets the state.

When setting the state in the promise it is not updating unless I wrap the assertion in setTimeout or completely stub out the promise.  Is there a way to do this with just a plain promise and an expect?

My component:

```<code>class App extends Component {

  constructor(props) {
    super(props);
    this.state = {results: []};
    this.service = props.service;
    this.load = this.load.bind(this);
  }

  load() {
    if (this.state.results.length === 0) {
      this.service.load('state is empty')
                  .then(result => this.setState({results: result.data}));
    } else {
      this.service.load('state is nonempty')
                  .then(result => this.setState({results: result.data}));
    }
  }

  render() {
    return (
      <div className="App">
        <button id="submit" onClick={this.load}/>
      </div>
    );
  }
}
</code>```

My test:

```<code>it('Calls service differently based on results', () => {

  const mockLoad = jest.fn((text) => {
    return new Promise((resolve, reject) => {
      resolve({data: [1, 2]});
    });
  });

  const serviceStub = {load: mockLoad};

  let component = mount(<App service={serviceStub}/>);
  let button = component.find("#submit");

  button.simulate('click');

  expect(mockLoad).toBeCalledWith('state is empty');

  button.simulate('click');

  //this assertion fails as the state has not updated and is still 'state is empty'
  expect(mockLoad).toBeCalledWith('state is nonempty');
});
</code>```

As mentioned, the following works, but I'd rather not wrap the expect if there's a way around it:

```<code>setTimeout(() => {
    expect(mockLoad).toBeCalledWith('state is nonempty');
    done();
  }, 50);
</code>```

I can also change how I mock the function to stub out the promise which will work:

```<code>const mockLoad = jest.fn((text) => {
  return {
    then: function (callback) {
      return callback({
        data : [1, 2]
      })
    }
  }
});
</code>```

But I'd like to just return a promise.

答:
Using Sinon with Sinon Stub Promise I was able to get this to work.  The stub promise library removes the async aspects of the promise, which means that state gets updated in time for the render:

```<code>const sinon = require('sinon');
const sinonStubPromise = require('sinon-stub-promise');
sinonStubPromise(sinon);

it('Calls service differently based on results', () => {

    const mockLoad = jest.fn((text) => {
        return sinon.stub().returnsPromise().resolves({data: [1, 2]})();
    });

    const serviceStub = {load: mockLoad};

    let component = mount(<App service={serviceStub}/>);
    let button = component.find("#submit");

    button.simulate('click');

    expect(mockLoad).toBeCalledWith('state is empty');

    button.simulate('click');

    expect(mockLoad).toBeCalledWith('state is nonempty');
});
</code>```

See:

http://sinonjs.org/

https://github.com/substantial/sinon-stub-promise

Body:
I'm trying to mock out the a service that returns promises so that I can verify it gets called with the correct parameters.  The way the service is called varies based on the state and the first call to the service sets the state.

When setting the state in the promise it is not updating unless I wrap the assertion in setTimeout or completely stub out the promise.  Is there a way to do this with just a plain promise and an expect?

My component:

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {results: []};
    this.service = props.service;
    this.load = this.load.bind(this);
  }

  load() {
    if (this.state.results.length === 0) {
      this.service.load('state is empty')
                  .then(result => this.setState({results: result.data}));
    } else {
      this.service.load('state is nonempty')
                  .then(result => this.setState({results: result.data}));
    }
  }

  render() {
    return (

        <button id="submit" onClick={this.load}/>

    );
  }
}

My test:

it('Calls service differently based on results', () => {

  const mockLoad = jest.fn((text) => {
    return new Promise((resolve, reject) => {
      resolve({data: [1, 2]});
    });
  });

  const serviceStub = {load: mockLoad};

  let component = mount(<App service={serviceStub}/>);
  let button = component.find("#submit");

  button.simulate('click');

  expect(mockLoad).toBeCalledWith('state is empty');

  button.simulate('click');

  //this assertion fails as the state has not updated and is still 'state is empty'
  expect(mockLoad).toBeCalledWith('state is nonempty');
});

As mentioned, the following works, but I'd rather not wrap the expect if there's a way around it:

setTimeout(() => {
    expect(mockLoad).toBeCalledWith('state is nonempty');
    done();
  }, 50);

I can also change how I mock the function to stub out the promise which will work:

const mockLoad = jest.fn((text) => {
  return {
    then: function (callback) {
      return callback({
        data : [1, 2]
      })
    }
  }
});

But I'd like to just return a promise.

Body:
Using Sinon with Sinon Stub Promise I was able to get this to work.  The stub promise library removes the async aspects of the promise, which means that state gets updated in time for the render:

const sinon = require('sinon');
const sinonStubPromise = require('sinon-stub-promise');
sinonStubPromise(sinon);

it('Calls service differently based on results', () => {

    const mockLoad = jest.fn((text) => {
        return sinon.stub().returnsPromise().resolves({data: [1, 2]})();
    });

    const serviceStub = {load: mockLoad};

    let component = mount(<App service={serviceStub}/>);
    let button = component.find("#submit");

    button.simulate('click');

    expect(mockLoad).toBeCalledWith('state is empty');

    button.simulate('click');

    expect(mockLoad).toBeCalledWith('state is nonempty');
});

See:

http://sinonjs.org/

https://github.com/substantial/sinon-stub-promise


问:
Disable Firefox auto-update in Linux
In my current project, I require Firefox browser to be run in headless mode using Xvfb and Selenium. In order to maintain compatibility between Selenium and Firefox, I want to maintain both of them at a specific version and stop Firefox auto-upgrades.

Currently, I am installing Firefox by the following steps:

Downloading a specific version of Firefox (wget http://kickstart/redhat/enterprise/fupdates/5.4C/x86_64/firefox-31.6.0-2.0.el5amzn.x86_64.rpm).

Installing the downloaded version (rpm -i firefox-31.6.0-2.0.el5amzn.x86_64.rpm).

"app.update.auto", "app.update.enabled" and "app.update.silent" configuration parameters (in "about:config") of the Firefox profile are disabled by default.
Does that mean it would not be auto-updated? Is it the case with such types of installation?

Any recommendation would be helpful.

答:
There are 3 files under the installation directory (at least on windows. So I believe, similar files should be on linux as well).

```<code>1. updater.exe
2. updater.ini
3. update-settings.init
</code>```

After removing these files, I was able to stop auto upgrade. Deleting these files will automatically change the auto update of firefox i.e. settings>advanced>Never check for update option as well.

Important: Remove these files before your first launch of the browser.

Hope this helps someone. :)

Title: Disable Firefox auto-update in Linux

Body:
There are 3 files under the installation directory (at least on windows. So I believe, similar files should be on linux as well).

1. updater.exe
2. updater.ini
3. update-settings.init

After removing these files, I was able to stop auto upgrade. Deleting these files will automatically change the auto update of firefox i.e. settings>advanced>Never check for update option as well.

Important: Remove these files before your first launch of the browser.

Hope this helps someone. :)


问:
Running Nginx on Raspberry Pi
I am currently trying to run a Node server on a Raspberry Pi. Full disclosure: I have no knowledge of servers, I am an interface designer and developer, so command lines are an unknown to me, don't expect prior knowledge.

I tried to follow many instructions on installing Nginx, but now it fails and I can't it to point to a line where I could check where it fails.

```<code>Job for nginx.service failed. See 'systemctl status nginx.service' and 'journalctl -xn' for details.
</code>```

The journalctl -xn says there is no file, and the other one gives me details, but I cant make heads or tails of it:

```<code>● nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled)
   Active: failed (Result: exit-code) since Fri 2017-07-07 12:43:36 EDT; 38s ago
  Process: 1071 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=1/FAILURE)
</code>```

I followed an instruction where it said that it's best to copy the sites-available/default rather than edit it, and here is what I did:

```<code>server {
  listen 80 default_server;
  listen [::]:80 default_server;

  root /var/www/osc-api/www;

  index index.html;

  server_name _;

  location / {
    # First attempt to serve request as file, then
    # as directory, then fall back to displaying a 404.
    try_files $uri $uri/ =404;
  }
}

server {
  listen 80 default_server;
  listen [::]:80 default_server;

  server_name osc-api;

  location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass http://127.0.0.1:3000/;
        proxy_redirect off;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        proxy_redirect off;
        proxy_set_header   X-Forwarded-Proto $scheme;
    }
}
</code>```

And yes, it is symlinked to the sites-enabled. I guess I am looking for info on how to understand how to fix this issue.

答:
Please verify that port 80 is not used by apache or some other process.
Please see this link
Nginx multiple server blocks listening to same port</p>

Title: Running Nginx on Raspberry Pi

Body:
I am currently trying to run a Node server on a Raspberry Pi. Full disclosure: I have no knowledge of servers, I am an interface designer and developer, so command lines are an unknown to me, don't expect prior knowledge.

I tried to follow many instructions on installing Nginx, but now it fails and I can't it to point to a line where I could check where it fails.

Job for nginx.service failed. See 'systemctl status nginx.service' and 'journalctl -xn' for details.

The journalctl -xn says there is no file, and the other one gives me details, but I cant make heads or tails of it:

● nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled)
   Active: failed (Result: exit-code) since Fri 2017-07-07 12:43:36 EDT; 38s ago
  Process: 1071 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=1/FAILURE)

I followed an instruction where it said that it's best to copy the sites-available/default rather than edit it, and here is what I did:

server {
  listen 80 default_server;
  listen [::]:80 default_server;

  root /var/www/osc-api/www;

  index index.html;

  server_name _;

  location / {
    # First attempt to serve request as file, then
    # as directory, then fall back to displaying a 404.
    try_files $uri $uri/ =404;
  }
}

server {
  listen 80 default_server;
  listen [::]:80 default_server;

  server_name osc-api;

  location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass http://127.0.0.1:3000/;
        proxy_redirect off;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        proxy_redirect off;
        proxy_set_header   X-Forwarded-Proto $scheme;
    }
}

And yes, it is symlinked to the sites-enabled. I guess I am looking for info on how to understand how to fix this issue.