问:
Why do people use __ (double underscore) so much in C++
I was taking a look through some open-source C++ code and I noticed a lot of double underscores used within in the code, mainly at the start of variable names.

```<code>return __CYGWIN__;
</code>```

Just wondering: Is there a reason for this, or is it just some people's code styles?  I would think that it makes it hard to read.

答:
Double underscores are reserved to the implementation

The top voted answer cites Programming in C++: Rules and Recommendations:

"The use of two underscores (`__') in identifiers is reserved for the compiler's internal use according to the ANSI-C standard."

However, after reading a few C++ and C standards, I was unable to find any mention of underscores being restricted to just the compiler's internal use.  The standards are more general, reserving double underscores for the implementation.

C++

C++ (current working draft, accessed 2019-5-26) states in lex.name:

Each identifier that contains a double underscore __ or begins with an underscore followed by an uppercase letter is reserved to the implementation for any use.

Each identifier that begins with an underscore is reserved to the implementation for use as a name in the global namespace.

C

Although this question is specific to C++, I've cited relevant sections from C standards 99 and 17:

C99 section 7.1.3

All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use.

All identifiers that begin with an underscore are always reserved for use as identifiers with file scope in both the ordinary and tag name
  spaces.

C17 says the same thing as C99.

What is the implementation?

For C/C++, the implementation loosely refers to the set resources necessary to produce an executable from user source files. This includes:

preprocessor

compiler

linker

standard library

Example implementations

There are a number of different C++ implementations mentioned on Wikipedia. (no anchor link, ctrl+f "implementation")

Here's an example of Digital Mars' C/C++ implementation reserving some keywords for a feature of theirs.

OwnerDisplayName: Nathan

Body:
I was taking a look through some open-source C++ code and I noticed a lot of double underscores used within in the code, mainly at the start of variable names.

return __CYGWIN__;

Just wondering: Is there a reason for this, or is it just some people's code styles?  I would think that it makes it hard to read.

LastEditorDisplayName: Nathan


来源: stackexchange

问:
Difference between the eden space usage values reported by jcmd and java.lang.management.MemoryUsage
I want to monitor heap usage of my code using java.lang.management.MemoryUsage. In the example below, I create a bunch of entries in a HashSet and then inspect the heap usage. I was expecting to see a non-zero value for the used memory of eden space. To my surprise, I see a zero value for eden space usage and non-zero value for survivor space usage.
This does not match with the heap info values printed by jcmd command, which shows non-zero usage of the eden space.
Can someone please help me understand the reason behind this?

I am using ParllelOldGC (-XX:+UseParallelOldGC), OpenJDK 11.0.2 on Linux.

I tried searching about this on various forums but could not find relevant information.

```<code>public HeapUsage() {
    System.out.println("Before ");
    printHeapUsage();
    HashSet<String> set = new HashSet<>();
    for (int i = 0; i<10000000; i++) {
        set.add(String.valueOf(i));
    }
    System.out.println("After");
    printHeapUsage();

}
public static void main(String[] args) throws InterruptedException {
    new HeapUsage();
    Thread.sleep(1000000);
}

private void printHeapUsage() {
    for (MemoryPoolMXBean mpbean :
         ManagementFactory.getMemoryPoolMXBeans()) {
        MemoryUsage usage = mpbean.getCollectionUsage();
        if (usage != null) {
            long max = usage.getMax();
            long used = usage.getUsed();
            System.out.println(mpbean.getName() + " Used " + used + ", Max " + max);
        }
    }
}
</code>```

Java code output -

Before
PS Old Gen Used 0, Max 21473787904

PS Survivor Space Used 0, Max 89128960

PS Eden Space Used 0, Max 10558111744

After

PS Old Gen Used 0, Max 21473787904

PS Survivor Space Used 89096256, Max 89128960

PS Eden Space Used 0, Max 10558111744

jcmd output -

jcmd 45766 GC.heap_info
45766:
 PSYoungGen      total 611840K, used 541937K [0x0000000580100000, 0x00000005cac00000, 0x0000000800000000)

eden space 524800K, 86% used [0x0000000580100000,0x000000059bd44778,0x00000005a0180000)

from space 87040K, 99% used [0x00000005a0180000,0x00000005a5678040,0x00000005a5680000)

to   space 87040K, 0% used [0x00000005c5700000,0x00000005c5700000,0x00000005cac00000)

ParOldGen       total 1398272K, used 385048K [0x0000000080200000, 0x00000000d5780000, 0x0000000580100000)

object space 1398272K, 27% used [0x0000000080200000,0x0000000097a06000,0x00000000d5780000)

Metaspace       used 6287K, capacity 6411K, committed 6656K, reserved 1056768K

class space    used 586K, capacity 653K, committed 768K, reserved 1048576K

答: I should have read the Javadoc carefully. MemoryPoolMXBean.getCollectionUsage() returns memory usage after the most recent garbage collection. It is normal for eden space to be empty after a GC. jcmd GC.heap_info gives the current heap usage (equivalent of MemoryPoolMXBean.getUsage(). Therefore, in this example, jcmd output does not match with the output of code-snippet in the question.

ContentLicense: CC BY-SA 4.0

Body:
I want to monitor heap usage of my code using java.lang.management.MemoryUsage. In the example below, I create a bunch of entries in a HashSet and then inspect the heap usage. I was expecting to see a non-zero value for the used memory of eden space. To my surprise, I see a zero value for eden space usage and non-zero value for survivor space usage.
This does not match with the heap info values printed by jcmd command, which shows non-zero usage of the eden space.
Can someone please help me understand the reason behind this?

I am using ParllelOldGC (-XX:+UseParallelOldGC), OpenJDK 11.0.2 on Linux.

I tried searching about this on various forums but could not find relevant information.

public HeapUsage() {
    System.out.println("Before ");
    printHeapUsage();
    HashSet<String> set = new HashSet<>();
    for (int i = 0; i<10000000; i++) {
        set.add(String.valueOf(i));
    }
    System.out.println("After");
    printHeapUsage();

}
public static void main(String[] args) throws InterruptedException {
    new HeapUsage();
    Thread.sleep(1000000);
}

private void printHeapUsage() {
    for (MemoryPoolMXBean mpbean :
         ManagementFactory.getMemoryPoolMXBeans()) {
        MemoryUsage usage = mpbean.getCollectionUsage();
        if (usage != null) {
            long max = usage.getMax();
            long used = usage.getUsed();
            System.out.println(mpbean.getName() + " Used " + used + ", Max " + max);
        }
    }
}

Java code output -

Before
PS Old Gen Used 0, Max 21473787904

PS Survivor Space Used 0, Max 89128960

PS Eden Space Used 0, Max 10558111744

After

PS Old Gen Used 0, Max 21473787904

PS Survivor Space Used 89096256, Max 89128960

PS Eden Space Used 0, Max 10558111744

jcmd output -

jcmd 45766 GC.heap_info
45766:
 PSYoungGen      total 611840K, used 541937K [0x0000000580100000, 0x00000005cac00000, 0x0000000800000000)

eden space 524800K, 86% used [0x0000000580100000,0x000000059bd44778,0x00000005a0180000)

from space 87040K, 99% used [0x00000005a0180000,0x00000005a5678040,0x00000005a5680000)

to   space 87040K, 0% used [0x00000005c5700000,0x00000005c5700000,0x00000005cac00000)

ParOldGen       total 1398272K, used 385048K [0x0000000080200000, 0x00000000d5780000, 0x0000000580100000)

object space 1398272K, 27% used [0x0000000080200000,0x0000000097a06000,0x00000000d5780000)

Metaspace       used 6287K, capacity 6411K, committed 6656K, reserved 1056768K

class space    used 586K, capacity 653K, committed 768K, reserved 1048576K


问:
Connect SQL Server from SQL Developer
I searched through all threads on the web available, but none could help me.

I am trying to connect to SQL Server engine from SQL Developer. In order to do that I enabled Named Pipes and TCP/IP from SQL Configuration Manager.

Then I tried different drivers:

I tried Microsoft JDBC driver for SQL Server - I cannot choose in connection manager SQL Server database type, so it does not work..

I tried jTDS driver instead, and it worked - I can choose SQL Server database type, but then all I get is an error informing that it cannot connect to Microsoft SQL Server on localhost (I tried localhost, name of my computer, none of which worked).

Is there anything more I can do?

EDIT

This is what I have so far:

SECOND EDIT

I had more problems:

With error saying

Status: Failur-I/O Error: SSO Failed: Native SSPI library not loaded. Check the java.library.path system property

Using windows authentication, I still got asked for username and password.

(All details and solutions in my answer below)

答:
Actually there were more problems, which I'll post here along with solutions:

In order to ba able to connect SQL Server database type from SQL developer it is needed to install jTDS driver, as already mentioned. Other types are not supported by SQL Developer.

Next thing was to configure with SQL Configuration Manager (the easiest way IMO) SQL Server to listen on IP port 1433, not dynamic, as was previously set. In order to do that in configuration manager I had to go to SQL Server Network Configuration and make appropriate changes. More here.

Next I had problem:

Status: Failur-I/O Error: SSO Failed: Native SSPI library not loaded. Check the java.library.path system property

Which was the fault of missing file, solution was placing file ntlmauth.dll to the /jdk/bin in SQL Developer directory.

I chose Windows authentication, which apparently is not supported by jTDS, so I needed to create user in SQL Server, which I use to connect SQL Server from SQL Developer.

After all that, I had it working.

Title: Connect SQL Server from SQL Developer


问:
I keep getting the same error in my error logs on my apache server using cpanel
```<code>cPanel Version  11.28.87
Theme   x3
Apache version  1.3.42
PHP version     5.2.13
MySQL version   5.0.92-community
Architecture    i686
Operating system    linux
</code>```

I noticed in the Error Log that I was getting the same error repeatedly. A simple missing .gif that was being requested.

```<code>[Tue Apr 12 12:12:23 2011] [error] [client --.---.---.---] File does not exist: /public_html/themes/3col_blue/images/dogcat.gif
</code>```

So I thought well lets just put that .gif (our logo) there...

Now I am getting a whole slew of errors regarding file does not exist that look like this:

```<code>[Tue Apr 12 02:27:47 2011] [error] [client --.---.---.---] File does not exist: /home/--------/public_html/index.php+++++++++++++++++++++++++++++++++Result:+\xe8\xf1\xef\xee\xeb\xfc\xe7\xee\xe2\xe0\xed+\xed\xe8\xea\xed\xe5\xe9\xec+"reltWeiweessy";+\xe7\xe0\xf0\xe5\xe3\xe8\xf1\xf2\xf0\xe8\xf0\xee\xe2\xe0\xeb\xe8\xf1\xfc+(\xe2\xea\xeb\xfe\xf7\xe5\xed+\xf0\xe5\xe6\xe8\xec+\xf2\xee\xeb\xfc\xea\xee+\xf0\xe5\xe3\xe8\xf1\xf2\xf0\xe0\xf6\xe8\xe8);
[Tue Apr 12 02:27:42 2011] [error] [client --.---.---.---] File does not exist: /home/--------/public_html/index.php+++++++++++++++++++++++++++++++++Result:+\xe8\xf1\xef\xee\xeb\xfc\xe7\xee\xe2\xe0\xed+\xed\xe8\xea\xed\xe5\xe9\xec+"reltWeiweessy";+\xe7\xe0\xf0\xe5\xe3\xe8\xf1\xf2\xf0\xe8\xf0\xee\xe2\xe0\xeb\xe8\xf1\xfc+(\xe2\xea\xeb\xfe\xf7\xe5\xed+\xf0\xe5\xe6\xe8\xec+\xf2\xee\xeb\xfc\xea\xee+\xf0\xe5\xe3\xe8\xf1\xf2\xf0\xe0\xf6\xe8\xe8);
</code>```

how did I make this go from bad to worse?

答: Are there referers for those particular hits in the access_log? Looks like someone/something is pointing at your site with a badly constructed link.</p>

ContentLicense: CC BY-SA 3.0

Body:
cPanel Version  11.28.87
Theme   x3
Apache version  1.3.42
PHP version     5.2.13
MySQL version   5.0.92-community
Architecture    i686
Operating system    linux

I noticed in the Error Log that I was getting the same error repeatedly. A simple missing .gif that was being requested.

[Tue Apr 12 12:12:23 2011] [error] [client --.---.---.---] File does not exist: /public_html/themes/3col_blue/images/dogcat.gif

So I thought well lets just put that .gif (our logo) there...

Now I am getting a whole slew of errors regarding file does not exist that look like this:

[Tue Apr 12 02:27:47 2011] [error] [client --.---.---.---] File does not exist: /home/--------/public_html/index.php+++++++++++++++++++++++++++++++++Result:+\xe8\xf1\xef\xee\xeb\xfc\xe7\xee\xe2\xe0\xed+\xed\xe8\xea\xed\xe5\xe9\xec+"reltWeiweessy";+\xe7\xe0\xf0\xe5\xe3\xe8\xf1\xf2\xf0\xe8\xf0\xee\xe2\xe0\xeb\xe8\xf1\xfc+(\xe2\xea\xeb\xfe\xf7\xe5\xed+\xf0\xe5\xe6\xe8\xec+\xf2\xee\xeb\xfc\xea\xee+\xf0\xe5\xe3\xe8\xf1\xf2\xf0\xe0\xf6\xe8\xe8);
[Tue Apr 12 02:27:42 2011] [error] [client --.---.---.---] File does not exist: /home/--------/public_html/index.php+++++++++++++++++++++++++++++++++Result:+\xe8\xf1\xef\xee\xeb\xfc\xe7\xee\xe2\xe0\xed+\xed\xe8\xea\xed\xe5\xe9\xec+"reltWeiweessy";+\xe7\xe0\xf0\xe5\xe3\xe8\xf1\xf2\xf0\xe8\xf0\xee\xe2\xe0\xeb\xe8\xf1\xfc+(\xe2\xea\xeb\xfe\xf7\xe5\xed+\xf0\xe5\xe6\xe8\xec+\xf2\xee\xeb\xfc\xea\xee+\xf0\xe5\xe3\xe8\xf1\xf2\xf0\xe0\xf6\xe8\xe8);

how did I make this go from bad to worse?


问:
Insert data to MySQL with Ajax in Laravel
I have a JS variable which store a JSON value in my blade view and I want to insert it to MySQL in Laravel project. But I don't know how to write it right. This is what I tried in my blade view:

      <button id="saveBtn" type="button">Save To Database</button>

```

But when I run it, it appear error said: jquery.js:8630 POST http://localhost/saveToDatabase 404 (Not Found).

How I can fix this?

Thank you very much!

答: The route is not selected correctly. http://localhost/saveToDatabase is not find for do something</p>

Body:
I have a JS variable which store a JSON value in my blade view and I want to insert it to MySQL in Laravel project. But I don't know how to write it right. This is what I tried in my blade view:

      <button id="saveBtn" type="button">Save To Database</button>

But when I run it, it appear error said: jquery.js:8630 POST http://localhost/saveToDatabase 404 (Not Found).

How I can fix this?

Thank you very much!


问:
Mac - Can’t install Homebrew
I tried to install Homebrew like this:

```<code>ruby -e "$(curl -fsSkL raw.github.com/mxcl/homebrew/go)"
</code>```

It didn’t install correctly so I closed Terminal and tried again. Now it displays me the following message:

```<code>It appears Homebrew is already installed. If your intent is to reinstall you
should do the following before running this installer again:
rm -rf /usr/local/Cellar /usr/local/.git && brew cleanup
</code>```

I tried to do that but without success. The following message is displayed:

```<code>brew: command not found
</code>```

So, the problem is that Homebrew is installed but actually it is not installed. Any suggestions how to solve this problem? Thank you!

答:
This is the most recent one that works for me.

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

I found it here in case it is updated later. https://brew.sh/

Title: Mac - Can’t install Homebrew

Body:
I tried to install Homebrew like this:

ruby -e "$(curl -fsSkL raw.github.com/mxcl/homebrew/go)"

It didn’t install correctly so I closed Terminal and tried again. Now it displays me the following message:

It appears Homebrew is already installed. If your intent is to reinstall you
should do the following before running this installer again:
rm -rf /usr/local/Cellar /usr/local/.git && brew cleanup

I tried to do that but without success. The following message is displayed:

brew: command not found

So, the problem is that Homebrew is installed but actually it is not installed. Any suggestions how to solve this problem? Thank you!


问:
How to remove the unwanted mark from date input field?

I need remove the x mark from the input, I use boostrap 4

This is the Code

```<code> <div class="form-group">
                    <center>Ingresa tu fecha de nacimiento</center>
                    <br>
                    <input type="date" class="form-control" name="bday" placeholder="Ingresa tu fecha de nacimiento" value="{{bday}}" style="text-align: center">
                </div>
</code>```

I want the x and arrows to be erased

答:
You could use the psuedo-class here

In CSS put this code

```<code>input[type=date]::-webkit-inner-spin-button {
    -webkit-appearance: none;
    display: none;
}
</code>```

then for the input tag you need to add required like this

```<code> <input type='date' required>
</code>```

Body:
I need remove the x mark from the input, I use boostrap 4

This is the Code

                    Ingresa tu fecha de nacimiento

                    <input type="date" class="form-control" name="bday" placeholder="Ingresa tu fecha de nacimiento" value="{{bday}}" style="text-align: center">

I want the x and arrows to be erased

Body:
You could use the psuedo-class here

In CSS put this code

input[type=date]::-webkit-inner-spin-button {
    -webkit-appearance: none;
    display: none;
}

then for the input tag you need to add required like this

 <input type='date' required>


问:
laravel updating editing database record - getting error when submitting the form
I am using this code to edit database record :

```<code>public function service_edit($id)
{
    $service = Service::find($id);
    return view('Super_Admin/service/.service_edit')->with('service', $service);
}

public function service_update(Request $request, $id)
{
    $service = Service::find($id);
    $input['title_name'] = strtoupper ($request['title_name']);
    $input['link'] = strtoupper ($request['link']);
    $input['note'] = strtoupper ($request['note']);
    $input['image'] = time().'.'.$request->

    image->getClientOriginalExtension();
    $folder1 = public_path('WEBSITE-FILE/SERVICE/1');
    $path1 = $folder1 . $input['image']; // path 1
    $request->image->move($folder1, $input['image']);
    $path2 = public_path('WEBSITE-FILE/SERVICE/2').$input['image'];// path 2
    $path3 = public_path('WEBSITE-FILE/SERVICE/3'). $input['image']; // path 3
    $path4 = public_path('WEBSITE-FILE/SERVICE/4'). $input['image']; // path 4

    \File::copy($path1, $path2);
    \File::copy($path1, $path3);
    \File::copy($path1, $path4);

    $service->save();

    return back()->with('success','UPDATED SUCCESSFULLY .');
}
</code>```

I am facing this error when I submit the form

"Call to a member function save() on array"

答:
$service is where you have to save, not $input.

You must to assign the values of the request to the $service variable (Service Object) and then save it.

Try in this way:

```<code>public function service_update(Request $request, $id)
{
    $service = Service::find($id);
    $service->title_name = strtoupper ($request->title_name);
    $service->link = strtoupper ($request->link);
    $service->note = strtoupper ($request->note);
    $service->image = time().'.'.$request->file('image')->getClientOriginalExtension();

    // ...

    $service->save();

    return back()->with('success','UPDATED SUCCESSFULLY .');
}
</code>```

Body:
I am using this code to edit database record :

public function service_edit($id)
{
    $service = Service::find($id);
    return view('Super_Admin/service/.service_edit')->with('service', $service);
}

public function service_update(Request $request, $id)
{
    $service = Service::find($id);
    $input['title_name'] = strtoupper ($request['title_name']);
    $input['link'] = strtoupper ($request['link']);
    $input['note'] = strtoupper ($request['note']);
    $input['image'] = time().'.'.$request->

    image->getClientOriginalExtension();
    $folder1 = public_path('WEBSITE-FILE/SERVICE/1');
    $path1 = $folder1 . $input['image']; // path 1
    $request->image->move($folder1, $input['image']);
    $path2 = public_path('WEBSITE-FILE/SERVICE/2').$input['image'];// path 2
    $path3 = public_path('WEBSITE-FILE/SERVICE/3'). $input['image']; // path 3
    $path4 = public_path('WEBSITE-FILE/SERVICE/4'). $input['image']; // path 4

    \File::copy($path1, $path2);
    \File::copy($path1, $path3);
    \File::copy($path1, $path4);

    $service->save();

    return back()->with('success','UPDATED SUCCESSFULLY .');
}

I am facing this error when I submit the form

"Call to a member function save() on array"

Body:
$service is where you have to save, not $input.

You must to assign the values of the request to the $service variable (Service Object) and then save it.

Try in this way:

public function service_update(Request $request, $id)
{
    $service = Service::find($id);
    $service->title_name = strtoupper ($request->title_name);
    $service->link = strtoupper ($request->link);
    $service->note = strtoupper ($request->note);
    $service->image = time().'.'.$request->file('image')->getClientOriginalExtension();

    // ...

    $service->save();

    return back()->with('success','UPDATED SUCCESSFULLY .');
}


问:
Take url as input from a textbox, and return contents of the url
I cannot find a question that does anything remotely similar.
I know how to build a text box in React or HTML, but I'm not sure how to parse the inputs as a URL, returning a display of said content.

Basically I need:
- A text box which takes a URL as an input
- Return said contents of URL
- Store text in URL in an array

There are a few other things to do, but those have been my biggest holdups.

This is a textbox in HTML:
https://github.com/mdn/learning-area/blob/master/html/forms/your-first-HTML-form/first-form-styled.html

This is a textbox in React:
https://codepen.io/gaearon/pen/VmmPgp?editors=0010

I've successfully set up both to take inputs, but not sure how to display contents of said input. I know there's something called an Ajax request? But the documentation was hard to follow.

```<code>input = url
display(url)
newList = list(text(url))
</code>```

答:
If I understood this correctly then this is what you want,</p>

```<code><textarea ref="searchURL" placeholder="Enter URL..." onChange={this.getData}/>
</code>```

```<code>getData(){
   let url = this.refs.searchFeed.value;
   this.refs.searchFeed.value = '';

   fetch(url)
     .then(response => {
         return response.json();
      })
      .then((res) => {
        console.log(res);
      })
      .catch((error) => {
        console.log("error", error)
        reject(error);
      });

}
</code>```

Body:
I cannot find a question that does anything remotely similar.
I know how to build a text box in React or HTML, but I'm not sure how to parse the inputs as a URL, returning a display of said content.

Basically I need:
- A text box which takes a URL as an input
- Return said contents of URL
- Store text in URL in an array

There are a few other things to do, but those have been my biggest holdups.

This is a textbox in HTML:
https://github.com/mdn/learning-area/blob/master/html/forms/your-first-HTML-form/first-form-styled.html

This is a textbox in React:
https://codepen.io/gaearon/pen/VmmPgp?editors=0010

I've successfully set up both to take inputs, but not sure how to display contents of said input. I know there's something called an Ajax request? But the documentation was hard to follow.

input = url
display(url)
newList = list(text(url))

Body:
If I understood this correctly then this is what you want,

<textarea ref="searchURL" placeholder="Enter URL..." onChange={this.getData}/>

getData(){
   let url = this.refs.searchFeed.value;
   this.refs.searchFeed.value = '';

   fetch(url)
     .then(response => {
         return response.json();
      })
      .then((res) => {
        console.log(res);
      })
      .catch((error) => {
        console.log("error", error)
        reject(error);
      });

}


问:
CRUD methods with PHP, JS/jQuery, and a little AJAX
I've been working on a system where you can create-read-update-delete to/from a table in a SQLite database.  So far I've only written the create and view methods (easy).

Now, I have ran into a roadblock on deciding how to go about deleting and updating items.  On the view page, there is query to the database through php and a generation of the table (echoed through php into html).  There is also a button added next to each row that looks like a little trash can to delete the row.

How can I use AJAX to simultaneously delete the row from the html table and sqlite table?  A more definitive question would be, how can I link each button to each row and query the database when the button is clicked?

Here is the generated table:

```<code>foreach($result as $entry){
 echo  '<tr>' . '<td>'. $entry['department']. ' ' . $entry['CRN']. '</td>' .
    '<td>'. $entry['title'] . '</td>' .
    '<td>'. $entry['addDate'] . '</td>'.
    '<td><button class="fg-button fg-button-icon-left ui-state-default ui-corner-all"><span class="ui-icon ui-icon-trash"></span></button></td>'.'</tr>';
}
</code>```

答:
Create a PHP controller and action.  It has to take an ID as a parameter and it should execute a delete command against your database using that ID.  Ideally, it will accept only DELETE requests (not GET or POST).  This isn't always possible because some browsers don't support DELETE HTTP requests.

on your front end, create HTML and javascript that looks like this:

HTML:

```<code><input id="clickMe" type="button" value="Delete Button" data-rowId="12"/>
</code>```

Javascript:

```<code>$(document).ready(function(){
    $('#clickMe').click(function(){
        // send the delete request
        $.ajax({
            url: '/myEntity/delete',
            data: {id: $(this).data('rowId')},
            type: 'DELETE',
            // removes the row only if the delete succeeds
            success: function(){ $(this).parents('tr').remove(); }
        });
    });
});
</code>```

Change type: 'DELETE' to type: 'POST' if you're working with browsers that don't support DELETE.

Body:
I've been working on a system where you can create-read-update-delete to/from a table in a SQLite database.  So far I've only written the create and view methods (easy).

Now, I have ran into a roadblock on deciding how to go about deleting and updating items.  On the view page, there is query to the database through php and a generation of the table (echoed through php into html).  There is also a button added next to each row that looks like a little trash can to delete the row.

How can I use AJAX to simultaneously delete the row from the html table and sqlite table?  A more definitive question would be, how can I link each button to each row and query the database when the button is clicked?

Here is the generated table:

foreach($result as $entry){
 echo  '
' . ''. $entry['department']. ' ' . $entry['CRN']. '	' .
    ''. $entry['title'] . '	' .
    ''. $entry['addDate'] . '	'.
    '<button class="fg-button fg-button-icon-left ui-state-default ui-corner-all"></button>	'.'
';
}

Body:
Create a PHP controller and action.  It has to take an ID as a parameter and it should execute a delete command against your database using that ID.  Ideally, it will accept only DELETE requests (not GET or POST).  This isn't always possible because some browsers don't support DELETE HTTP requests.

on your front end, create HTML and javascript that looks like this:

HTML:

<input id="clickMe" type="button" value="Delete Button" data-rowId="12"/>

Javascript:

$(document).ready(function(){
    $('#clickMe').click(function(){
        // send the delete request
        $.ajax({
            url: '/myEntity/delete',
            data: {id: $(this).data('rowId')},
            type: 'DELETE',
            // removes the row only if the delete succeeds
            success: function(){ $(this).parents('tr').remove(); }
        });
    });
});

Change type: 'DELETE' to type: 'POST' if you're working with browsers that don't support DELETE.


问:
What will be regular expression of domain URL of "www.google.com"?
What will be the regex for RegularExpressionValidator in asp.net for domain name like "www.google.com"?

Valid Cases:

www.google.com

www.youwebsite.com

Invalid Cases:

http://www.google.com

https://www.google.com

google.com

www.google

Currently I used (?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9] but it fails for invalid case number 3 and 4.

答:
This matches the part you want.

```<code>\bwww\.[a-zA-Z0-9]{2,256}\.com\b
</code>```

But easier way to go with such a simple pattern is to use StartsWith, EndsWith, and then check what is in between.

Body:
This matches the part you want.

\bwww\.[a-zA-Z0-9]{2,256}\.com\b

But easier way to go with such a simple pattern is to use StartsWith, EndsWith, and then check what is in between.


问:
Why can I not authenticate with peripheral device?
Language version: Microsoft Visual C++ 2013 Redistributable (x85) – 12.0.30501

Platform version: 4.0

Operating system: Microsoft Windows 8.1 6.3.9600 Build 9600

Any other relevant software:

Visual Studio 2013 Community with update 4

Halo Configuration Control Panel

Halo Hub

What I am trying to do

I am trying to communicate with a peripheral device that is using the OSDP protocol.

What is actually happening

I get the following from the output panel in visual studio.

Received valid packet of 326 bytes

Received authentication response from OSDP Hub

Session Key > E856417D8B0364313A4B8F0D89524273F0F70AB1DFF8E950FE96905FECAC9F2F

Received packet after 3 ms

Received valid packet of 4 bytes

Received authentication denial from OSDP Hub

Received packet after 0 ms

Performing a search on 0 devices

Rough Copy

```<code>'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Work\velox\admins-velox-project\proprietary\rtos\apps\chibios\utilities\osdp_client\Debug_msvc\osdp_client_mswud_vc11.exe'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ntdll.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded

'C:\Windows\SysWOW64\kernel32.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded

'C:\Windows\SysWOW64\KernelBase.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\user32.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\gdi32.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\comdlg32.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\winspool.drv'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\winmm.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\shell32.dll'. Cannot find or open the PDB file.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\WinSxS\x86_microsoft.windows.common-controls_6595b64144ccf1df_6.0.9600.18006_none_a9ec6aab013aafee\comctl32.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ole32.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\oleaut32.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\rpcrt4.dll'. Cannot find or open the PDB file.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\advapi32.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\wsock32.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ws2_32.dll'. Cannot find or open the PDB file.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcp120d.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcr120d.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcrt.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\shlwapi.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\winmmbase.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\combase.dll'. Cannot find or open the PDB file.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\sechost.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\sspicli.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\nsi.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\cfgmgr32.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\devobj.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\cryptbase.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\SHCore.dll'. Cannot find or open the PDB file.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\bcryptprimitives.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\imm32.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msctf.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\kernel.appcore.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\uxtheme.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\ProgramData\Internet Helper Anti-phishing\internetHelper_antiphishing.dll'. Module was built without symbols.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\version.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\dwmapi.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\IconCodecService.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\WindowsCodecs.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\WinSxS\x86_microsoft.windows.gdiplus_6595b64144ccf1df_1.1.9600.18696_none_dae05f525bc50fb1\GdiPlus.dll'. Cannot find or open the PDB file.
Password = 1234
Private key = 03ac674216f3e15c761ee1a5e255f067
Added 0 items
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\mswsock.dll'. Cannot find or open the PDB file.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\dnsapi.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\FWPUCLNT.DLL'. Cannot find or open the PDB file.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\rasadhlp.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\cryptsp.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\rsaenh.dll'. Cannot find or open the PDB file.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\bcrypt.dll'. Symbols loaded.
..\..\src\common\strvararg.cpp(658): assert "n <= parser.nargs" failed in `anonymous-namespace'::DoGetArgumentType(): more arguments than format string specifiers? [in thread cb4]
First-chance exception at 0x76165608 (KernelBase.dll) in osdp_client_mswud_vc11.exe: 0x00001976.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\dbghelp.dll'. Symbols loaded.
DBGHELP: Symbol Search Path: .
DBGHELP: .\wkernelbase.pdb - file not found
DBGHELP: .\dll\wkernelbase.pdb - file not found
DBGHELP: .\symbols\dll\wkernelbase.pdb - file not found
DBGHELP: wkernelbase.pdb - file not found
DBGHELP: KERNELBASE - export symbols
DBGHELP: .\osdp_client_mswud_vc11.pdb - file not found
DBGHELP: .\exe\osdp_client_mswud_vc11.pdb - file not found
DBGHELP: .\symbols\exe\osdp_client_mswud_vc11.pdb - file not found
Received valid packet of 326 bytes
Received authentication response from OSDP Hub
Session Key > 63B2D0C583090EFD994B5AFE12A417A07F406CEE1F64DCB1613703B45428E32E
Received packet after 3 ms
Received valid packet of 4 bytes
Received authentication denial from OSDP Hub
Received packet after 2 ms
DBGHELP: osdp_client_mswud_vc11 - private symbols & lines
        C:\Work\velox\admins-velox-project\proprietary\rtos\apps\chibios\utilities\osdp_client\Debug_msvc\osdp_client_mswud_vc11.pdb
DBGHELP: .\msvcr120d.i386.pdb - file not found
DBGHELP: .\dll\msvcr120d.i386.pdb - file not found
DBGHELP: .\symbols\dll\msvcr120d.i386.pdb - file not found
DBGHELP: msvcr120d.i386.pdb - file not found
DBGHELP: MSVCR120D - export symbols
DBGHELP: .\wntdll.pdb - file not found
DBGHELP: .\dll\wntdll.pdb - file not found
DBGHELP: .\symbols\dll\wntdll.pdb - file not found
DBGHELP: wntdll.pdb - file not found
DBGHELP: ntdll - export symbols
DBGHELP: .\wkernel32.pdb - file not found
DBGHELP: .\DLL\wkernel32.pdb - file not found
DBGHELP: .\symbols\DLL\wkernel32.pdb - file not found
DBGHELP: wkernel32.pdb - file not found
DBGHELP: KERNEL32 - export symbols
</code>```

Here is the actual code;

```<code>case OSDP_HUB:
{
    bool ipv4;
    uint8_t ip_addr[16];

    osdp_hub_messages* hub = (osdp_hub_messages*)m_packets.get_data( OSDP_HUB );

    // goes from here to decode method ondown
    hub->decode( (uint8_t*)buffer, m_packets.get_header()->m_data.length );

    if ( hub->get_msg_type() == OSDP_HUB_TCP_IND )
    {
        hub->get_ip_addr( &ipv4, ip_addr );

        if ( hub->get_enable() )
        {
                        // Device has connected...
            wxLogDebug( wxT("Device connected on IP address %d.%d.%d.%d : %u"),
                ip_addr[0], ip_addr[1], ip_addr[2], ip_addr[3], hub->get_tcp_port() );

            m_tcp_device_connected = true;

                        // Assign an address
                        /// @todo Create an address generation function
            std::vector<uint8_t> ip_addr_vec;
            ip_addr_vec.resize( ipv4? 4 : 16 );
            memcpy( &ip_addr_vec[0], ip_addr, ipv4? 4 : 16 );
            m_tcp_map[0] = ip_addr_vec;

            MyCustomEvent customEvent( MyCustomCommandEvent, ID_EVENT_TCP_ADD );
            customEvent.SetText( _T( "SocketThread::Entry() ID_EVENT_TCP_ADD" ) );
            wxPostEvent( m_parent, customEvent );
        }
        else
        {
                        // Device has disconnected...
            wxLogDebug( wxT("Device disconnected on IP address %d.%d.%d.%d"),
                ip_addr[0], ip_addr[1], ip_addr[2], ip_addr[3] );

                        // Change the UI to display the nearest device on the list
            MyCustomEvent customEvent( MyCustomCommandEvent, ID_EVENT_TCP_REMOVE );
            customEvent.SetText( _T( "SocketThread::Entry() ID_EVENT_TCP_REMOVE" ) );
            wxPostEvent( m_parent, customEvent );
        }
    }
    else if ( hub->get_msg_type() == OSDP_HUB_AUTH_1 )
    {
        wxLogDebug( wxT("Received authentication response from OSDP Hub") );

        m_auth1_received = true;

        std::string salt = hub->get_salt();
        std::string key = hub->get_publickey();
        m_srp_auth->gen_client_session_key( salt, key );
        wxLogDebug( wxT("Session Key > %s"), m_srp_auth->get_session_key() );
        m_srp_auth->gen_client_cryptogram();
    }
    else if ( hub->get_msg_type() == OSDP_HUB_AUTH_3 ) // skips here
    {
        wxLogDebug( wxT("Received authentication accept from OSDP Hub") );

        m_auth3_received = true;
    }
    else if ( hub->get_msg_type() == OSDP_HUB_AUTH_4 ) // enters in here
    {
        wxLogDebug( wxT("Received authentication denial from OSDP Hub") );

        m_auth4_received = true;
    }
    else if ( hub->get_msg_type() == OSDP_HUB_PONG )
    {
        wxLogDebug( wxT("Received PONG from OSDP Hub") );

        m_pong_received = true;

        int32_t length;
        hub->encode( (uint8_t*)msg, &length );
        m_clientSocket->Write( (char*)msg, length );
    }
} break;

//comes in here
int32_t osdp_hub_messages::decode( uint8_t* buffer, int32_t len )
{
    return osdp_hub_messages_decode( &m_osdp_hub_messages, buffer, len );

} // decode()

// then comes in here
int32_t osdp_hub_messages_decode( osdp_hub_messages_t* data, uint8_t* buffer, int32_t len )
{
    //goes from OSDP_HUB_AUTH_2 t0 OSDP_HUB_AUTH_4
    //never hits OSDP_HUB_START or OSDP_HUB_TCP_IND
    data->hub_msg = (osdp_hub_e)buffer[0];

    switch ( data->hub_msg )
    {
        case OSDP_HUB_START: return decode_start( data, buffer+1, len ); break;
        case OSDP_HUB_TCP_IND: return decode_tcp_ind( data, buffer+1, len ); break;
        case OSDP_HUB_AUTH_0: return decode_auth_0( data, buffer+1, len ); break;
        case OSDP_HUB_AUTH_1: return decode_auth_1( data, buffer+1, len ); break;
        case OSDP_HUB_AUTH_2: return decode_auth_2( data, buffer+1, len ); break;
        case OSDP_HUB_AUTH_3: return decode_auth_2( data, buffer+1, len ); break;
        case OSDP_HUB_AUTH_4: return decode_auth_4( data, buffer+1, len ); break;
        case OSDP_HUB_PING: return decode_ping( data, buffer+1, len ); break;
        case OSDP_HUB_PONG: return decode_pong( data, buffer+1, len ); break;
        case OSDP_HUB_GET_AUTH_1: return decode_get_auth_1( data, buffer+1, len ); break;
        case OSDP_HUB_GET_AUTH_3: return decode_get_auth_3( data, buffer+1, len ); break;

        default:
        {
            return 0;
        } break;
    }

} // osdp_hub_messages_decode()

//additional code

/// @file osdp_halo_alarm_base.h
/// @brief A C implementation of the proprietary Halo alarm packet.
///
/// @author neil

#pragma once

#include "osdp_header.h"

#ifdef _cplusplus
extern "C" {
#endif

/// The ID used to define a HALO HUB packet
#define OSDP_HUB    0x00

typedef enum
{
    OSDP_HUB_START = 0,
    OSDP_HUB_TCP_IND,
    OSDP_HUB_AUTH_0,
    OSDP_HUB_AUTH_1,
    OSDP_HUB_AUTH_2,
    OSDP_HUB_AUTH_3,
    OSDP_HUB_AUTH_4,
    OSDP_HUB_PING,
    OSDP_HUB_PONG,
    OSDP_HUB_GET_AUTH_1,
    OSDP_HUB_GET_AUTH_3,
} osdp_hub_e;

struct _osdp_hub_messages_t
{
    osdp_hub_e     hub_msg;
    bool           enable;
    uint8_t        max_tcp;
    uint8_t        ip_addr[16];
    bool           ipv4;
    uint32_t       port;
    bool           success;
    uint8_t        username[17];
    uint8_t        publickey[321];
    uint8_t        salt[65];
    uint8_t        cryptogram[65];
    osdp_header_t* header;
};
typedef struct _osdp_hub_messages_t osdp_hub_messages_t;

/// @brief Translate the data structure to a packet for transmission
/// @param buffer An input data buffer used to store the packet
/// @param len The length of the output packet
void osdp_hub_messages_encode( osdp_hub_messages_t* data, uint8_t* buffer, int32_t* len );

/// @brief Translate a received packet into a data structure
/// @param data A struct containing the decoded output parameters
/// @param buffer An input data buffer used to store the packet
/// @param len The length of the input packet
/// @return The number of decoded bytes
int32_t osdp_hub_messages_decode( osdp_hub_messages_t* data, uint8_t* buffer, int32_t len );

#ifdef _cplusplus
}
#endif

//
// end of file
//
</code>```

Anymore information required and i will surely add it. Thanks for your help!

答: The code you posted does not look like SIA OSDP.  (According to Sensurity's web site that is the OSDP they are referring to.)  Perhaps this is some other part of the mechanism?  The current SIA OSDP working group activity regarding OSDP over an IP network is around OSDP over TCP (using the existing "secure channel" mechanism) or OSDP over TLS.</p>

Body:
Language version: Microsoft Visual C++ 2013 Redistributable (x85) – 12.0.30501

Platform version: 4.0

Operating system: Microsoft Windows 8.1 6.3.9600 Build 9600

Any other relevant software:

Visual Studio 2013 Community with update 4

Halo Configuration Control Panel

Halo Hub

What I am trying to do

I am trying to communicate with a peripheral device that is using the OSDP protocol.

What is actually happening

I get the following from the output panel in visual studio.

Received valid packet of 326 bytes

Received authentication response from OSDP Hub

Session Key > E856417D8B0364313A4B8F0D89524273F0F70AB1DFF8E950FE96905FECAC9F2F

Received packet after 3 ms

Received valid packet of 4 bytes

Received authentication denial from OSDP Hub

Received packet after 0 ms

Performing a search on 0 devices

Rough Copy

'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Work\velox\admins-velox-project\proprietary\rtos\apps\chibios\utilities\osdp_client\Debug_msvc\osdp_client_mswud_vc11.exe'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ntdll.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded

'C:\Windows\SysWOW64\kernel32.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded

'C:\Windows\SysWOW64\KernelBase.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\user32.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\gdi32.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\comdlg32.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\winspool.drv'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\winmm.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\shell32.dll'. Cannot find or open the PDB file.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\WinSxS\x86_microsoft.windows.common-controls_6595b64144ccf1df_6.0.9600.18006_none_a9ec6aab013aafee\comctl32.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ole32.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\oleaut32.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\rpcrt4.dll'. Cannot find or open the PDB file.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\advapi32.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\wsock32.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ws2_32.dll'. Cannot find or open the PDB file.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcp120d.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcr120d.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcrt.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\shlwapi.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\winmmbase.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\combase.dll'. Cannot find or open the PDB file.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\sechost.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\sspicli.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\nsi.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\cfgmgr32.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\devobj.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\cryptbase.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\SHCore.dll'. Cannot find or open the PDB file.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\bcryptprimitives.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\imm32.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msctf.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\kernel.appcore.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\uxtheme.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\ProgramData\Internet Helper Anti-phishing\internetHelper_antiphishing.dll'. Module was built without symbols.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\version.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\dwmapi.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\IconCodecService.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\WindowsCodecs.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\WinSxS\x86_microsoft.windows.gdiplus_6595b64144ccf1df_1.1.9600.18696_none_dae05f525bc50fb1\GdiPlus.dll'. Cannot find or open the PDB file.
Password = 1234
Private key = 03ac674216f3e15c761ee1a5e255f067
Added 0 items
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\mswsock.dll'. Cannot find or open the PDB file.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\dnsapi.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\FWPUCLNT.DLL'. Cannot find or open the PDB file.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\rasadhlp.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\cryptsp.dll'. Symbols loaded.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\rsaenh.dll'. Cannot find or open the PDB file.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\bcrypt.dll'. Symbols loaded.
..\..\src\common\strvararg.cpp(658): assert "n <= parser.nargs" failed in `anonymous-namespace'::DoGetArgumentType(): more arguments than format string specifiers? [in thread cb4]
First-chance exception at 0x76165608 (KernelBase.dll) in osdp_client_mswud_vc11.exe: 0x00001976.
'osdp_client_mswud_vc11.exe' (Win32): Loaded 'C:\Windows\SysWOW64\dbghelp.dll'. Symbols loaded.
DBGHELP: Symbol Search Path: .
DBGHELP: .\wkernelbase.pdb - file not found
DBGHELP: .\dll\wkernelbase.pdb - file not found
DBGHELP: .\symbols\dll\wkernelbase.pdb - file not found
DBGHELP: wkernelbase.pdb - file not found
DBGHELP: KERNELBASE - export symbols
DBGHELP: .\osdp_client_mswud_vc11.pdb - file not found
DBGHELP: .\exe\osdp_client_mswud_vc11.pdb - file not found
DBGHELP: .\symbols\exe\osdp_client_mswud_vc11.pdb - file not found
Received valid packet of 326 bytes
Received authentication response from OSDP Hub
Session Key > 63B2D0C583090EFD994B5AFE12A417A07F406CEE1F64DCB1613703B45428E32E
Received packet after 3 ms
Received valid packet of 4 bytes
Received authentication denial from OSDP Hub
Received packet after 2 ms
DBGHELP: osdp_client_mswud_vc11 - private symbols & lines
        C:\Work\velox\admins-velox-project\proprietary\rtos\apps\chibios\utilities\osdp_client\Debug_msvc\osdp_client_mswud_vc11.pdb
DBGHELP: .\msvcr120d.i386.pdb - file not found
DBGHELP: .\dll\msvcr120d.i386.pdb - file not found
DBGHELP: .\symbols\dll\msvcr120d.i386.pdb - file not found
DBGHELP: msvcr120d.i386.pdb - file not found
DBGHELP: MSVCR120D - export symbols
DBGHELP: .\wntdll.pdb - file not found
DBGHELP: .\dll\wntdll.pdb - file not found
DBGHELP: .\symbols\dll\wntdll.pdb - file not found
DBGHELP: wntdll.pdb - file not found
DBGHELP: ntdll - export symbols
DBGHELP: .\wkernel32.pdb - file not found
DBGHELP: .\DLL\wkernel32.pdb - file not found
DBGHELP: .\symbols\DLL\wkernel32.pdb - file not found
DBGHELP: wkernel32.pdb - file not found
DBGHELP: KERNEL32 - export symbols

Here is the actual code;

case OSDP_HUB:
{
    bool ipv4;
    uint8_t ip_addr[16];

    osdp_hub_messages* hub = (osdp_hub_messages*)m_packets.get_data( OSDP_HUB );

    // goes from here to decode method ondown
    hub->decode( (uint8_t*)buffer, m_packets.get_header()->m_data.length );

    if ( hub->get_msg_type() == OSDP_HUB_TCP_IND )
    {
        hub->get_ip_addr( &ipv4, ip_addr );

        if ( hub->get_enable() )
        {
                        // Device has connected...
            wxLogDebug( wxT("Device connected on IP address %d.%d.%d.%d : %u"),
                ip_addr[0], ip_addr[1], ip_addr[2], ip_addr[3], hub->get_tcp_port() );

            m_tcp_device_connected = true;

                        // Assign an address
                        /// @todo Create an address generation function
            std::vector<uint8_t> ip_addr_vec;
            ip_addr_vec.resize( ipv4? 4 : 16 );
            memcpy( &ip_addr_vec[0], ip_addr, ipv4? 4 : 16 );
            m_tcp_map[0] = ip_addr_vec;

            MyCustomEvent customEvent( MyCustomCommandEvent, ID_EVENT_TCP_ADD );
            customEvent.SetText( _T( "SocketThread::Entry() ID_EVENT_TCP_ADD" ) );
            wxPostEvent( m_parent, customEvent );
        }
        else
        {
                        // Device has disconnected...
            wxLogDebug( wxT("Device disconnected on IP address %d.%d.%d.%d"),
                ip_addr[0], ip_addr[1], ip_addr[2], ip_addr[3] );

                        // Change the UI to display the nearest device on the list
            MyCustomEvent customEvent( MyCustomCommandEvent, ID_EVENT_TCP_REMOVE );
            customEvent.SetText( _T( "SocketThread::Entry() ID_EVENT_TCP_REMOVE" ) );
            wxPostEvent( m_parent, customEvent );
        }
    }
    else if ( hub->get_msg_type() == OSDP_HUB_AUTH_1 )
    {
        wxLogDebug( wxT("Received authentication response from OSDP Hub") );

        m_auth1_received = true;

        std::string salt = hub->get_salt();
        std::string key = hub->get_publickey();
        m_srp_auth->gen_client_session_key( salt, key );
        wxLogDebug( wxT("Session Key > %s"), m_srp_auth->get_session_key() );
        m_srp_auth->gen_client_cryptogram();
    }
    else if ( hub->get_msg_type() == OSDP_HUB_AUTH_3 ) // skips here
    {
        wxLogDebug( wxT("Received authentication accept from OSDP Hub") );

        m_auth3_received = true;
    }
    else if ( hub->get_msg_type() == OSDP_HUB_AUTH_4 ) // enters in here
    {
        wxLogDebug( wxT("Received authentication denial from OSDP Hub") );

        m_auth4_received = true;
    }
    else if ( hub->get_msg_type() == OSDP_HUB_PONG )
    {
        wxLogDebug( wxT("Received PONG from OSDP Hub") );

        m_pong_received = true;

        int32_t length;
        hub->encode( (uint8_t*)msg, &length );
        m_clientSocket->Write( (char*)msg, length );
    }
} break;

//comes in here
int32_t osdp_hub_messages::decode( uint8_t* buffer, int32_t len )
{
    return osdp_hub_messages_decode( &m_osdp_hub_messages, buffer, len );

} // decode()

// then comes in here
int32_t osdp_hub_messages_decode( osdp_hub_messages_t* data, uint8_t* buffer, int32_t len )
{
    //goes from OSDP_HUB_AUTH_2 t0 OSDP_HUB_AUTH_4
    //never hits OSDP_HUB_START or OSDP_HUB_TCP_IND
    data->hub_msg = (osdp_hub_e)buffer[0];

    switch ( data->hub_msg )
    {
        case OSDP_HUB_START: return decode_start( data, buffer+1, len ); break;
        case OSDP_HUB_TCP_IND: return decode_tcp_ind( data, buffer+1, len ); break;
        case OSDP_HUB_AUTH_0: return decode_auth_0( data, buffer+1, len ); break;
        case OSDP_HUB_AUTH_1: return decode_auth_1( data, buffer+1, len ); break;
        case OSDP_HUB_AUTH_2: return decode_auth_2( data, buffer+1, len ); break;
        case OSDP_HUB_AUTH_3: return decode_auth_2( data, buffer+1, len ); break;
        case OSDP_HUB_AUTH_4: return decode_auth_4( data, buffer+1, len ); break;
        case OSDP_HUB_PING: return decode_ping( data, buffer+1, len ); break;
        case OSDP_HUB_PONG: return decode_pong( data, buffer+1, len ); break;
        case OSDP_HUB_GET_AUTH_1: return decode_get_auth_1( data, buffer+1, len ); break;
        case OSDP_HUB_GET_AUTH_3: return decode_get_auth_3( data, buffer+1, len ); break;

        default:
        {
            return 0;
        } break;
    }

} // osdp_hub_messages_decode()

//additional code

/// @file osdp_halo_alarm_base.h
/// @brief A C implementation of the proprietary Halo alarm packet.
///
/// @author neil

#pragma once

#include "osdp_header.h"

#ifdef _cplusplus
extern "C" {
#endif

/// The ID used to define a HALO HUB packet
#define OSDP_HUB    0x00

typedef enum
{
    OSDP_HUB_START = 0,
    OSDP_HUB_TCP_IND,
    OSDP_HUB_AUTH_0,
    OSDP_HUB_AUTH_1,
    OSDP_HUB_AUTH_2,
    OSDP_HUB_AUTH_3,
    OSDP_HUB_AUTH_4,
    OSDP_HUB_PING,
    OSDP_HUB_PONG,
    OSDP_HUB_GET_AUTH_1,
    OSDP_HUB_GET_AUTH_3,
} osdp_hub_e;

struct _osdp_hub_messages_t
{
    osdp_hub_e     hub_msg;
    bool           enable;
    uint8_t        max_tcp;
    uint8_t        ip_addr[16];
    bool           ipv4;
    uint32_t       port;
    bool           success;
    uint8_t        username[17];
    uint8_t        publickey[321];
    uint8_t        salt[65];
    uint8_t        cryptogram[65];
    osdp_header_t* header;
};
typedef struct _osdp_hub_messages_t osdp_hub_messages_t;

/// @brief Translate the data structure to a packet for transmission
/// @param buffer An input data buffer used to store the packet
/// @param len The length of the output packet
void osdp_hub_messages_encode( osdp_hub_messages_t* data, uint8_t* buffer, int32_t* len );

/// @brief Translate a received packet into a data structure
/// @param data A struct containing the decoded output parameters
/// @param buffer An input data buffer used to store the packet
/// @param len The length of the input packet
/// @return The number of decoded bytes
int32_t osdp_hub_messages_decode( osdp_hub_messages_t* data, uint8_t* buffer, int32_t len );

#ifdef _cplusplus
}
#endif

//
// end of file
//

Anymore information required and i will surely add it. Thanks for your help!


问:
Custom Bar Button Item Image Frame Too Wide
I am trying to add a custom icon as the image of a bar button item. I correctly added the image assets in the 1x, 2x, 3x sizes, but the frame is too wide for no apparent reason. The image itself is a square and does not have such a wide frame. Click the link below to see the issue. Is there a way to fix this?

Extra wide frame image

答:
These are the Human Interface Guidelines that the documentation recommends for custom icons.

You just need to resize the image as per standard.

1X: 25 x 25

2X: 50 x 50

3X: 75 x 75


问:
How to exclude a DataRow from it's collection without Deleting it from the database?
Is there a way to remove a DataRow from it's DataRowCollection without deleting it from the database?

I am writing a program that monitors a web site.  It uses a DataTable from a DataAdapter created with Select * From MonitorSamples Where 1=0 to get a DataRowCollection with no actual rows in it.  The table is quite large and the monitor doesn't need the old samples, so for the sake of simplicity and efficiency, I am only getting/keeping the rows that it is working on.  (Also, not getting rid of these DataRows is technically a memory leak, since they will accumulate regularly over time until the program is restarted or it runs out of memory.)

As it runs periodically, it gathers data from the web site and creates new records (Datatable.NewRow()) which it then adds it to the DataTable's DatarowCollection (DataTable.Add()), which will be Inserted into the database when Dataset.Update is called.  In later periods, these same DataRows will also be modified and Updated back to the database.

Still later, the monitor knows that there will be no more updates for specific records, and so I would like to remove them from the DataRowCollection, but, not from the database.  I don't want to Delete them, I just don't want them in the dataset any longer for efficiency sake.  If I do not remove them the DataRowCollection will become filled with thousands of these unnecessary completed rows, far outnumbering the still updating active rows.

Obviously the .Delete() method Deletes it from the database after .AcceptChanges() or .Update().  Unfortunately, despite numerous claims on the Internet to the contrary, the .Remove() method does so also only it does it immediately.  From the MS Doc:

Calling Remove is the same as calling Delete and then calling AcceptChanges.

Also, I do not want to just refill the DataSet because it would be very complex for various reasons, including those not yet completed rows that the Monitor is still updating periodically.

Ok, so on a whim, since so many internet posts claimed that DataRowsCollection.Remove(DataRow) worked, I tried it.  And it worked.(!!)

So either the doc is wrong, or I am misunderstanding something here.  I will accept the first answer that can tell me what the real story is here.

答:
The database doesn't get updated until DataAdapter.Update is called. I think doing a Delete on a row, then immediately calling AcceptChanges on that row, will remove all traces of the row from the DataSet's diffgram, so that if/when DataAdapter.Update is called later, nothing will be done to that row in the database.

To help in understanding, you could try calling:

```<code>YourDataSet.WriteXml("c:\\somefile.xml", XmlWriteMode.DiffGram)
</code>```

after your Remove call.
Then have a look at the resulting file. There should not be a <diffgr:before> entry for the Removed row.

For background info on diffgrams:
https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/dataset-datatable-dataview/diffgrams

From that link:

```<code>Note that Deleted rows will have an Original row version in the <diffgr:before> block, but there will be no annotated element in the < DataInstance > block.
</code>```

Body:
The database doesn't get updated until DataAdapter.Update is called. I think doing a Delete on a row, then immediately calling AcceptChanges on that row, will remove all traces of the row from the DataSet's diffgram, so that if/when DataAdapter.Update is called later, nothing will be done to that row in the database.

To help in understanding, you could try calling:

YourDataSet.WriteXml("c:\\somefile.xml", XmlWriteMode.DiffGram)

after your Remove call.
Then have a look at the resulting file. There should not be a <diffgr:before> entry for the Removed row.

For background info on diffgrams:
https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/dataset-datatable-dataview/diffgrams

From that link:

Note that Deleted rows will have an Original row version in the <diffgr:before> block, but there will be no annotated element in the < DataInstance > block.


问:
How database changes send to web client with node js?
I am developing web application with admin dashboard, I need to show notifications, new user register etc. on dashboard and I don't want to use a third party notification library like pusher, firebase etc. I am new to this, how normally this work?

I tried query every x seconds to see any new changes on server by http ajax request, but I realized this not the proper way and it may overload server handling. I am thinking to use websocket, then when server get new post request from other client, send message to dashboard, but I am not sure how to use websocket properly (when data changes how to send throuh socket)..

If websocket is not the ideal solution, how normally work this? Any tutorial or example on how to interact with ws object on server side would be much appreciated (if websocket is the ideal solution)

答:
After doing some research, I came up with a solution to my question. I hope it may helpful to others or I can improve my solution by getting some feedback from others or a better approach on my solution.

Just need two files to get this working

Client side (index.html)

  open console to see what is happening.

```
</div>
</div>
</p>

<p>Server side (server.js)
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const WebSocket = require('ws');
const express = require('express')
var expressWs = require('express-ws');
var expressWs = expressWs(express());

var app = expressWs.app;

// express routes
app.get('/', function(req, res) {
  res.sendFile(__dirname + '/index.html');
})

app.get('/customers', function(req, res) {
  res.send('Showing list of customers');

  NotifyDashboard('someone viewed list of customers..');
})

// websocket route
app.ws('/notifications', (ws, req) => {
  ws.on('close', () => {
    console.log('WebSocket was closed')
  })
})

// Let all dashboard clients know.
function NotifyDashboard(data) {
  expressWs.getWss('/notifications').clients.forEach(function each(client) {
    if (client.readyState === WebSocket.OPEN) {
      client.send(data);
    }
  });
};

app.listen(3000, function() {
  console.log(`http/ws server listening on 3000`);
});</code>```

Body:
After doing some research, I came up with a solution to my question. I hope it may helpful to others or I can improve my solution by getting some feedback from others or a better approach on my solution.

Just need two files to get this working

Client side (index.html)

<p>
  open console to see what is happening.
</p>
<script>
  const socketProtocol = (window.location.protocol === 'https:' ? 'wss:' : 'ws:')
  const echoSocketUrl = socketProtocol + '//' + window.location.hostname + ':3000/notifications/'
  const socket = new WebSocket(echoSocketUrl);

  console.log('Waiting for new notifications from server');

  socket.onmessage = e => {
    console.log('Message from server:', event.data)
  }
</script>

Server side (server.js)

const WebSocket = require('ws');
const express = require('express')
var expressWs = require('express-ws');
var expressWs = expressWs(express());

var app = expressWs.app;

// express routes
app.get('/', function(req, res) {
  res.sendFile(__dirname + '/index.html');
})

app.get('/customers', function(req, res) {
  res.send('Showing list of customers');

  NotifyDashboard('someone viewed list of customers..');
})

// websocket route
app.ws('/notifications', (ws, req) => {
  ws.on('close', () => {
    console.log('WebSocket was closed')
  })
})

// Let all dashboard clients know.
function NotifyDashboard(data) {
  expressWs.getWss('/notifications').clients.forEach(function each(client) {
    if (client.readyState === WebSocket.OPEN) {
      client.send(data);
    }
  });
};

app.listen(3000, function() {
  console.log(`http/ws server listening on 3000`);
});


问:
Django front end user restrictions
I have a question which might be repeated multiple times but I'm unable to understand any of them at all.

I have a view, in the view the user selects a value from a choice drop down and enters a integer amount to process.

If the user enters lets say 5 in the Quantity and he has 2 leaves remaining in the selected choice, I want him to be notified after submitting the form or on the very page that you don't have this many leaves to apply for.

view.py

def request_leave(request, emp_id):  # Requesting leave
    employee = Employee.objects.get(employee_name=emp_id)
    if employee.allowed == True:
        form = Leave_Form(request.POST, employee=employee)
        if form.is_valid():
            abc = form.save(commit=False)
            abc.employee_leaves = request.user.employee
            abc.save()
        form = Leave_Form
        context = {'employee': employee, 'form': form}
        # context = {'form': form}
        return render(request, 'projectfiles/reqleave.html', context)
    else:
        return render(request, "projectfiles/banned.html")
```

<p><strong>models.py</strong></p>

<pre class="lang-py prettyprint-override"><code>
class Employee(models.Model):

    allowed = models.BooleanField(default=True)
    employee_name = models.OneToOneField(User, on_delete = models.CASCADE)
    employee_designation = models.CharField(max_length = 5)
    employee_department = models.CharField(max_length = 5)
    Annual_leave = models.PositiveSmallIntegerField(default=5)
    Sick_leave = models.PositiveSmallIntegerField(default=5)
    Casual_leave = models.PositiveSmallIntegerField(default=5)
    Half_pay = models.PositiveSmallIntegerField(default=5)
    Emergency_leave = models.PositiveSmallIntegerField(default=5)

</code>```

forms.py

to_date = forms.DateField(
        widget=forms.DateInput(format=('%m/%d/%y'),
                               attrs={'class': 'form-control',
                                      'placeholder': ' Month/Date/Year'}))

    from_date = forms.DateField(
        widget=forms.DateInput(format=('%m/%d/%y'),
                               attrs={'class': 'form-control',
                               'placeholder':' Month/Date/Year'}))

    def __init__(self, *args, **kwargs):
        employee = kwargs.pop('employee', None)
        if employee:
            self.employee = employee
        super(Leave_Form, self).__init__(*args, **kwargs)

    def clean(self):
        cleaned_data = super(Leave_Form, self).clean()
        leave_qty = cleaned_data.get('leave_qty')
        leave_type = cleaned_data.get('leave_Type')
        #If form still submits, then please put a debugger here
        if leave_type == "Annual_Leave":  # Checking Leave Type and comparing leave_qty against that type of leave
            if self.employee.Annual_Leave:
                forms.ValidationError("You don't have enough Annual Leave")
        if leave_type == "Sick_leave":
            if self.employee.Sick_leave:
                forms.ValidationError("You don't have enough Sick Leave")
        # similarly add other else if logic for other types of leaves
        return leave_qty

    class Meta:
        model = Leave
        fields = ['leave_Type', 'description',
                  'from_date', 'to_date', 'leave_qty']
        exclude = ['employee_leaves', 'submit_date', 'leave_status']
        leave_type_choice = (

            ("Annual_leave", "Annual leave"),
            ("Sick_leave", "Sick leave"),
            ("Casual_leave", "Casual leave"),
            ("Emergency_leave", "Emergency leave"),
            ("Half_pay","Half Pay")
    )

        widgets = {

            'leave_Type': forms.Select(choices = leave_type_choice, attrs={'class': 'form-control'}),
            'description': forms.Textarea(
                attrs={'class': 'form-control','placeholder': 'Enter description here', 'rows': 3, 'cols': 21})}

```

<p><strong>urls.py</strong></p>

<pre class="lang-py prettyprint-override"><code>url(r'^(?i)request/(?P<emp_id>\d+)$', views.request_leave,
        name='Leave-Page'),  # leave request

</code>```

req.html

{% include 'projectfiles/base.html' %}
<title>Request Leave</title>

{% block asd %}

<form method="POST" style="width:190px">

    {% csrf_token %}
    {{form.as_p}}

<button class="btn btn-success my-2 my-sm-0" type="submit">Apply</button>

</form>

{% endblock %}
```

<p><strong>error</strong></p>

```
Traceback:

File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Python27\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

File "C:\Users\Bitswits 3\Desktop\Intern Work\LMS\LMS\projectfiles\views.py" in request_leave
  47.         if form.is_valid():

File "C:\Python27\lib\site-packages\django\forms\forms.py" in is_valid
  183.         return self.is_bound and not self.errors

File "C:\Python27\lib\site-packages\django\forms\forms.py" in errors
  175.             self.full_clean()

File "C:\Python27\lib\site-packages\django\forms\forms.py" in full_clean
  386.         self._post_clean()

File "C:\Python27\lib\site-packages\django\forms\models.py" in _post_clean
  394.         exclude = self._get_validation_exclusions()

File "C:\Python27\lib\site-packages\django\forms\models.py" in _get_validation_exclusions
  354.                 field_value = self.cleaned_data.get(field)

Exception Type: AttributeError at /request/2
Exception Value: 'int' object has no attribute 'get'
```

<p><strong>log</strong></p>

```[31/May/2019 12:51:07] "POST /request/2 HTTP/1.1" 200 7906
========Annual_leave
________45
[31/May/2019 12:53:32] "POST /request/2 HTTP/1.1" 200 7906

=======================

========Sick_leave
________52
[31/May/2019 12:54:34] "POST /request/2 HTTP/1.1" 200 7906

```

<p><img src="https://i.stack.imgur.com/yfGOk.png" alt="Annual Leave"></p>

<p><strong>update</strong></p>

```to_date = forms.DateField(
        widget=forms.DateInput(format=('%m/%d/%y'),
                               attrs={'class': 'form-control',
                                      'placeholder': ' Month/Date/Year'}))

    from_date = forms.DateField(
        widget=forms.DateInput(format=('%m/%d/%y'),
                               attrs={'class': 'form-control',
                               'placeholder':' Month/Date/Year'}))

    def __init__(self, *args, **kwargs):
        employee = kwargs.pop('employee', None)
        if employee:
            self.employee = employee
        super(Leave_Form, self).__init__(*args, **kwargs)

    def clean(self):
        cleaned_data = super(Leave_Form, self).clean()
        leave_qty = cleaned_data.get('leave_qty')
        leave_type = cleaned_data.get('leave_Type')
        if leave_type < leave_qty:

            print "======== " + str(leave_type)
            print "________ " + str(leave_qty)

            raise forms.ValidationError("You don't have enough Annual Leave")

        return cleaned_data
```

I expect an error either after the submission of the form or on the very page, My seniors have suggested to use JS but I;m not familiar with JS.

答:
Maybe you can use clean method in ModelForm. You can do it like this:

For accessing Employee's current leave count, we need pass Employee object to the Form. So we have to override Form's __init__ method as well:

```<code>class Leave_Form(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        employee = kwargs.pop('employee', None)
        if employee:
            self.employee = employee
        super(Leave_Form, self).__init__(*args, **kwargs)
    ...

    def clean(self):
        cleaned_data = super(Leave_Form, self).clean()
        leave_qty = cleaned_data.get('leave_qty')
        leave_type = cleaned_data.get('leave_Type')
        #If form still submits, then please put a debugger here
        if leave_type == "Annual_leave":  # Checking Leave Type and comparing leave_qty against that type of leave
            if self.employee.Annual_leave < leave_qty:
                 raise forms.ValidationError("You don't have enough Annual Leave")
        if leave_type == "Sick_leave":
            if self.employee.Sick_leave < leave_qty:
                 raise forms.ValidationError("You don't have enough Sick Leave")
        # similarly add other else if logic for other types of leaves
        return cleaned_data
</code>```

Now, we can use this form in request_leave view like this( we will pass employee object as keyword argument in Form):

```<code>@login_required(login_url='LoginPage')
def request_leave(request, emp_id):  # Requesting leave
    employee = Employee.objects.get(employee_name=emp_id)
    if employee.allowed == True:
        form = Leave_Form(request.POST,<b>employee=employee</b>)
        # rest of the code</code>```

Finally, update the template as well to show errors(documentation):

```<code>{% if form.non_field_errors %}

    {% for err in form.non_field_errors %}
      <p>{{ err }}</p>
    {% endfor %}

{% endif %}
</code>```

Title: Django front end user restrictions

Body:
I have a question which might be repeated multiple times but I'm unable to understand any of them at all.

I have a view, in the view the user selects a value from a choice drop down and enters a integer amount to process.

If the user enters lets say 5 in the Quantity and he has 2 leaves remaining in the selected choice, I want him to be notified after submitting the form or on the very page that you don't have this many leaves to apply for.

view.py

def request_leave(request, emp_id):  # Requesting leave
    employee = Employee.objects.get(employee_name=emp_id)
    if employee.allowed == True:
        form = Leave_Form(request.POST, employee=employee)
        if form.is_valid():
            abc = form.save(commit=False)
            abc.employee_leaves = request.user.employee
            abc.save()
        form = Leave_Form
        context = {'employee': employee, 'form': form}
        # context = {'form': form}
        return render(request, 'projectfiles/reqleave.html', context)
    else:
        return render(request, "projectfiles/banned.html")

models.py

class Employee(models.Model):

    allowed = models.BooleanField(default=True)
    employee_name = models.OneToOneField(User, on_delete = models.CASCADE)
    employee_designation = models.CharField(max_length = 5)
    employee_department = models.CharField(max_length = 5)
    Annual_leave = models.PositiveSmallIntegerField(default=5)
    Sick_leave = models.PositiveSmallIntegerField(default=5)
    Casual_leave = models.PositiveSmallIntegerField(default=5)
    Half_pay = models.PositiveSmallIntegerField(default=5)
    Emergency_leave = models.PositiveSmallIntegerField(default=5)

forms.py

to_date = forms.DateField(
        widget=forms.DateInput(format=('%m/%d/%y'),
                               attrs={'class': 'form-control',
                                      'placeholder': ' Month/Date/Year'}))

    from_date = forms.DateField(
        widget=forms.DateInput(format=('%m/%d/%y'),
                               attrs={'class': 'form-control',
                               'placeholder':' Month/Date/Year'}))

    def __init__(self, *args, **kwargs):
        employee = kwargs.pop('employee', None)
        if employee:
            self.employee = employee
        super(Leave_Form, self).__init__(*args, **kwargs)

    def clean(self):
        cleaned_data = super(Leave_Form, self).clean()
        leave_qty = cleaned_data.get('leave_qty')
        leave_type = cleaned_data.get('leave_Type')
        #If form still submits, then please put a debugger here
        if leave_type == "Annual_Leave":  # Checking Leave Type and comparing leave_qty against that type of leave
            if self.employee.Annual_Leave:
                forms.ValidationError("You don't have enough Annual Leave")
        if leave_type == "Sick_leave":
            if self.employee.Sick_leave:
                forms.ValidationError("You don't have enough Sick Leave")
        # similarly add other else if logic for other types of leaves
        return leave_qty

    class Meta:
        model = Leave
        fields = ['leave_Type', 'description',
                  'from_date', 'to_date', 'leave_qty']
        exclude = ['employee_leaves', 'submit_date', 'leave_status']
        leave_type_choice = (

            ("Annual_leave", "Annual leave"),
            ("Sick_leave", "Sick leave"),
            ("Casual_leave", "Casual leave"),
            ("Emergency_leave", "Emergency leave"),
            ("Half_pay","Half Pay")
    )

        widgets = {

            'leave_Type': forms.Select(choices = leave_type_choice, attrs={'class': 'form-control'}),
            'description': forms.Textarea(
                attrs={'class': 'form-control','placeholder': 'Enter description here', 'rows': 3, 'cols': 21})}

urls.py

url(r'^(?i)request/(?P<emp_id>\d+)$', views.request_leave,
        name='Leave-Page'),  # leave request

req.html

{% include 'projectfiles/base.html' %}
<title>Request Leave</title>

{% block asd %}

<form method="POST" style="width:190px">

    {% csrf_token %}
    {{form.as_p}}

<button class="btn btn-success my-2 my-sm-0" type="submit">Apply</button>

</form>

{% endblock %}

error

Traceback:

File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Python27\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

File "C:\Users\Bitswits 3\Desktop\Intern Work\LMS\LMS\projectfiles\views.py" in request_leave
  47.         if form.is_valid():

File "C:\Python27\lib\site-packages\django\forms\forms.py" in is_valid
  183.         return self.is_bound and not self.errors

File "C:\Python27\lib\site-packages\django\forms\forms.py" in errors
  175.             self.full_clean()

File "C:\Python27\lib\site-packages\django\forms\forms.py" in full_clean
  386.         self._post_clean()

File "C:\Python27\lib\site-packages\django\forms\models.py" in _post_clean
  394.         exclude = self._get_validation_exclusions()

File "C:\Python27\lib\site-packages\django\forms\models.py" in _get_validation_exclusions
  354.                 field_value = self.cleaned_data.get(field)

Exception Type: AttributeError at /request/2
Exception Value: 'int' object has no attribute 'get'

log

[31/May/2019 12:51:07] "POST /request/2 HTTP/1.1" 200 7906
========Annual_leave
________45
[31/May/2019 12:53:32] "POST /request/2 HTTP/1.1" 200 7906

=======================

========Sick_leave
________52
[31/May/2019 12:54:34] "POST /request/2 HTTP/1.1" 200 7906

update

to_date = forms.DateField(
        widget=forms.DateInput(format=('%m/%d/%y'),
                               attrs={'class': 'form-control',
                                      'placeholder': ' Month/Date/Year'}))

    from_date = forms.DateField(
        widget=forms.DateInput(format=('%m/%d/%y'),
                               attrs={'class': 'form-control',
                               'placeholder':' Month/Date/Year'}))

    def __init__(self, *args, **kwargs):
        employee = kwargs.pop('employee', None)
        if employee:
            self.employee = employee
        super(Leave_Form, self).__init__(*args, **kwargs)

    def clean(self):
        cleaned_data = super(Leave_Form, self).clean()
        leave_qty = cleaned_data.get('leave_qty')
        leave_type = cleaned_data.get('leave_Type')
        if leave_type < leave_qty:

            print "======== " + str(leave_type)
            print "________ " + str(leave_qty)

            raise forms.ValidationError("You don't have enough Annual Leave")

        return cleaned_data

I expect an error either after the submission of the form or on the very page, My seniors have suggested to use JS but I;m not familiar with JS.

Body:
Maybe you can use clean method in ModelForm. You can do it like this:

For accessing Employee's current leave count, we need pass Employee object to the Form. So we have to override Form's __init__ method as well:

class Leave_Form(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        employee = kwargs.pop('employee', None)
        if employee:
            self.employee = employee
        super(Leave_Form, self).__init__(*args, **kwargs)
    ...

    def clean(self):
        cleaned_data = super(Leave_Form, self).clean()
        leave_qty = cleaned_data.get('leave_qty')
        leave_type = cleaned_data.get('leave_Type')
        #If form still submits, then please put a debugger here
        if leave_type == "Annual_leave":  # Checking Leave Type and comparing leave_qty against that type of leave
            if self.employee.Annual_leave < leave_qty:
                 raise forms.ValidationError("You don't have enough Annual Leave")
        if leave_type == "Sick_leave":
            if self.employee.Sick_leave < leave_qty:
                 raise forms.ValidationError("You don't have enough Sick Leave")
        # similarly add other else if logic for other types of leaves
        return cleaned_data

Now, we can use this form in request_leave view like this( we will pass employee object as keyword argument in Form):

@login_required(login_url='LoginPage')
def request_leave(request, emp_id):  # Requesting leave
    employee = Employee.objects.get(employee_name=emp_id)
    if employee.allowed == True:
        form = Leave_Form(request.POST,employee=employee)
        # rest of the code

Finally, update the template as well to show errors(documentation):

{% if form.non_field_errors %}

    {% for err in form.non_field_errors %}
      <p>{{ err }}</p>
    {% endfor %}

{% endif %}


问:
How do i set the state from one API call and use the data for URL in next API call?
I need the data from API call 1 to add to the URL of API call 2. The data from API 2 will go into the URL for API 3. I am setting the state on each Axios request and it is not working. Returning undefined</p>

```<code>componentDidMount() {
  // Get the IP adress of user
  axios
    .get('https://api.ipify.org?format=json')
    .then(res => {
      this.setState({
        ip: res.data.ip
      });
      console.log(`IP : ${this.state.ip}`);
    })
    .catch(err => console.log(err));

  // GET the coordinates of a location based on IP adress
  axios
    .get(
      'https://geo.ipify.org/api/v1?apiKey=YOUR_API_KEY&ipAddress=24.8.227.87'
    )
    .then(res => {
      this.setState({
        latitude: res.data.location.lat,
        longitude: res.data.location.lng
      });
      console.log(
        `Latitude: ${this.state.latitude}. Longitude: ${this.state.longitude}`
      );
    })
    .catch(err => console.log(err));

  // Make the API call on page load
  axios({
      method: 'get',
      url: `https://developers.zomato.com/api/v2.1/geocode?lat=39.6924553&lon=-105.0256318`,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        Accept: 'application/json',
        'user-key': 'USER_KEY'
      }
    })
    .then(res => {
      const restaurantsNearMe = res.data.nearby_restaurants;

      this.setState({
        restaurants: restaurantsNearMe
      });

      // Pick out a random retaurant from what the API returns
      var randomRestaurant =
        restaurantsNearMe[
          Math.floor(Math.random() * restaurantsNearMe.length)
        ];

      // Select only the data that you want
      var finalResult = {
        name: randomRestaurant.restaurant.name,
        id: randomRestaurant.restaurant.id,
        rating: randomRestaurant.restaurant.user_rating.aggregate_rating,
        ratingColor: randomRestaurant.restaurant.user_rating.rating_color,
        address: randomRestaurant.restaurant.location.address,
        delivery: randomRestaurant.restaurant.is_delivering_now,
        typeOfFood: randomRestaurant.restaurant.cuisines
      };

      this.setState({
        restaurant: finalResult
      });
      console.log(this.state.restaurant);
    })
    .catch(err => console.log(err));
}
</code>```

答:
one thing to keep in mind, this.setState is not synchronous. React batches multiple set state calls to improve render performance. That's why you might be seeing undefined in the console.log.
setState method takes a callback as second parameter.

this.setState(newState, callbalck)

so try to console log in the callback and give it a try.

Body:
I need the data from API call 1 to add to the URL of API call 2. The data from API 2 will go into the URL for API 3. I am setting the state on each Axios request and it is not working. Returning undefined

componentDidMount() {
  // Get the IP adress of user
  axios
    .get('https://api.ipify.org?format=json')
    .then(res => {
      this.setState({
        ip: res.data.ip
      });
      console.log(`IP : ${this.state.ip}`);
    })
    .catch(err => console.log(err));

  // GET the coordinates of a location based on IP adress
  axios
    .get(
      'https://geo.ipify.org/api/v1?apiKey=YOUR_API_KEY&ipAddress=24.8.227.87'
    )
    .then(res => {
      this.setState({
        latitude: res.data.location.lat,
        longitude: res.data.location.lng
      });
      console.log(
        `Latitude: ${this.state.latitude}. Longitude: ${this.state.longitude}`
      );
    })
    .catch(err => console.log(err));

  // Make the API call on page load
  axios({
      method: 'get',
      url: `https://developers.zomato.com/api/v2.1/geocode?lat=39.6924553&lon=-105.0256318`,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        Accept: 'application/json',
        'user-key': 'USER_KEY'
      }
    })
    .then(res => {
      const restaurantsNearMe = res.data.nearby_restaurants;

      this.setState({
        restaurants: restaurantsNearMe
      });

      // Pick out a random retaurant from what the API returns
      var randomRestaurant =
        restaurantsNearMe[
          Math.floor(Math.random() * restaurantsNearMe.length)
        ];

      // Select only the data that you want
      var finalResult = {
        name: randomRestaurant.restaurant.name,
        id: randomRestaurant.restaurant.id,
        rating: randomRestaurant.restaurant.user_rating.aggregate_rating,
        ratingColor: randomRestaurant.restaurant.user_rating.rating_color,
        address: randomRestaurant.restaurant.location.address,
        delivery: randomRestaurant.restaurant.is_delivering_now,
        typeOfFood: randomRestaurant.restaurant.cuisines
      };

      this.setState({
        restaurant: finalResult
      });
      console.log(this.state.restaurant);
    })
    .catch(err => console.log(err));
}


问:
MySQL SELECT rows with string but not other strings doesn't work as expected
I have text data in a column in a table in MySQL. I am trying to select only those rows that have:

```<code>SELECT * FROM `leganalyse_unitsub` WHERE `content` LIKE '%Act%' AND `content` NOT LIKE '%this Act%' AND `content` NOT LIKE '%Act (%' AND `content` NOT LIKE '%[Act%'
</code>```

I am trying to get only those rows that have the string "Act" in it, but these rows should also not have the strings:
"this Act", "Act (", "[Act".

However, after executing query, I get rows like:
"(11)  Where the Registrar discloses and makes available for public inspection the particulars of a public accountant’s residential address, the Registrar must give notice of that fact to the public accountant."
Which do not even have the word "Act" at all.

Why, and how do I modify the query to get what I want?

答:
Maybe you can create a nested SELECT:</p>

```<code>SELECT * FROM (SELECT * FROM `leganalyse_unitsub` WHERE `content` LIKE '%Act')
 WHERE `content` NOT LIKE '%this Act%' AND `content` NOT LIKE '%Act (%' AND `content` NOT LIKE '%[Act%'
</code>```

Body:
I have text data in a column in a table in MySQL. I am trying to select only those rows that have:

SELECT * FROM `leganalyse_unitsub` WHERE `content` LIKE '%Act%' AND `content` NOT LIKE '%this Act%' AND `content` NOT LIKE '%Act (%' AND `content` NOT LIKE '%[Act%'

I am trying to get only those rows that have the string "Act" in it, but these rows should also not have the strings:
"this Act", "Act (", "[Act".

However, after executing query, I get rows like:
"(11)  Where the Registrar discloses and makes available for public inspection the particulars of a public accountant’s residential address, the Registrar must give notice of that fact to the public accountant."
Which do not even have the word "Act" at all.

Why, and how do I modify the query to get what I want?

Body:
Maybe you can create a nested SELECT:

SELECT * FROM (SELECT * FROM `leganalyse_unitsub` WHERE `content` LIKE '%Act')
 WHERE `content` NOT LIKE '%this Act%' AND `content` NOT LIKE '%Act (%' AND `content` NOT LIKE '%[Act%'


问:
Prevent pages from rendering if the user is not logged in
I'm using Lazy loading to render pages in my application.

```<code>{ path: 'dashboard', loadChildren: './dashboard/dashboard.module#DashboardModule', canActivate: [AuthGuard] }
</code>```

Problem is if I type www.mydomain.com/dashboard in the URL, the browser actually renders the dashboard page even though the user is not logged in and the redirect to the login screen after a second or two.

How do I prevent the browser from rendering any page at all if the user is not logged in? Basically it should straightaway redirect to the login page.

AuthGuard Class

```<code>export class AuthGuard implements CanActivate {

  result: boolean = false;
  auth: any;
  outRes: any;

  constructor(private _authService: JwtService, private _router: Router) {

  }

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

    this.outRes = this._authService.isAuthenticated();

    if (this.outRes) {
      this.outRes.subscribe(o => o ? true : this._authService.redirectToLogin());

      return true;
    } else {

      this._authService.redirectToLogin();
      return false;
    }

  }

}
</code>```

Service Class

```<code>  public isAuthenticated() {

    if (!this.loggedIn)
      this.redirectToLogin();

    return this.httpClient.get<boolean>(`${this.settings.getApiSettings('uri')}/api/auth/IsTokenValid`, {
      params: { token: this.getToken }
    }).map( /// <<<=== use `map` here
      (response) => {

        if (response !== null) {

          var receivedToken = response["securityStamp"];
          var availableToken = localStorage.getItem('access_token');

           //Check if received a refreshed token. (tokens are refreshed every 15 minutes)
          if (receivedToken && receivedToken !== availableToken) {

            localStorage.removeItem('access_token');
            localStorage.setItem('access_token', response["securityStamp"]);

          }

        }

        let data = response;
        if (data == null)
          return false;
        else
          return true;

      }
    );

  }

  redirectToLogin() {

    localStorage.removeItem('access_token');
    window.location.href = "./login";

  }
</code>```

答:
Your main issue is this if (this.outRes) and this o => o ? true : this._authService.redirectToLogin() , you always get true because your function will always return a response and it will never be null;
you're basically checking if there is response but not what type of response (true/false);

```<code> canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

    let isAuth: any;
    this._authService.isAuthenticated()
       .subscribe(response => isAuth = response); //<== this can true or false based on service

    if (!isAuth) {
      this._authService.redirectToLogin();
    }
     return isAuth;
  }
</code>```

Body:
I'm using Lazy loading to render pages in my application.

{ path: 'dashboard', loadChildren: './dashboard/dashboard.module#DashboardModule', canActivate: [AuthGuard] }

Problem is if I type www.mydomain.com/dashboard in the URL, the browser actually renders the dashboard page even though the user is not logged in and the redirect to the login screen after a second or two.

How do I prevent the browser from rendering any page at all if the user is not logged in? Basically it should straightaway redirect to the login page.

AuthGuard Class

export class AuthGuard implements CanActivate {

  result: boolean = false;
  auth: any;
  outRes: any;

  constructor(private _authService: JwtService, private _router: Router) {

  }

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

    this.outRes = this._authService.isAuthenticated();

    if (this.outRes) {
      this.outRes.subscribe(o => o ? true : this._authService.redirectToLogin());

      return true;
    } else {

      this._authService.redirectToLogin();
      return false;
    }

  }

}

Service Class

  public isAuthenticated() {

    if (!this.loggedIn)
      this.redirectToLogin();

    return this.httpClient.get<boolean>(`${this.settings.getApiSettings('uri')}/api/auth/IsTokenValid`, {
      params: { token: this.getToken }
    }).map( /// <<<=== use `map` here
      (response) => {

        if (response !== null) {

          var receivedToken = response["securityStamp"];
          var availableToken = localStorage.getItem('access_token');

           //Check if received a refreshed token. (tokens are refreshed every 15 minutes)
          if (receivedToken && receivedToken !== availableToken) {

            localStorage.removeItem('access_token');
            localStorage.setItem('access_token', response["securityStamp"]);

          }

        }

        let data = response;
        if (data == null)
          return false;
        else
          return true;

      }
    );

  }

  redirectToLogin() {

    localStorage.removeItem('access_token');
    window.location.href = "./login";

  }

Body:
Your main issue is this if (this.outRes) and this o => o ? true : this._authService.redirectToLogin() , you always get true because your function will always return a response and it will never be null;
you're basically checking if there is response but not what type of response (true/false);

 canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

    let isAuth: any;
    this._authService.isAuthenticated()
       .subscribe(response => isAuth = response); //<== this can true or false based on service

    if (!isAuth) {
      this._authService.redirectToLogin();
    }
     return isAuth;
  }