问:
Convert datetime-local to UTC time in js/jquery
I have a form that a user can input a datetime

```<code><input class="form-control" name="aution_end_time" required type="datetime-local id="auction_end_time-input">
</code>```

Now what I would like to do is convert this "local datetime object" to UTC time and store that value in a hidden input of the form.

```<code><input type="hidden" class="form-control" name="auction_end_time_utc">
</code>```

How would I go about this?
To summarize:
user enters a datetime in the form, then once they do that the hidden input gets updated with the same datetime but in UTC. I am unsure of how to determine the users local time zone and how to convert to UTC. Thanks!

答:
I would recommend to use moment.js for that.

See my code snippet! I changed type="hidden" to type="text" and name to id for the second input for presentational purpose.

document.getElementById("auction_end_time-input").oninput = function() {
  var datetimeLocal = document.getElementById("auction_end_time-input").value;
  var datetimeUTC = moment.utc(datetimeLocal).format();
  document.getElementById("auction_end_time_utc").value = datetimeUTC;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- moment.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.3/moment-with-locales.min.js"></script>

<input class="form-control" name="aution_end_time" required type="datetime-local" id="auction_end_time-input">
<input type="text" class="form-control" id="auction_end_time_utc"></code>```

Body:
I have a form that a user can input a datetime

<input class="form-control" name="aution_end_time" required type="datetime-local id="auction_end_time-input">

Now what I would like to do is convert this "local datetime object" to UTC time and store that value in a hidden input of the form.

<input type="hidden" class="form-control" name="auction_end_time_utc">

How would I go about this?
To summarize:
user enters a datetime in the form, then once they do that the hidden input gets updated with the same datetime but in UTC. I am unsure of how to determine the users local time zone and how to convert to UTC. Thanks!

Body:
I would recommend to use moment.js for that.

See my code snippet! I changed type="hidden" to type="text" and name to id for the second input for presentational purpose.

document.getElementById("auction_end_time-input").oninput = function() {
  var datetimeLocal = document.getElementById("auction_end_time-input").value;
  var datetimeUTC = moment.utc(datetimeLocal).format();
  document.getElementById("auction_end_time_utc").value = datetimeUTC;
}

<!-- moment.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.3/moment-with-locales.min.js"></script>

<input class="form-control" name="aution_end_time" required type="datetime-local" id="auction_end_time-input">
<input type="text" class="form-control" id="auction_end_time_utc">


来源: stackexchange

问:
PYTHON: Simple Float conversion not working why?
Why this simple conversion does not work beats me Please help:

```<code>print(getx)

Date
2017-12-08   -4.484884
Name: CCI, dtype: float64

chkccisplt=getx
type(getx)
chksplt=str(getx)
type(chksplt)
print(chksplt)
Date
2017-12-08   -4.484884
Name: CCI, dtype: float64
chkdt,chkcci=chksplt.split("  ")
print(chkdt)
Date
2017-12-08
print(chkcci)
-4.484884
Name: CCI, dtype: float64
chkcci=chkcci.strip()
chkcciflt=float(chkcci)

**ValueError: could not convert string to float: '-4.484884\nName: CCI, dtype:
float64'**
</code>```

In the last line above the Value Error is thrown back.
A Thousand Thanks in advance for all your answers.

答:
Change this line

```<code>chkcci=chkcci.strip()
</code>```

to

```<code>chkcci=chkcci.split('\n')[0].strip()
</code>```

You need to remove the 'Name:' part to convert the data to float.

ContentLicense: CC BY-SA 3.0

Body:
Why this simple conversion does not work beats me Please help:

print(getx)

Date
2017-12-08   -4.484884
Name: CCI, dtype: float64

chkccisplt=getx
type(getx)
chksplt=str(getx)
type(chksplt)
print(chksplt)
Date
2017-12-08   -4.484884
Name: CCI, dtype: float64
chkdt,chkcci=chksplt.split("  ")
print(chkdt)
Date
2017-12-08
print(chkcci)
-4.484884
Name: CCI, dtype: float64
chkcci=chkcci.strip()
chkcciflt=float(chkcci)

**ValueError: could not convert string to float: '-4.484884\nName: CCI, dtype:
float64'**

In the last line above the Value Error is thrown back.
A Thousand Thanks in advance for all your answers.

Body:
Change this line

chkcci=chkcci.strip()

to

chkcci=chkcci.split('\n')[0].strip()

You need to remove the 'Name:' part to convert the data to float.


问:
Get the name of a decorated function?
here is my decorator:

```<code>def check_domain(func):

    def wrapper(domain_id, *args, **kwargs):
        domain = get_object_or_None(Domain, id=domain_id)
        if not domain:
            return None
        return func(domain_id, *args, **kwargs)

    return wrapper
</code>```

Here is a wrapped up function:

```<code>@check_domain
def collect_data(domain_id, from_date, to_date):
    do_stuff(...)
</code>```

If I do collect_data.__name__ I get wrapper instead of collect_data

Any ideas?

答:
For anyone who needs to access the decorated function name when there are multiple decorators, like this:

```<code>@decorator1
@decorator2
@decorator3
def decorated_func(stuff):
    return stuff
</code>```

the functools.wraps mentioned above solves that.

ContentLicense: CC BY-SA 2.5

Title: Get the name of a decorated function?

Body:
here is my decorator:

def check_domain(func):

    def wrapper(domain_id, *args, **kwargs):
        domain = get_object_or_None(Domain, id=domain_id)
        if not domain:
            return None
        return func(domain_id, *args, **kwargs)

    return wrapper

Here is a wrapped up function:

@check_domain
def collect_data(domain_id, from_date, to_date):
    do_stuff(...)

If I do collect_data.__name__ I get wrapper instead of collect_data

Any ideas?

Body:
For anyone who needs to access the decorated function name when there are multiple decorators, like this:

@decorator1
@decorator2
@decorator3
def decorated_func(stuff):
    return stuff

the functools.wraps mentioned above solves that.


问:
c++ size of a struct with a function
The result says 12.

Where is the function foobar stored in the memory?

```<code>#include <iostream>
using namespace std;
struct ABC_ {
    int a;
    int b;
    int c;
    int foobar(int a) {
        return a;
    }
};
int main() {
    ABC_ ABC;
    cout << sizeof ABC;
    return 0;
}
</code>```

答: The function foobar is not part of the object. Rather, it is part of the compiled program. When the function is called, the machine code refers to its address.

Title: c++ size of a struct with a function

Body:
The result says 12.

Where is the function foobar stored in the memory?

#include <iostream>
using namespace std;
struct ABC_ {
    int a;
    int b;
    int c;
    int foobar(int a) {
        return a;
    }
};
int main() {
    ABC_ ABC;
    cout << sizeof ABC;
    return 0;
}


问:
ASP.NET mvc: How to automatic fill the date field with today's date?
Assume that a model has a datetime datatype.
So in view there will be a blank field ask you to input datetime.

Is there a way to fill this HTML field with today's date/datetime as default value?

答:
```<code>model.SomeDateField = DateTime.Now();

return View(model);
</code>```


问:
Correct way for excluding constraints based on index
Assume the following constraint:

```<code>@constraint(model, [i=1:5,j=1:5], a[i] <= b[j])
</code>```

How do I exclude constraint where i == j from the above? This is simple to do in AMPL but I can't find any similar syntax in JuMP.

Body:
Assume the following constraint:

@constraint(model, [i=1:5,j=1:5], a[i] <= b[j])

How do I exclude constraint where i == j from the above? This is simple to do in AMPL but I can't find any similar syntax in JuMP.

Body: @constraint(model, [i=1:5, j=1:5; i != j], a[i] <= b[j])


问:
How to make a public dictionary in an Excel
I have something like this:

```<code>Private Sub ComboBox1_Change()
'(...do something related to alpha...)
End Sub

Private Sub UserForm_Activate()
Set alpha = CreateObject("Scripting.Dictionary")
'(...do something like add keys and values to the alpha dictionary...)
End Sub
</code>```

I'm really new at VBA and I noticed that alpha dictionary can only be used inside UserForm_Activate, so I want to make a global variable in order to use it also in ComboBox1_Change.

But I can't.

I tried with something more simple, like an integer.

```<code>Public x as Integer

Private Sub ComboBox1_Change()
MsgBox(x)
End Sub

Private Sub UserForm_Activate()
x = 5
End Sub
</code>```

And this work, but if I do something similar but with a dictionary (Public alpha as Scripting.Dictionary), it raise (from spanish) "Compilation error: It wasn't defined the type defined by the user". I don't know what to do.

答: Using Public Alpha As Object above everything. Then Alpha can be change to a dictionary using Set alpha = CreateObject("Scripting.Dictionary").

Body:
I have something like this:

Private Sub ComboBox1_Change()
'(...do something related to alpha...)
End Sub

Private Sub UserForm_Activate()
Set alpha = CreateObject("Scripting.Dictionary")
'(...do something like add keys and values to the alpha dictionary...)
End Sub

I'm really new at VBA and I noticed that alpha dictionary can only be used inside UserForm_Activate, so I want to make a global variable in order to use it also in ComboBox1_Change.

But I can't.

I tried with something more simple, like an integer.

Public x as Integer

Private Sub ComboBox1_Change()
MsgBox(x)
End Sub

Private Sub UserForm_Activate()
x = 5
End Sub

And this work, but if I do something similar but with a dictionary (Public alpha as Scripting.Dictionary), it raise (from spanish) "Compilation error: It wasn't defined the type defined by the user". I don't know what to do.


问:
One line if-condition-assignment
I have the following code

```<code>num1 = 10
someBoolValue = True
</code>```

I need to set the value of num1 to 20 if someBoolValue is True; and do nothing otherwise. So, here is my code for that

```<code>num1 = 20 if someBoolValue else num1
</code>```

Is there someway I could avoid the ...else num1 part to make it look cleaner? An equivalent to

```<code>if someBoolValue:
    num1 = 20
</code>```

I tried replacing it with ...else pass like this: num1=20 if someBoolValue else pass. All I got was syntax error. Nor I could just omit the ...else num1 part.

答:
```<code>num1 = 10 + 10*(someBoolValue is True)
</code>```

That's my new final answer.
Prior answer was as follows and was overkill for the stated problem. Getting_too_clever == not Good.  Here's the prior answer... still good if you want add one thing for True cond and another for False:

```<code>num1 = 10 + (0,10)[someBoolValue is True]
</code>```

You mentioned num1 would already have a value that should be left alone.  I assumed num1 = 10 since that's the first statement of the post, so the operation to get to 20 is to add 10.

```<code>num1 = 10
someBoolValue = True

num1 = 10 + (0,10)[someBoolValue is True]

print(f'num1 = {num1}\nsomeBoolValue = {someBoolValue}')
</code>```

produced this output

```<code>num1 = 20
someBoolValue = True
</code>```

ContentLicense: CC BY-SA 4.0

Title: One line if-condition-assignment

Body:
I have the following code

num1 = 10
someBoolValue = True

I need to set the value of num1 to 20 if someBoolValue is True; and do nothing otherwise. So, here is my code for that

num1 = 20 if someBoolValue else num1

Is there someway I could avoid the ...else num1 part to make it look cleaner? An equivalent to

if someBoolValue:
    num1 = 20

I tried replacing it with ...else pass like this: num1=20 if someBoolValue else pass. All I got was syntax error. Nor I could just omit the ...else num1 part.

Body:
num1 = 10 + 10*(someBoolValue is True)

That's my new final answer.
Prior answer was as follows and was overkill for the stated problem. Getting_too_clever == not Good.  Here's the prior answer... still good if you want add one thing for True cond and another for False:

num1 = 10 + (0,10)[someBoolValue is True]

You mentioned num1 would already have a value that should be left alone.  I assumed num1 = 10 since that's the first statement of the post, so the operation to get to 20 is to add 10.

num1 = 10
someBoolValue = True

num1 = 10 + (0,10)[someBoolValue is True]

print(f'num1 = {num1}\nsomeBoolValue = {someBoolValue}')

produced this output

num1 = 20
someBoolValue = True


问:
Live streaming .webm file with ffmpeg and nginx
Hi I am new to ffmpeg and I need some help with live streaming of .webm file which is still being written into. I have a .webm file containing only video in vp9 codecwhich needs to be live streamed (preferably without transcoding and streamed using DASH`. I have compiled nginx along with nginx-ts-module from (https://github.com/arut/nginx-ts-module#features) with the following configuration

```<code>nginx version: nginx/1.12.1
built by gcc 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.3)
built with OpenSSL 1.0.1f 6 Jan 2014
TLS SNI support enabled
configure arguments: --with-cc-opt='-g -O2 -fPIE -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -fPIC -D_FORTIFY_SOURCE=2' --with-ld-opt='-Wl,-Bsymbolic-functions -fPIE -pie -Wl,-z,relro -Wl,-z,now -fPIC' --prefix=/usr/share/nginx --conf-path=/etc/nginx/nginx.conf --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --lock-path=/var/lock/nginx.lock --pid-path=/run/nginx.pid --modules-path=/usr/lib/nginx/modules --http-client-body-temp-path=/var/lib/nginx/body --http-fastcgi-temp-path=/var/lib/nginx/fastcgi --http-proxy-temp-path=/var/lib/nginx/proxy --http-scgi-temp-path=/var/lib/nginx/scgi --http-uwsgi-temp-path=/var/lib/nginx/uwsgi --with-debug --with-pcre-jit --with-http_ssl_module --with-http_stub_status_module --with-http_realip_module --with-http_auth_request_module --with-http_v2_module --with-http_dav_module --with-http_slice_module --with-threads --with-http_addition_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_sub_module --with-stream=dynamic --with-stream_ssl_module --with-stream_ssl_preread_module --with-mail=dynamic --with-mail_ssl_module --add-dynamic-module=/home/ubuntu/NGINX/nginx-ts-module-master
</code>```

The mediafile has the following properties(obtained with mediainfo):

```<code>General
Complete name                            : video_4_1_Admin_0.webm
Format                                   : WebM
Format version                           : Version 2
File size                                : 19.7 MiB
Duration                                 : 1ms
Overall bit rate                         : 165 Gbps
Writing library                          : libwebm-0.2.1.0
Video
ID                                       : 1
Format                                   : VP9
Codec ID                                 : V_VP9
Width                                    : 320 pixels
Height                                   : 180 pixels
Display aspect ratio                     : 16:9
Frame rate mode                          : Variable
Language                                 : English
Default                                  : Yes
Forced                                   : No
</code>```

I am trying to stream the file with the following

```<code>ffmpeg -re -i video_4_1_Admin_0.webm -bsf:v vp9_superframe -c copy -f webm_chunk  http://127.0.0.1:8000/publish/sintel
</code>```

And I am getting the following error

```<code>Input #0, matroska,webm, from 'video_4_1_Admin_0.webm':
  Metadata:
    encoder         : libwebm-0.2.1.0
  Duration: 00:00:00.00, start: 0.000000, bitrate: 174444152 kb/s
    Stream #0:0(eng): Video: vp9 (Profile 0), yuv420p(tv), 320x180, SAR 1:1 DAR 16:9, 30 fps, 30 tbr, 1k tbn, 1k tbc (default)
Output #0, webm_chunk, to 'http://127.0.0.1:8000/publish/sintel':
Output file #0 does not contain any stream
</code>```

I am not sure what are the exact options to be passed to ffmpeg so that it creates the .mpd and needed chunks which will allow me to LiveStream the media, I tried replacing the options given in the example (https://github.com/arut/nginx-ts-module#features) with what seems like vp9 equivalent., but, I am not sure. Can someone help me out here? Thanks in advance

答:
WebM is not MPEG-TS.

Nginx is not appropriate for your use case.  You can use Icecast instead.

Body:
Hi I am new to ffmpeg and I need some help with live streaming of .webm file which is still being written into. I have a .webm file containing only video in vp9 codecwhich needs to be live streamed (preferably without transcoding and streamed using DASH`. I have compiled nginx along with nginx-ts-module from (https://github.com/arut/nginx-ts-module#features) with the following configuration

nginx version: nginx/1.12.1
built by gcc 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.3)
built with OpenSSL 1.0.1f 6 Jan 2014
TLS SNI support enabled
configure arguments: --with-cc-opt='-g -O2 -fPIE -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -fPIC -D_FORTIFY_SOURCE=2' --with-ld-opt='-Wl,-Bsymbolic-functions -fPIE -pie -Wl,-z,relro -Wl,-z,now -fPIC' --prefix=/usr/share/nginx --conf-path=/etc/nginx/nginx.conf --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --lock-path=/var/lock/nginx.lock --pid-path=/run/nginx.pid --modules-path=/usr/lib/nginx/modules --http-client-body-temp-path=/var/lib/nginx/body --http-fastcgi-temp-path=/var/lib/nginx/fastcgi --http-proxy-temp-path=/var/lib/nginx/proxy --http-scgi-temp-path=/var/lib/nginx/scgi --http-uwsgi-temp-path=/var/lib/nginx/uwsgi --with-debug --with-pcre-jit --with-http_ssl_module --with-http_stub_status_module --with-http_realip_module --with-http_auth_request_module --with-http_v2_module --with-http_dav_module --with-http_slice_module --with-threads --with-http_addition_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_sub_module --with-stream=dynamic --with-stream_ssl_module --with-stream_ssl_preread_module --with-mail=dynamic --with-mail_ssl_module --add-dynamic-module=/home/ubuntu/NGINX/nginx-ts-module-master

The mediafile has the following properties(obtained with mediainfo):

General
Complete name                            : video_4_1_Admin_0.webm
Format                                   : WebM
Format version                           : Version 2
File size                                : 19.7 MiB
Duration                                 : 1ms
Overall bit rate                         : 165 Gbps
Writing library                          : libwebm-0.2.1.0
Video
ID                                       : 1
Format                                   : VP9
Codec ID                                 : V_VP9
Width                                    : 320 pixels
Height                                   : 180 pixels
Display aspect ratio                     : 16:9
Frame rate mode                          : Variable
Language                                 : English
Default                                  : Yes
Forced                                   : No

I am trying to stream the file with the following

ffmpeg -re -i video_4_1_Admin_0.webm -bsf:v vp9_superframe -c copy -f webm_chunk  http://127.0.0.1:8000/publish/sintel

And I am getting the following error

Input #0, matroska,webm, from 'video_4_1_Admin_0.webm':
  Metadata:
    encoder         : libwebm-0.2.1.0
  Duration: 00:00:00.00, start: 0.000000, bitrate: 174444152 kb/s
    Stream #0:0(eng): Video: vp9 (Profile 0), yuv420p(tv), 320x180, SAR 1:1 DAR 16:9, 30 fps, 30 tbr, 1k tbn, 1k tbc (default)
Output #0, webm_chunk, to 'http://127.0.0.1:8000/publish/sintel':
Output file #0 does not contain any stream

I am not sure what are the exact options to be passed to ffmpeg so that it creates the .mpd and needed chunks which will allow me to LiveStream the media, I tried replacing the options given in the example (https://github.com/arut/nginx-ts-module#features) with what seems like vp9 equivalent., but, I am not sure. Can someone help me out here? Thanks in advance


问:
How to write function in R that does glm for a data frame?
I have:

```<code>myColCI<-function(colName){
  predictorvariable <- glm(death180 ~ nepalData[,colName], data=nepalData, family="binomial")
  summary(predictorvariable)
  confint(predictorvariable)
}
</code>```

One of the names of the column is parity so when after making my function, when I put myColCI(parity), it says the

object "parity" is not found

Can anyone give me a pointer to what's wrong with my code.

答:
Your formula is wrong here, hence you are getting the error, The right hand side after tilda side shouldn't be a reference to a dataframe. It should be column names separated by plus signs :

From the documentation of ?formula

The models fit by, e.g., the lm and glm functions are specified in a
  compact symbolic form. The ~ operator is basic in the formation of
  such models. An expression of the form y ~ model is interpreted as a
  specification that the response y is modelled by a linear predictor
  specified symbolically by model. Such a model consists of a series of
  terms separated by + operators. The terms themselves consist of
  variable and factor names separated by : operators. Such a term is
  interpreted as the interaction of all the variables and factors
  appearing in the term.

dependent_variable ~ Independent_variable1 + Independent_variable2 etc

From data mtcars, I have written a glm formula as :
glm(am ~ mpg + disp + hp, data=mtcars, family="binomial")

So, your formula should be something like this:

```<code>glm(death180 ~ column1 + column2 +column3, data= nepalData, family="binomial")
</code>```

To invoke this inside a function, since you have only one dependent variable it seems you can use below (Note here that, removing the datframe reference here and adding the as.formula expression to incorporate strings, convert the expression as valid formula):

```<code>myColCI<-function(colName){
  predictorvariable <- glm(as.formula(paste0("death180 ~", colName)), data=nepalData, family="binomial")
  summary(predictorvariable)
  confint(predictorvariable)
}

myColCI("parity")
</code>```

Body:
I have:

myColCI<-function(colName){
  predictorvariable <- glm(death180 ~ nepalData[,colName], data=nepalData, family="binomial")
  summary(predictorvariable)
  confint(predictorvariable)
}

One of the names of the column is parity so when after making my function, when I put myColCI(parity), it says the

object "parity" is not found

Can anyone give me a pointer to what's wrong with my code.

Body:
Your formula is wrong here, hence you are getting the error, The right hand side after tilda side shouldn't be a reference to a dataframe. It should be column names separated by plus signs :

From the documentation of ?formula

The models fit by, e.g., the lm and glm functions are specified in a
  compact symbolic form. The ~ operator is basic in the formation of
  such models. An expression of the form y ~ model is interpreted as a
  specification that the response y is modelled by a linear predictor
  specified symbolically by model. Such a model consists of a series of
  terms separated by + operators. The terms themselves consist of
  variable and factor names separated by : operators. Such a term is
  interpreted as the interaction of all the variables and factors
  appearing in the term.

dependent_variable ~ Independent_variable1 + Independent_variable2 etc

From data mtcars, I have written a glm formula as :
glm(am ~ mpg + disp + hp, data=mtcars, family="binomial")

So, your formula should be something like this:

glm(death180 ~ column1 + column2 +column3, data= nepalData, family="binomial")

To invoke this inside a function, since you have only one dependent variable it seems you can use below (Note here that, removing the datframe reference here and adding the as.formula expression to incorporate strings, convert the expression as valid formula):

myColCI<-function(colName){
  predictorvariable <- glm(as.formula(paste0("death180 ~", colName)), data=nepalData, family="binomial")
  summary(predictorvariable)
  confint(predictorvariable)
}

myColCI("parity")


问:
neutron.plugins.ml2.drivers.linuxbridge.agent.linuxbridge_neutron_agent [-] Interface for physical network provider does not exist
I install controller node and compute node in one server. when I install the compute service:

I use neutron agent-list shows nothing:

```<code>[root@controller ~]# neutron agent-list
neutron CLI is deprecated and will be removed in the future. Use openstack CLI instead.
</code>```

I also tried use openstack network agent list, still shows nothing.

I check the /var/log/neutron/linuxbridge-agent.log, find it sayInterface ifcfg-enp2s0f0 for physical network provider does not exist.:

```<code>vim /var/log/neutron/linuxbridge-agent.log

2017-12-07 23:04:08.374 12766 INFO neutron.common.config [-] Logging enabled!
2017-12-07 23:04:08.375 12766 INFO neutron.common.config [-] /usr/bin/neutron-linuxbridge-agent version 10.0.0
2017-12-07 23:04:08.375 12766 INFO neutron.plugins.ml2.drivers.linuxbridge.agent.linuxbridge_neutron_agent [-] Interface mappings: {'provider': 'ifcfg-enp2s0f0'}
2017-12-07 23:04:08.375 12766 INFO neutron.plugins.ml2.drivers.linuxbridge.agent.linuxbridge_neutron_agent [-] Bridge mappings: {}
2017-12-07 23:04:08.382 12766 ERROR neutron.plugins.ml2.drivers.linuxbridge.agent.linuxbridge_neutron_agent [-] Interface ifcfg-enp2s0f0 for physical network provider does not exist. Agent terminated!
</code>```

I use vim /etc/neutron/plugins/ml2/linuxbridge_agent.ini check my linuxbridge_agent.ini:

```<code>[linux_bridge]
physical_interface_mappings = provider:ifcfg-enp2s0f0

[securitygroup]
enable_security_group = True
firewall_driver = neutron.agent.linux.iptables_firewall.IptablesFirewallDriver

[vxlan]
enable_vxlan = True
local_ip = 10.1.1.120
l2_population = True
</code>```

But however in my /etc/sysconfig/network-scripts/， I have ifcfg-enp2s0f0 and ifcfg-enp2s0f1 network-interfaces.

in my ifcfg-enp2s0f0:

```<code>TYPE="Ethernet"
BOOTPROTO="static"
DEFROUTE="yes"
IPV4_FAILURE_FATAL="no"
IPV6INIT="no"
IPV6_AUTOCONF="yes"
IPV6_DEFROUTE="yes"
IPV6_FAILURE_FATAL="no"
NAME="enp2s0f0"
UUID="2748d036-2377-4d8d-9753-52873fe03d3d"
DEVICE="enp2s0f0"
ONBOOT="yes"
IPADDR="100.35.202.1"
PREFIX="29"
IPADDR1="100.35.202.2"
PREFIX1="29"
IPADDR2="100.35.202.3"
PREFIX2="29"
IPADDR3="100.35.202.4"
PREFIX3="29"
IPADDR4="100.35.202.5"
PREFIX4="29"
GATEWAY="100.35.202.6"
DNS1="8.8.8.8"
IPV6_PEERDNS="yes"
IPV6_PEERROUTES="yes"
IPV6_PRIVACY="no"
</code>```

in my ifcfg-enp2s0f1:

```<code>TYPE=Ethernet
BOOTPROTO=static
DEFROUTE=yes
PEERDNS=yes
PEERROUTES=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=no
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_PEERDNS=yes
IPV6_PEERROUTES=yes
IPV6_FAILURE_FATAL=no
NAME=enp2s0f1
UUID=098161a9-4bae-4ff2-a768-eeaada509507
DEVICE=enp2s0f1
ONBOOT=yes
IPADDR=10.1.1.120
NETMASK=255.255.255.0
~
</code>```

I don't know whtere is the issue, some friend can help me about it?

答:
Thanks to Bernd Bausch, he tell me the issue is:

```<code>physical_interface_mappings = provider:ifcfg-enp2s0f0
</code>```

My network-interface name is enp2s0f0, not the ifcfg-enp2s0f0.

Body:
I install controller node and compute node in one server. when I install the compute service:

I use neutron agent-list shows nothing:

[root@controller ~]# neutron agent-list
neutron CLI is deprecated and will be removed in the future. Use openstack CLI instead.

I also tried use openstack network agent list, still shows nothing.

I check the /var/log/neutron/linuxbridge-agent.log, find it sayInterface ifcfg-enp2s0f0 for physical network provider does not exist.:

vim /var/log/neutron/linuxbridge-agent.log

2017-12-07 23:04:08.374 12766 INFO neutron.common.config [-] Logging enabled!
2017-12-07 23:04:08.375 12766 INFO neutron.common.config [-] /usr/bin/neutron-linuxbridge-agent version 10.0.0
2017-12-07 23:04:08.375 12766 INFO neutron.plugins.ml2.drivers.linuxbridge.agent.linuxbridge_neutron_agent [-] Interface mappings: {'provider': 'ifcfg-enp2s0f0'}
2017-12-07 23:04:08.375 12766 INFO neutron.plugins.ml2.drivers.linuxbridge.agent.linuxbridge_neutron_agent [-] Bridge mappings: {}
2017-12-07 23:04:08.382 12766 ERROR neutron.plugins.ml2.drivers.linuxbridge.agent.linuxbridge_neutron_agent [-] Interface ifcfg-enp2s0f0 for physical network provider does not exist. Agent terminated!

I use vim /etc/neutron/plugins/ml2/linuxbridge_agent.ini check my linuxbridge_agent.ini:

[linux_bridge]
physical_interface_mappings = provider:ifcfg-enp2s0f0

[securitygroup]
enable_security_group = True
firewall_driver = neutron.agent.linux.iptables_firewall.IptablesFirewallDriver

[vxlan]
enable_vxlan = True
local_ip = 10.1.1.120
l2_population = True

But however in my /etc/sysconfig/network-scripts/， I have ifcfg-enp2s0f0 and ifcfg-enp2s0f1 network-interfaces.

in my ifcfg-enp2s0f0:

TYPE="Ethernet"
BOOTPROTO="static"
DEFROUTE="yes"
IPV4_FAILURE_FATAL="no"
IPV6INIT="no"
IPV6_AUTOCONF="yes"
IPV6_DEFROUTE="yes"
IPV6_FAILURE_FATAL="no"
NAME="enp2s0f0"
UUID="2748d036-2377-4d8d-9753-52873fe03d3d"
DEVICE="enp2s0f0"
ONBOOT="yes"
IPADDR="100.35.202.1"
PREFIX="29"
IPADDR1="100.35.202.2"
PREFIX1="29"
IPADDR2="100.35.202.3"
PREFIX2="29"
IPADDR3="100.35.202.4"
PREFIX3="29"
IPADDR4="100.35.202.5"
PREFIX4="29"
GATEWAY="100.35.202.6"
DNS1="8.8.8.8"
IPV6_PEERDNS="yes"
IPV6_PEERROUTES="yes"
IPV6_PRIVACY="no"

in my ifcfg-enp2s0f1:

TYPE=Ethernet
BOOTPROTO=static
DEFROUTE=yes
PEERDNS=yes
PEERROUTES=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=no
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_PEERDNS=yes
IPV6_PEERROUTES=yes
IPV6_FAILURE_FATAL=no
NAME=enp2s0f1
UUID=098161a9-4bae-4ff2-a768-eeaada509507
DEVICE=enp2s0f1
ONBOOT=yes
IPADDR=10.1.1.120
NETMASK=255.255.255.0
~

I don't know whtere is the issue, some friend can help me about it?

Body:
Thanks to Bernd Bausch, he tell me the issue is:

physical_interface_mappings = provider:ifcfg-enp2s0f0

My network-interface name is enp2s0f0, not the ifcfg-enp2s0f0.


问:
Are there any differences between applying floor division and int() after dividing?
It seems there are cases that the outputs are different between applying floor division and int() after dividing.
Could you explain me the reasons or show me concrete cases?

Problem:
int(a // b) is not equal to int(a / b)

Situation:
a and b are integer and 0 < a,b <= 1e18

Setting:
Python 3.4.3

Note:
I cannot list up concrete cases because they are made by online judge test and test cases are not public.

I hope your help.
Thank you.

答:
Concrete example (in Python 3.4.4 shell):

```<code>>>> int(99999999999999999/100000000000000000)
1
>>> 99999999999999999//100000000000000000
0
</code>```

This happens when the result of the (mathematical) float division is very near to an integer so that the numerical float division result is rounded towards this integer.

Body:
Concrete example (in Python 3.4.4 shell):

>>> int(99999999999999999/100000000000000000)
1
>>> 99999999999999999//100000000000000000
0

This happens when the result of the (mathematical) float division is very near to an integer so that the numerical float division result is rounded towards this integer.


问:
Windows Server 2008 Hyper-V on x86 processor
I notice there are two version of Windows Server 2008 w/ Hyper-V available for download on the MSDN Subscription License site:

Windows Server 2008 Datacenter, Enterprise and Standard (x64)

Windows Server 2008 Datacenter, Enterprise and Standard (x86)

I want to set up a development server for testing/developing using the Hyper-V software.  According to the pre-requisites, you can only run Hyper-V on x64 based processor.  Can a run Hyper-V on a x86 based processer?  If not, why do Microsoft offer a x86 and x64 download?

This is a follow up to this question

Update:

The MSDN subscription site also offers a download for Windows Server 2008 Datacenter, Enterprise and Standard without Hyper-V (x64 and x86).  Why don't they just offer one download for x86 version on Windows Server 2008, it is just confusing trying to determine the correct installion ISO....

答:
x86 Does Not require 64-bit hardware. It exists to allow installation of Windows Server 2008 on legacy x86 hardware.

Legacy x86 hardware in my experiences has often times not had Hardware Virtualization support, and these flavors of Windows work great in this case.


问:
Trying to display all posts in given category - getting error
I'm building my first laravel app.

I'm trying to display all posts in x category.

My routes:

```<code>Route::get('/', 'PostsController@index')->name('home');
Route::get('/{id}/{slug?}', 'PostsController@show')->name('show');
Route::get('/categories/{category}', 'CategoriesController@index')->name('category');
</code>```

My category model:

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }

    public function getRouteKeyName()
    {
        return 'slug';
    }
}
</code>```

My category controller:

```<code>namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Category;

class CategoriesController extends Controller
{
    public function index(Category $category)
    {
        $posts = $category->posts;

        return view('index', compact('posts'));
    }
}
</code>```

Getting: "Sorry, the page you are looking for could not be found."

Works if I change:

```<code>Route::get('/{id}/{slug?}', 'PostsController@show')->name('show');
</code>```

To:

```<code>Route::get('/{post}', 'PostsController@show')->name('show');
</code>```

Thank you in advance!

答:
İf you have many to many or one to many relationships between categories and posts, you can do that.

```<code>Route::get('categories/{category_slug?}',['as'=>'category.show','uses'=>'CategoriesController@Show'})
</code>```

and in your controller;

```<code> public function Show($category_slug){

        $category = Category::where('category_slug',$category_slug)->first();

        return view('index',compact('category'));
    }
</code>```

and in your blade;

```<code>@foreach($category->posts as $post)
  $post->title
  $post->content
@endforeach
</code>```

Body:
I'm building my first laravel app.

I'm trying to display all posts in x category.

My routes:

Route::get('/', 'PostsController@index')->name('home');
Route::get('/{id}/{slug?}', 'PostsController@show')->name('show');
Route::get('/categories/{category}', 'CategoriesController@index')->name('category');

My category model:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }

    public function getRouteKeyName()
    {
        return 'slug';
    }
}

My category controller:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Category;

class CategoriesController extends Controller
{
    public function index(Category $category)
    {
        $posts = $category->posts;

        return view('index', compact('posts'));
    }
}

Getting: "Sorry, the page you are looking for could not be found."

Works if I change:

Route::get('/{id}/{slug?}', 'PostsController@show')->name('show');

To:

Route::get('/{post}', 'PostsController@show')->name('show');

Thank you in advance!

Body:
İf you have many to many or one to many relationships between categories and posts, you can do that.

Route::get('categories/{category_slug?}',['as'=>'category.show','uses'=>'CategoriesController@Show'})

and in your controller;

 public function Show($category_slug){

        $category = Category::where('category_slug',$category_slug)->first();

        return view('index',compact('category'));
    }

and in your blade;

@foreach($category->posts as $post)
  $post->title
  $post->content
@endforeach


答:
sizeof() will consider only member variables.

Also, non-vptr methods do not contribute to the size of struct since they do not require any runtime support.

Your struct is similar to

```<code>struct ABC_ {
    int a;
    int b;
    int c;
};
int ABC_::foobar(int a) {
    return a;
}
</code>```

Title: c++ size of a struct with a function

Body:
sizeof() will consider only member variables.

Also, non-vptr methods do not contribute to the size of struct since they do not require any runtime support.

Your struct is similar to

struct ABC_ {
    int a;
    int b;
    int c;
};
int ABC_::foobar(int a) {
    return a;
}


问:
Make VSCode Variables have Colour
I would like to make variables displayed with colours.

This is how it looks:

This is how I want it to be:

Looking through here, I cannot find any settings that allow me to change this.

答:
You should be able to add the color in tokenColors to customize the colors (basic example):

SomeTheme.json

```<code>{
 "name": "Some Theme",
 "type": "dark",
 "colors": {
 ...
},
"tokenColors": [
   {
    "name": "Variables",
    "scope": "variable",
    "settings": {
    "foreground": "#e06c75"
   }
  },
 ]
}
</code>```

I don't have VSCode, although from looking at another themes JSON it looks similar.

Title: Make VSCode Variables have Colour

Body:
You should be able to add the color in tokenColors to customize the colors (basic example):

SomeTheme.json

{
 "name": "Some Theme",
 "type": "dark",
 "colors": {
 ...
},
"tokenColors": [
   {
    "name": "Variables",
    "scope": "variable",
    "settings": {
    "foreground": "#e06c75"
   }
  },
 ]
}

I don't have VSCode, although from looking at another themes JSON it looks similar.


问:
Using RestSharp, how to include a fieldname like "$fieldname" in RestRequest.AddJsonBody()?
Using RestSharp, I need to POST a body containing a json string that looks like this:

```<code>{
    "$a": "b",
    "c": "d"
}
</code>```

In the past I've created RestSharp requests using code like this:

```<code>var request = new RestRequest("someApiEndPoint", RestSharp.Method.POST);
request.AddJsonBody(new
{
    a = "b",
    c = "d"
});
</code>```

What's the best way to add a "$" to the "a" property in this case?

答:
Since you are using an anonymous type, you could just as easily switch to using a dictionary:

```<code>var root = new Dictionary<string, object>
{
    {"$a", "b" },
    {"c", "d" },
};
var request = new RestRequest("someApiEndPoint", RestSharp.Method.POST)
    .AddJsonBody(root);
</code>```

If you were using an explicit type, you could check RestSharp serialization to JSON, object is not using SerializeAs attribute as expected for options.

Body:
Using RestSharp, I need to POST a body containing a json string that looks like this:

{
    "$a": "b",
    "c": "d"
}

In the past I've created RestSharp requests using code like this:

var request = new RestRequest("someApiEndPoint", RestSharp.Method.POST);
request.AddJsonBody(new
{
    a = "b",
    c = "d"
});

What's the best way to add a "$" to the "a" property in this case?

Body:
Since you are using an anonymous type, you could just as easily switch to using a dictionary:

var root = new Dictionary<string, object>
{
    {"$a", "b" },
    {"c", "d" },
};
var request = new RestRequest("someApiEndPoint", RestSharp.Method.POST)
    .AddJsonBody(root);

If you were using an explicit type, you could check RestSharp serialization to JSON, object is not using SerializeAs attribute as expected for options.


问:
How to find most common value for specific categories in MongoDB?
I have a dataset in MongoDB that looks like this:

```<code>{ "name": "Tom's", "category": "coffee shop" },
{ "name": "Red Lobster", "category": "restaurant" },
{ "name": "Tom's", "category": "coffee shop" },
{ "name": "Starbucks", "category": "coffee shop" },
{ "name": "Central Park", "category": "park" },
{ "name": "Office", "category": "office" },
{ "name": "Red Lobster", "category": "restaurant" },
{ "name": "Home", "category": "home" },
{ ... } // and so on
</code>```

How can I find the most common value for specific categories? For example, the most common occurring value for coffee shop and restaurant should be Tom's and Red Lobster, respectively.

My current $aggregate query only seems to list the most common occurring value among ALL of the dataset:

```<code>db.collection.aggregate(
{ "$group": { "_id": { "name": "$name" }, "count": { "$sum":1 } }},
{ "$group": { "_id": "$_id.name", "count": { "$sum": "$count" } }},
{ "$sort": { "count":-1 }}
)
</code>```

答:
You can try the below query.

$group on category and name to get the count for each category and name combination.

$sort the input documents by category and count desc.

$group on category with $first to pick the document with most occurrences.

```<code>db.collection_name.aggregate([
  {
    "$group": {
      "_id": {
        "category": "$category",
        "name": "$name"
      },
      "count": {
        "$sum": 1
      }
    }
  },
  {
    "$sort": {
      "_id.category": 1,
      "count": -1
    }
  },
  {
    "$group": {
      "_id": {
        "category": "$_id.category"
      },
      "name": {
        "$first": "$_id.name"
      },
      "count": {
        "$first": "$count"
      }
    }
  }
])
</code>```

Body:
I have a dataset in MongoDB that looks like this:

{ "name": "Tom's", "category": "coffee shop" },
{ "name": "Red Lobster", "category": "restaurant" },
{ "name": "Tom's", "category": "coffee shop" },
{ "name": "Starbucks", "category": "coffee shop" },
{ "name": "Central Park", "category": "park" },
{ "name": "Office", "category": "office" },
{ "name": "Red Lobster", "category": "restaurant" },
{ "name": "Home", "category": "home" },
{ ... } // and so on

How can I find the most common value for specific categories? For example, the most common occurring value for coffee shop and restaurant should be Tom's and Red Lobster, respectively.

My current $aggregate query only seems to list the most common occurring value among ALL of the dataset:

db.collection.aggregate(
{ "$group": { "_id": { "name": "$name" }, "count": { "$sum":1 } }},
{ "$group": { "_id": "$_id.name", "count": { "$sum": "$count" } }},
{ "$sort": { "count":-1 }}
)

Body:
You can try the below query.

$group on category and name to get the count for each category and name combination.

$sort the input documents by category and count desc.

$group on category with $first to pick the document with most occurrences.

db.collection_name.aggregate([
  {
    "$group": {
      "_id": {
        "category": "$category",
        "name": "$name"
      },
      "count": {
        "$sum": 1
      }
    }
  },
  {
    "$sort": {
      "_id.category": 1,
      "count": -1
    }
  },
  {
    "$group": {
      "_id": {
        "category": "$_id.category"
      },
      "name": {
        "$first": "$_id.name"
      },
      "count": {
        "$first": "$count"
      }
    }
  }
])


问:
Check URL parameter in php
I want to check a parameter in a url variable, for example:

```<code>$var2join = 'en'; // can be anything else
$url = 'https://www.example.com/hello/parameter2';
$url2 = 'https://www.example.com/hello2';
$url3 = 'https://www.example.com/en/hey';
</code>```

first check if the $url vars have the $var2join into $var as parameter if have it, leave it intact and if not add it.

Wanted output:

```<code>$url = 'https://www.example.com/en/hello/parameter2';
$url2 = 'https://www.example.com/en/hello2';
$url3 = 'https://www.example.com/en/hey';
</code>```

I tried:

```<code>$url = (!preg_match('~^/[a-z]{2}(?:/|$)~', $location)) ? '/' . $var2join . $url : $url;
</code>```

答:
This is a little generic function with some support code to give you some ideas... Not very elegant but it works.</p>

```<code><?php

$base_url = 'https://www.example.com/';
$var2join = 'en'; // can be anything else

$url = $base_url . 'hello/parameter2';
$url2 = $base_url . 'hello2';
$url3 = $base_url . 'en/hey';
$url4 = $base_url . 'hey/this/is/longer';

echo prepend_path_to_url($base_url, $url, $var2join);
echo '<br>';
echo prepend_path_to_url($base_url, $url2, $var2join);
echo '<br>';
echo prepend_path_to_url($base_url, $url3, $var2join);
echo '<br>';
echo prepend_path_to_url($base_url, $url4, $var2join);
echo '<br>';

/**
 * Prepend a Path to the url
 *
 * @param $base_url
 * @param $url
 * @param $path_to_join
 * @return string
 */
function prepend_path_to_url($base_url, $url, $path_to_join) {
    // Does the path_to_join exist in the url
    if (strpos($url, $path_to_join) === FALSE) {
        $url_request = str_replace($base_url,'',$url);
        $url = $base_url . $path_to_join . '/'. $url_request;
    }
    return $url;
}
</code>```

Title: Check URL parameter in php

Body:
I want to check a parameter in a url variable, for example:

$var2join = 'en'; // can be anything else
$url = 'https://www.example.com/hello/parameter2';
$url2 = 'https://www.example.com/hello2';
$url3 = 'https://www.example.com/en/hey';

first check if the $url vars have the $var2join into $var as parameter if have it, leave it intact and if not add it.

Wanted output:

$url = 'https://www.example.com/en/hello/parameter2';
$url2 = 'https://www.example.com/en/hello2';
$url3 = 'https://www.example.com/en/hey';

I tried:

$url = (!preg_match('~^/[a-z]{2}(?:/|$)~', $location)) ? '/' . $var2join . $url : $url;

Body:
This is a little generic function with some support code to give you some ideas... Not very elegant but it works.

<?php

$base_url = 'https://www.example.com/';
$var2join = 'en'; // can be anything else

$url = $base_url . 'hello/parameter2';
$url2 = $base_url . 'hello2';
$url3 = $base_url . 'en/hey';
$url4 = $base_url . 'hey/this/is/longer';

echo prepend_path_to_url($base_url, $url, $var2join);
echo '<br>';
echo prepend_path_to_url($base_url, $url2, $var2join);
echo '<br>';
echo prepend_path_to_url($base_url, $url3, $var2join);
echo '<br>';
echo prepend_path_to_url($base_url, $url4, $var2join);
echo '<br>';

/**
 * Prepend a Path to the url
 *
 * @param $base_url
 * @param $url
 * @param $path_to_join
 * @return string
 */
function prepend_path_to_url($base_url, $url, $path_to_join) {
    // Does the path_to_join exist in the url
    if (strpos($url, $path_to_join) === FALSE) {
        $url_request = str_replace($base_url,'',$url);
        $url = $base_url . $path_to_join . '/'. $url_request;
    }
    return $url;
}


问:
how to I fix my table about distinct and count in ASP.NET MVC
I have trouble about my table and about my Count and Distinct

this for my RazorView

```<code><table id="example2" class="table table-bordered table-striped">
    <thead>
        <tr>
            <th rowspan="2">Tahun</th>
            <th colspan="2">Jml. F1</th>
            <th rowspan="2">Jml. F2 PR</th>
            <th rowspan="2">Jml. F2 PE</th>
        </tr>
        <tr>
            <th>Sementara</th>
            <th>Tetap</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model.rol_tb_form1List.Select(x => x.tgl_moc.Year).Distinct())
            {
                <tr>
                    <td>@Html.DisplayFor(x => item)</td>
                </tr>
            }
        @foreach (var form1 in Model.rol_tb_form1List.Where(y => y.jenis_perubahan == "sementara").GroupBy(x => x.tgl_moc.Year))
            {
                <tr>
                     <td>@Html.DisplayFor(x => form1).ToString().Count()</td>
                </tr>
            }
        @foreach (var form1 in Model.rol_tb_form1List.Where(y => y.jenis_perubahan == "tetap").GroupBy(x => x.tgl_moc.Year))
            {
                <tr>
                     <td>@Html.DisplayFor(x => form1).ToString().Count()</td>
                </tr>
            }
    </tbody>
</table>
</code>```

can someone fix my code about my table or my Count or my Distinct..

sorry about my bad english

this foy my Controller

```<code>public ActionResult Rekap()
    {
        Setting setting = new Setting();
        setting.rol_tb_form1List = db.rol_tb_form1.ToList();
        return View(setting);
    }
</code>```

I just use a simple Controller but I dont know this right or not..

result for that code

I want value 19 18 42 49 in column Sementara and value 377 363 63 13 in column Tetap

this for my example data, this just example

and I want result for thats example is like this

答:
A few principals that you should always follow:

Your controller is responsible for passing the correct data to the
view (your views should not contain queries)

Create view models to represent the way you want the represent the
data in the view

In you case you need a view model to represent your table, and to represent each row in your table

```<code>public class RowVM
{
    // Properties for each column
    public int Tahun { get; set; }
    public int Sementara { get; set; }
    public int Tetap { get; set; }
}
public class TableVM
{
    public Enumerable<RowVM> Rows { get; set; }
    .... // other properties as required to represent the table header, footer etc
}
</code>```

Then in the GET method, change the query to return the data and project it into your view model

```<code>var data = db.rol_tb_form1.AsEnumerable().GroupBy(x => x.tgl_moc.Year).Select(x => new RowVM
{
    Tahun = x.Key,
    Sementara = x.Where(y => y.genis_perubahan == "sementara").Count(),
    Tetap = x.Where(y => y.genis_perubahan == "tetap").Count()
});
TableVM model = new TableVM
{
    Rows = data,
    ....
};
return View(model);
</code>```

and the view is simply

```<code>@model TableVM
....
<table>
    <thead> .... </thead>
    <tbody>
        @foreach (var row in Model.Rows)
        {
            <tr>
                <td>@row.Tahun<td>
                <td>@row.Sementara<td>
                <td>@row.Tetap<td>
            </tr>
        }
    </tbody>
</table>
</code>```

Note that I omitted the table headings because its not clear what your trying to do with your first image, but since the rows contain 3 columns, then you heading should also contain 3 columns.

Body:
I have trouble about my table and about my Count and Distinct

this for my RazorView

            Tahun
            Jml. F1
            Jml. F2 PR
            Jml. F2 PE

            Sementara
            Tetap

        @foreach (var item in Model.rol_tb_form1List.Select(x => x.tgl_moc.Year).Distinct())
            {

                    @Html.DisplayFor(x => item)

            }
        @foreach (var form1 in Model.rol_tb_form1List.Where(y => y.jenis_perubahan == "sementara").GroupBy(x => x.tgl_moc.Year))
            {

                     @Html.DisplayFor(x => form1).ToString().Count()

            }
        @foreach (var form1 in Model.rol_tb_form1List.Where(y => y.jenis_perubahan == "tetap").GroupBy(x => x.tgl_moc.Year))
            {

                     @Html.DisplayFor(x => form1).ToString().Count()

            }

can someone fix my code about my table or my Count or my Distinct..

sorry about my bad english

this foy my Controller

public ActionResult Rekap()
    {
        Setting setting = new Setting();
        setting.rol_tb_form1List = db.rol_tb_form1.ToList();
        return View(setting);
    }

I just use a simple Controller but I dont know this right or not..

result for that code

I want value 19 18 42 49 in column Sementara and value 377 363 63 13 in column Tetap

this for my example data, this just example

and I want result for thats example is like this

Body:
A few principals that you should always follow:

Your controller is responsible for passing the correct data to the
view (your views should not contain queries)

Create view models to represent the way you want the represent the
data in the view

In you case you need a view model to represent your table, and to represent each row in your table

public class RowVM
{
    // Properties for each column
    public int Tahun { get; set; }
    public int Sementara { get; set; }
    public int Tetap { get; set; }
}
public class TableVM
{
    public Enumerable<RowVM> Rows { get; set; }
    .... // other properties as required to represent the table header, footer etc
}

Then in the GET method, change the query to return the data and project it into your view model

var data = db.rol_tb_form1.AsEnumerable().GroupBy(x => x.tgl_moc.Year).Select(x => new RowVM
{
    Tahun = x.Key,
    Sementara = x.Where(y => y.genis_perubahan == "sementara").Count(),
    Tetap = x.Where(y => y.genis_perubahan == "tetap").Count()
});
TableVM model = new TableVM
{
    Rows = data,
    ....
};
return View(model);

and the view is simply

@model TableVM
....
<table>
    <thead> .... </thead>
    <tbody>
        @foreach (var row in Model.Rows)
        {
            <tr>
                <td>@row.Tahun<td>
                <td>@row.Sementara<td>
                <td>@row.Tetap<td>
            </tr>
        }
    </tbody>
</table>

Note that I omitted the table headings because its not clear what your trying to do with your first image, but since the rows contain 3 columns, then you heading should also contain 3 columns.


问:
Left Outer Join returns duplicate records - Oracle
Scenario :

Join Table ORDER with Table COST
where COST has multiple rows for a single reference from Table ORDER

Desired outcome:

Return single row per Order with its associated costs.

```<code>ID NAME PRICE GST
1  Book 100   10
2  CD   50    5
</code>```

Ex:

Table ORDER

```<code>ID   NAME  COST
1    Book  110
2    CD    55
</code>```

Table COST

```<code>ID ORDER_ID COST_TYPE VALUE
1   1   PRICE      100
2   1   GST        10
3   2   PRICE      50
4   2   GST        5
</code>```

LEFT OUTER JOIN returns multiple rows when below condition is used

```<code>SELECT * from ORDER
LEFT OUTER JOIN COST
ON ORDER.ID = COST.ORDER_ID
</code>```

答:
```<code>select o.id, o.name, c.price, c.gst
from   order o left outer join
       ( select   order_id,
                  sum(case when cost_type = 'PRICE' then value end) as price,
                  sum(case when cost_type = 'GST'   then value end) as gst
         from     cost
         group by order_id
       ) c
       on o.id = c.order_id
;
</code>```

Body:
Scenario :

Join Table ORDER with Table COST
where COST has multiple rows for a single reference from Table ORDER

Desired outcome:

Return single row per Order with its associated costs.

ID NAME PRICE GST
1  Book 100   10
2  CD   50    5

Ex:

Table ORDER

ID   NAME  COST
1    Book  110
2    CD    55

Table COST

ID ORDER_ID COST_TYPE VALUE
1   1   PRICE      100
2   1   GST        10
3   2   PRICE      50
4   2   GST        5

LEFT OUTER JOIN returns multiple rows when below condition is used

SELECT * from ORDER
LEFT OUTER JOIN COST
ON ORDER.ID = COST.ORDER_ID


问:
Suppress JInput Warnings
My JInput code works fine, it just prints these warnings to the console every time the program starts. I need to suppress them.

Nov 29, 2017 8:59:55 AM net.java.games.input.DefaultControllerEnvironment getControllers
WARNING: Found unknown Windows version: Windows 10
Nov 29, 2017 8:59:55 AM net.java.games.input.DefaultControllerEnvironment getControllers
WARNING: Attempting to use default windows plug-in.

EDIT: I found a way to do it, but it's a bit of a hack: System.err.close(); Is there a way for me to temporarily disable System.err ?

答:
The solution is to use System.setErr():

```<code>    PrintStream error=System.err;
    System.setErr(new PrintStream(new OutputStream(){
        public void write(int a){}
    }));
    controllers=ControllerEnvironment.getDefaultEnvironment().getControllers();
    System.setErr(error);
</code>```

Title: Suppress JInput Warnings

Body:
The solution is to use System.setErr():

    PrintStream error=System.err;
    System.setErr(new PrintStream(new OutputStream(){
        public void write(int a){}
    }));
    controllers=ControllerEnvironment.getDefaultEnvironment().getControllers();
    System.setErr(error);


答:
This is what you have to do

```<code>myColCI("parity")
</code>```

This should give you the answer.

I don't think your code is wrong. You are trying to subset a column of a data frame using the column name. In R, when you do this, you have to pass the name as a string. eg

```<code>dataframe[,"column_name"]
</code>```

For your function, if you want to have both the confidence intervals and summary output, you would have to modify a little bit. Just like this:

```<code>myColCI<-function(colName){
  predictorvariable <- glm(death180 ~ nepalData[,colName],
  data=nepalData, family="binomial")
  return(list(summary(predictorvariable),confint(predictorvariable)))
}
</code>```

Title: How to write function in R that does glm for a data frame?

Body:
I have:

myColCI<-function(colName){
  predictorvariable <- glm(death180 ~ nepalData[,colName], data=nepalData, family="binomial")
  summary(predictorvariable)
  confint(predictorvariable)
}

One of the names of the column is parity so when after making my function, when I put myColCI(parity), it says the

object "parity" is not found

Can anyone give me a pointer to what's wrong with my code.

Body:
This is what you have to do

myColCI("parity")

This should give you the answer.

I don't think your code is wrong. You are trying to subset a column of a data frame using the column name. In R, when you do this, you have to pass the name as a string. eg

dataframe[,"column_name"]

For your function, if you want to have both the confidence intervals and summary output, you would have to modify a little bit. Just like this:

myColCI<-function(colName){
  predictorvariable <- glm(death180 ~ nepalData[,colName],
  data=nepalData, family="binomial")
  return(list(summary(predictorvariable),confint(predictorvariable)))
}


问:
c++ size of a struct with a function
The result says 12.

Where is the function foobar stored in the memory?

```<code>#include <iostream>
using namespace std;
struct ABC_ {
    int a;
    int b;
    int c;
    int foobar(int a) {
        return a;
    }
};
int main() {
    ABC_ ABC;
    cout << sizeof ABC;
    return 0;
}
</code>```

答:
Adding to the existing answer:

Also interesting to note is that classes with virtual methods are 8 bytes larger (or however many bytes a pointer on your system has). This is a pointer to a table with addresses for the virtual methods. This is how the program knows at runtime which version of the virtual method to call.

Title: c++ size of a struct with a function

Body:
The result says 12.

Where is the function foobar stored in the memory?

#include <iostream>
using namespace std;
struct ABC_ {
    int a;
    int b;
    int c;
    int foobar(int a) {
        return a;
    }
};
int main() {
    ABC_ ABC;
    cout << sizeof ABC;
    return 0;
}


问:
How do I simulate flip of biased coin?
In unbiased coin flip H or T occurs 50% of times.

But I want to simulate coin which gives H  with probability 'p' and T with probability '(1-p)'.

something like this:

```<code>def flip(p):
   '''this function return H with probability p'''
   # do something
   return result

>> [flip(0.8) for i in xrange(10)]
[H,H,T,H,H,H,T,H,H,H]
</code>```

答:
random.random() returns a uniformly distributed pseudo-random floating point number in the range [0, 1). This number is less than a given number p in the range [0,1) with probability p. Thus:

```<code>def flip(p):
    return 'H' if random.random() < p else 'T'
</code>```

Some experiments:

```<code>>>> N = 100
>>> flips = [flip(0.2) for i in xrange(N)]
>>> float(flips.count('H'))/N
0.17999999999999999  # Approximately 20% of the coins are heads

>>> N = 10000
>>> flips = [flip(0.2) for i in xrange(N)]
>>> float(flips.count('H'))/N
0.20549999999999999  # Better approximation
</code>```

OwnerDisplayName: david makcenzie

Title: How do I simulate flip of biased coin?

Body:
In unbiased coin flip H or T occurs 50% of times.

But I want to simulate coin which gives H  with probability 'p' and T with probability '(1-p)'.

something like this:

def flip(p):
   '''this function return H with probability p'''
   # do something
   return result

>> [flip(0.8) for i in xrange(10)]
[H,H,T,H,H,H,T,H,H,H]

LastEditorDisplayName: Mitch Wheat

Body:
random.random() returns a uniformly distributed pseudo-random floating point number in the range [0, 1). This number is less than a given number p in the range [0,1) with probability p. Thus:

def flip(p):
    return 'H' if random.random() < p else 'T'

Some experiments:

>>> N = 100
>>> flips = [flip(0.2) for i in xrange(N)]
>>> float(flips.count('H'))/N
0.17999999999999999  # Approximately 20% of the coins are heads

>>> N = 10000
>>> flips = [flip(0.2) for i in xrange(N)]
>>> float(flips.count('H'))/N
0.20549999999999999  # Better approximation

OwnerDisplayName: Federico Ramponi

LastEditorDisplayName: Federico Ramponi


问:
How to change default message validation on bootstrap
how to change message default upload file on bootstrap from "please a select file" to "please upload document" ?</p>

```<code><div class="form-group">
    <div class="col-sm-10">
        <label for="file" class="col-sm-2 control-label">Unggah Dokumen</label>
                <div class="col-sm-6">
                    <input type="file" name="file" class="form-control" required="">
                </div>
    </div>
</div>
</code>```

答:
You can do something like this:

```<code><input name="myfile" class="form-control" type="file"  required=""
    oninvalid="this.setCustomValidity('Please upload document')"
    oninput="setCustomValidity('')"/>
</code>```

more information about other options
https://www.html5rocks.com/en/tutorials/forms/constraintvalidation/

Body:
how to change message default upload file on bootstrap from "please a select file" to "please upload document" ?

        Unggah Dokumen

                    <input type="file" name="file" class="form-control" required="">

Body:
You can do something like this:

<input name="myfile" class="form-control" type="file"  required=""
    oninvalid="this.setCustomValidity('Please upload document')"
    oninput="setCustomValidity('')"/>

more information about other options
https://www.html5rocks.com/en/tutorials/forms/constraintvalidation/


问:
Advice on creating a local instance of Azure Website
I have, I admit, done things the wrong way round and created an Umbraco installation on Azure, developed multiple websites on that installation and only just decided I want a local instance for further development purposes.

Given that that's where I am, does anyone have any advice for how to go about achieving this? I have tried installing Visual Studio Community 2017 and MS SQL Server 2017 Developer and while I can connect to Azure with Visual Studio I don't seem to be able to work out how to view the installation, much less copy it down to my PC (something which I my searches seem to suggest isn't possible with Visual Studio).

答:
I think you will need to copy down the site via FTP and the database using SQL Server Management Tools (assuming you are using SQL Server and not SQL CE).

You can get the FTP connection information from the Azure portal.  The web root is in /site/wwwroot.  Copy it down locally and you will be able to open it in Visual Studio as a Web Site.   For the database, you can connect to the Azure SQL database with SQL Server Management Tools  (you should have the connection info from when you created the database) and then right click on the database, select "Tasks" > "Export Data-tier application..." which will allow you to save a 'bacpac' file your local machine.  You can then connect to your local SQL Server instance, and then right click on the "Databases" node in the Object Explorer and select "Import Data-tier application..."   Once the database is imported, you may need to create/update a SQL Server user and grant it access to the database you just imported. For local development I just set the user to be owner of the the db.   Back in Visual Studio, you should update the "umbracoDbDSN" connection string to use the new local database.  At this point you should be able to run the website locally.


问:
initialize class with same type directly or through constructor
I have this code:

```<code>#include <iostream>
template <int mult>
struct A {
    int v;
    A (int p) {
        v = p * mult;
    }
};

int main (void) {
    A<4> a (2); // initialize v = 2 * 4
    A<4> b = {2}; // initialize v to 2
    std::cout << a.v << " " << b.v << std::endl;
}
</code>```

I want to see "8 2". What I get is "8 8".

I'd like a way to initialize v either through constructor or through some other method to avoid constructor. I've researched initializer_list or aggregate initialization but I haven't found a solution. The only hack was to create a new constructor with a dummy extra parameter.

Any better ways?

答:
You could keep a private constructor and use static methods that treat their arguments differently:</p>

```<code>template <int mult>
class A {
    int v;
    A (int p) {
        v = p;
    }
public:
    static A<mult> constructor1(int p) {
        return A<mult>(p);
    }
    static A<mult> constructor2(int p) {
        return A<mult>(p * mult);
    }
};
</code>```

Body:
I have this code:

#include <iostream>
template <int mult>
struct A {
    int v;
    A (int p) {
        v = p * mult;
    }
};

int main (void) {
    A<4> a (2); // initialize v = 2 * 4
    A<4> b = {2}; // initialize v to 2
    std::cout << a.v << " " << b.v << std::endl;
}

I want to see "8 2". What I get is "8 8".

I'd like a way to initialize v either through constructor or through some other method to avoid constructor. I've researched initializer_list or aggregate initialization but I haven't found a solution. The only hack was to create a new constructor with a dummy extra parameter.

Any better ways?

Body:
You could keep a private constructor and use static methods that treat their arguments differently:

template <int mult>
class A {
    int v;
    A (int p) {
        v = p;
    }
public:
    static A<mult> constructor1(int p) {
        return A<mult>(p);
    }
    static A<mult> constructor2(int p) {
        return A<mult>(p * mult);
    }
};


问:
How to improve simple but inefficient parent/child relationship query
I have a simple table as described below, where there's a possible parent/child relationship. This is actually a very large table, but this is an fair representation.  There are no "grandchildren" relationships.

I need to transform this into a slightly different table which is filtered on some input value.

```<code>    declare @pc table ( myId char(1) not null, parentId char(1)  );

    insert into @pc (myId, parentId) values ('A', null)
    insert into @pc (myId, parentId) values ('B', 'A')
    insert into @pc (myId, parentId) values ('C', 'A')
    insert into @pc (myId, parentId) values ('D', null)
    insert into @pc (myId, parentId) values ('E', null)
    insert into @pc (myId, parentId) values ('F', 'E')
    insert into @pc (myId, parentId) values ('G', null)
    insert into @pc (myId, parentId) values ('H', 'G')
    insert into @pc (myId, parentId) values ('I', 'G')
    insert into @pc (myId, parentId) values ('J', 'G')
    insert into @pc (myId, parentId) values ('K', null)

    -- This is the results I need
    declare @target table ( myId char(1) not null, parentId char(1), hasFamily bit );
</code>```

Given input of "A", then I need three rows like this:

```<code>    A  NULL 1
    B  A    1
    C  A    1
</code>```

In other words, I need everything that belongs to the "family group" A.

Given "B" I need the same output, everything in B's family group (which happens to be A's):

```<code>    A  NULL 1
    B  A    1
    C  A    1
</code>```

Given "D" I need just the one line since no-one is in D's family:

```<code>    D NULL  0
</code>```

Given null, I need the entire table data set but with the proper rows marked as "having family" or not.

Here's my attempt which is technically correct, but it's not efficient at all taking 3 passes at the data to do it:

```<code>    declare @testcase char(1) = 'B';

    -- The inefficient method
    INSERT INTO @target( myId,parentId )
          SELECT pc.myId, pc.parentId
          FROM @pc pc
          WHERE(pc.myId = ISNULL(@testcase, pc.myId))
              OR (pc.parentId =@testcase);

    INSERT INTO @target( myId,parentId )
          SELECT pc.myId, pc.parentId
          FROM @pc pc
          WHERE pc.myId IN ( SELECT parentId FROM @target )
               AND pc.myId NOT IN  ( SELECT myId FROM @target );

    update t
        set t.hasFamily = 1
        from @target t
        left outer join @target t2
        on t.myId = t2.parentId
        where t.parentId is not null or t2.myId is not null;
</code>```

Can you see a better way of looking at this problem?

答:
A window function to count children, made available on every row, simplifies the wanted queries. How you chose to deploy it is u to you. You might choose to use persisted computed columns for example, or triggers. If scale and performance are issues then you would need to consider the indexing and inspect execution plans.

Perhaps I don't see the complexity from the small model you have presented here hence my suggestions may be too simplistc.

Demo at SQL Fiddle

```<code>create table Table1 ( myId char(1) not null, parentId char(1)  );

insert into Table1 (myId, parentId) values ('A', null);
insert into Table1 (myId, parentId) values ('B', 'A');
insert into Table1 (myId, parentId) values ('C', 'A');
insert into Table1 (myId, parentId) values ('D', null);
insert into Table1 (myId, parentId) values ('E', null);
insert into Table1 (myId, parentId) values ('F', 'E');
insert into Table1 (myId, parentId) values ('G', null);
insert into Table1 (myId, parentId) values ('H', 'G');
insert into Table1 (myId, parentId) values ('I', 'G');
insert into Table1 (myId, parentId) values ('J', 'G');
insert into Table1 (myId, parentId) values ('K', null);

create view too_simplistic as
select
       myId
     , parentId
     , coalesce(parentId, myId) parent_flat
     , case when count(*) over(partition by coalesce(parentId, myId))-1 = 0
                 then 0
                 else 1
       end as hasFamily
    from table1
;
</code>```

Query 1:

```<code>declare @want char(1) = 'A'

select myId, parentId, hasFamily
from too_simplistic
where parent_flat = (select parent_flat from too_simplistic where MyId = @want)
or MyId = @want
</code>```

Results:

```<code>| myId | parentId | hasFamily |
|------|----------|-----------|
|    A |   (null) |         1 |
|    B |        A |         1 |
|    C |        A |         1 |
</code>```

Query 2:

```<code>declare @want char(1) = 'B'

select myId, parentId, hasFamily
from too_simplistic
where parent_flat = (select parent_flat from too_simplistic where MyId = @want)
or MyId = @want
</code>```

Results:

```<code>| myId | parentId | hasFamily |
|------|----------|-----------|
|    A |   (null) |         1 |
|    B |        A |         1 |
|    C |        A |         1 |
</code>```

Query 3:

```<code>declare @want char(1) = 'D'

select myId, parentId, hasFamily
from too_simplistic
where parent_flat = (select parent_flat from too_simplistic where MyId = @want)
or MyId = @want
</code>```

Results:

```<code>| myId | parentId | hasFamily |
|------|----------|-----------|
|    D |   (null) |         0 |
</code>```

Query 4:

```<code>select *
from too_simplistic
</code>```

Results:

```<code>| myId | parentId | parent_flat | hasFamily |
|------|----------|-------------|-----------|
|    A |   (null) |           A |         1 |
|    B |        A |           A |         1 |
|    C |        A |           A |         1 |
|    D |   (null) |           D |         0 |
|    E |   (null) |           E |         1 |
|    F |        E |           E |         1 |
|    G |   (null) |           G |         1 |
|    H |        G |           G |         1 |
|    I |        G |           G |         1 |
|    J |        G |           G |         1 |
|    K |   (null) |           K |         0 |

select d.*
     , case when children = 0 then 0 else 1 end as hasFamily
from (
    select *
         , count(*) over(partition by coalesce(parentId, myId))-1 children
    from @pc
    ) d
;
</code>```

Body:
I have a simple table as described below, where there's a possible parent/child relationship. This is actually a very large table, but this is an fair representation.  There are no "grandchildren" relationships.

I need to transform this into a slightly different table which is filtered on some input value.

    declare @pc table ( myId char(1) not null, parentId char(1)  );

    insert into @pc (myId, parentId) values ('A', null)
    insert into @pc (myId, parentId) values ('B', 'A')
    insert into @pc (myId, parentId) values ('C', 'A')
    insert into @pc (myId, parentId) values ('D', null)
    insert into @pc (myId, parentId) values ('E', null)
    insert into @pc (myId, parentId) values ('F', 'E')
    insert into @pc (myId, parentId) values ('G', null)
    insert into @pc (myId, parentId) values ('H', 'G')
    insert into @pc (myId, parentId) values ('I', 'G')
    insert into @pc (myId, parentId) values ('J', 'G')
    insert into @pc (myId, parentId) values ('K', null)

    -- This is the results I need
    declare @target table ( myId char(1) not null, parentId char(1), hasFamily bit );

Given input of "A", then I need three rows like this:

    A  NULL 1
    B  A    1
    C  A    1

In other words, I need everything that belongs to the "family group" A.

Given "B" I need the same output, everything in B's family group (which happens to be A's):

    A  NULL 1
    B  A    1
    C  A    1

Given "D" I need just the one line since no-one is in D's family:

    D NULL  0

Given null, I need the entire table data set but with the proper rows marked as "having family" or not.

Here's my attempt which is technically correct, but it's not efficient at all taking 3 passes at the data to do it:

    declare @testcase char(1) = 'B';

    -- The inefficient method
    INSERT INTO @target( myId,parentId )
          SELECT pc.myId, pc.parentId
          FROM @pc pc
          WHERE(pc.myId = ISNULL(@testcase, pc.myId))
              OR (pc.parentId =@testcase);

    INSERT INTO @target( myId,parentId )
          SELECT pc.myId, pc.parentId
          FROM @pc pc
          WHERE pc.myId IN ( SELECT parentId FROM @target )
               AND pc.myId NOT IN  ( SELECT myId FROM @target );

    update t
        set t.hasFamily = 1
        from @target t
        left outer join @target t2
        on t.myId = t2.parentId
        where t.parentId is not null or t2.myId is not null;

Can you see a better way of looking at this problem?

Body:
A window function to count children, made available on every row, simplifies the wanted queries. How you chose to deploy it is u to you. You might choose to use persisted computed columns for example, or triggers. If scale and performance are issues then you would need to consider the indexing and inspect execution plans.

Perhaps I don't see the complexity from the small model you have presented here hence my suggestions may be too simplistc.

Demo at SQL Fiddle

create table Table1 ( myId char(1) not null, parentId char(1)  );

insert into Table1 (myId, parentId) values ('A', null);
insert into Table1 (myId, parentId) values ('B', 'A');
insert into Table1 (myId, parentId) values ('C', 'A');
insert into Table1 (myId, parentId) values ('D', null);
insert into Table1 (myId, parentId) values ('E', null);
insert into Table1 (myId, parentId) values ('F', 'E');
insert into Table1 (myId, parentId) values ('G', null);
insert into Table1 (myId, parentId) values ('H', 'G');
insert into Table1 (myId, parentId) values ('I', 'G');
insert into Table1 (myId, parentId) values ('J', 'G');
insert into Table1 (myId, parentId) values ('K', null);

create view too_simplistic as
select
       myId
     , parentId
     , coalesce(parentId, myId) parent_flat
     , case when count(*) over(partition by coalesce(parentId, myId))-1 = 0
                 then 0
                 else 1
       end as hasFamily
    from table1
;

Query 1:

declare @want char(1) = 'A'

select myId, parentId, hasFamily
from too_simplistic
where parent_flat = (select parent_flat from too_simplistic where MyId = @want)
or MyId = @want

Results:

| myId | parentId | hasFamily |
|------|----------|-----------|
|    A |   (null) |         1 |
|    B |        A |         1 |
|    C |        A |         1 |

Query 2:

declare @want char(1) = 'B'

select myId, parentId, hasFamily
from too_simplistic
where parent_flat = (select parent_flat from too_simplistic where MyId = @want)
or MyId = @want

Results:

| myId | parentId | hasFamily |
|------|----------|-----------|
|    A |   (null) |         1 |
|    B |        A |         1 |
|    C |        A |         1 |

Query 3:

declare @want char(1) = 'D'

select myId, parentId, hasFamily
from too_simplistic
where parent_flat = (select parent_flat from too_simplistic where MyId = @want)
or MyId = @want

Results:

| myId | parentId | hasFamily |
|------|----------|-----------|
|    D |   (null) |         0 |

Query 4:

select *
from too_simplistic

Results:

| myId | parentId | parent_flat | hasFamily |
|------|----------|-------------|-----------|
|    A |   (null) |           A |         1 |
|    B |        A |           A |         1 |
|    C |        A |           A |         1 |
|    D |   (null) |           D |         0 |
|    E |   (null) |           E |         1 |
|    F |        E |           E |         1 |
|    G |   (null) |           G |         1 |
|    H |        G |           G |         1 |
|    I |        G |           G |         1 |
|    J |        G |           G |         1 |
|    K |   (null) |           K |         0 |

select d.*
     , case when children = 0 then 0 else 1 end as hasFamily
from (
    select *
         , count(*) over(partition by coalesce(parentId, myId))-1 children
    from @pc
    ) d
;


问:
How can I start android application info screen programmatically?
Is it possible to start the "application info" screen (that is, Menu → Settings → Applications → Manage Applications → select any application) from another app?

答:
In 2.2 and below, there is no public APIs you can access. But you can still start the InstalledAppDetails activity just as the ManageApplications does. see here

```<code> // utility method used to start sub activity
 private void startApplicationDetailsActivity() {
     // Create intent to start new activity
     Intent intent = new Intent(Intent.ACTION_VIEW);
     intent.setClass(this, InstalledAppDetails.class);
     intent.putExtra(APP_PKG_NAME, mCurrentPkgName);
     // start new activity to display extended information
     startActivityForResult(intent, INSTALLED_APP_DETAILS);
 }
</code>```

Conclusion: you can start the "application info" screen like this i wrote:

```<code>private static final String SCHEME = "package";

private static final String APP_PKG_NAME_21 = "com.android.settings.ApplicationPkgName";

private static final String APP_PKG_NAME_22 = "pkg";

private static final String APP_DETAILS_PACKAGE_NAME = "com.android.settings";

private static final String APP_DETAILS_CLASS_NAME = "com.android.settings.InstalledAppDetails";

public static void showInstalledAppDetails(Context context, String packageName) {
    Intent intent = new Intent();
    final int apiLevel = Build.VERSION.SDK_INT;
    if (apiLevel >= 9) { // above 2.3
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts(SCHEME, packageName, null);
        intent.setData(uri);
    } else { // below 2.3
        final String appPkgName = (apiLevel == 8 ? APP_PKG_NAME_22
                : APP_PKG_NAME_21);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setClassName(APP_DETAILS_PACKAGE_NAME,
                APP_DETAILS_CLASS_NAME);
        intent.putExtra(appPkgName, packageName);
    }
    context.startActivity(intent);
}
</code>```

Body:
In 2.2 and below, there is no public APIs you can access. But you can still start the InstalledAppDetails activity just as the ManageApplications does. see here

 // utility method used to start sub activity
 private void startApplicationDetailsActivity() {
     // Create intent to start new activity
     Intent intent = new Intent(Intent.ACTION_VIEW);
     intent.setClass(this, InstalledAppDetails.class);
     intent.putExtra(APP_PKG_NAME, mCurrentPkgName);
     // start new activity to display extended information
     startActivityForResult(intent, INSTALLED_APP_DETAILS);
 }

Conclusion: you can start the "application info" screen like this i wrote:

private static final String SCHEME = "package";

private static final String APP_PKG_NAME_21 = "com.android.settings.ApplicationPkgName";

private static final String APP_PKG_NAME_22 = "pkg";

private static final String APP_DETAILS_PACKAGE_NAME = "com.android.settings";

private static final String APP_DETAILS_CLASS_NAME = "com.android.settings.InstalledAppDetails";

public static void showInstalledAppDetails(Context context, String packageName) {
    Intent intent = new Intent();
    final int apiLevel = Build.VERSION.SDK_INT;
    if (apiLevel >= 9) { // above 2.3
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts(SCHEME, packageName, null);
        intent.setData(uri);
    } else { // below 2.3
        final String appPkgName = (apiLevel == 8 ? APP_PKG_NAME_22
                : APP_PKG_NAME_21);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setClassName(APP_DETAILS_PACKAGE_NAME,
                APP_DETAILS_CLASS_NAME);
        intent.putExtra(appPkgName, packageName);
    }
    context.startActivity(intent);
}


问:
QtCreator returns error "Cannot change to working directory"
I'm trying to running a simple HelloWorld program with Qt Creator
Code:

```<code>#include <iostream>

using namespace std;

int main()
{
  cout << "Hello World!" << endl;
  return 0;
}
</code>```

When running occurs the error

```<code>Cannot change to working directory '/home/myusername/build-myproject-Desktop-Debug': file or directory not found
</code>```

Many tutorials in the internet tell me to disable "Run in terminal", but I need this for my project.
My working directory is /home/myusername/build-myproject-Desktop-Debug

Any help?

答:
You can install Terminator terminal (sudo apt-get install terminator) and use it as Qt Creator terminal:

Tools->Options->Enviroment->System->Terminal->"/usr/bin/terminator -x"

Body:
I'm trying to running a simple HelloWorld program with Qt Creator
Code:

#include <iostream>

using namespace std;

int main()
{
  cout << "Hello World!" << endl;
  return 0;
}

When running occurs the error

Cannot change to working directory '/home/myusername/build-myproject-Desktop-Debug': file or directory not found

Many tutorials in the internet tell me to disable "Run in terminal", but I need this for my project.
My working directory is /home/myusername/build-myproject-Desktop-Debug

Any help?


问:
Featherjs and Angular 2 error
im trying to use FeathersJS with Angular 2 but i can't get it to work, im following the guide here: Angular2 Guide with Feathers
My problem is that i create the services as it says like this:

```<code>import * as feathers from 'feathers/client';
import * as hooks from 'feathers-hooks';
import * as rest from 'feathers-rest/client';
import { Injectable } from '@angular/core';
const superagent = require('superagent');

const HOST = 'https://myurl.com/';

@Injectable()
export class RestService {
  private _app: any;
  constructor() {
    this._app = feathers() // Initialize feathers
      .configure(rest(HOST).superagent(superagent)) // Fire up rest
      .configure(hooks()); // Configure feathers-hooks
  }
}
</code>```

And i try to use it like this

```<code>import { RestService } from './rest.service';
import { Injectable } from '@angular/core';

@Injectable()
export class UsersService {

  private _rest;

  constructor( private _restService: RestService ) {
    this._rest = _restService.getService('users');
  }

}
</code>```

And i get the error: "Property 'getService' does not exist on type 'RestService'"

I think i have to instantiate the service but i can get it to do it, any help is much appreciated.

Regards,

答:
I use with the last version 3.0.1, and install with those commands:

```<code>npm install @feathersjs/feathers @feathersjs/socketio-client --save
npm install @feathersjs/authentication-client --save
npm install socket.io-client --save
</code>```

In Angular 4, my service is:

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

import feathers from '@feathersjs/feathers';
import socketio from '@feathersjs/socketio-client';
import authencl from '@feathersjs/authentication-client';

import io from 'socket.io-client';

@Injectable()
export class AppService {

  private urlServer = 'http://localhost:3030';
  private socket = io(this.urlServer, {
    transports: ['websocket'],
    forceNew: true
  });

  app: any;

  constructor() {
    this.app = feathers()
        .configure(socketio(this.socket))
        .configure(authencl());
  }
}
</code>```

Title: Featherjs and Angular 2 error

Body:
im trying to use FeathersJS with Angular 2 but i can't get it to work, im following the guide here: Angular2 Guide with Feathers
My problem is that i create the services as it says like this:

import * as feathers from 'feathers/client';
import * as hooks from 'feathers-hooks';
import * as rest from 'feathers-rest/client';
import { Injectable } from '@angular/core';
const superagent = require('superagent');

const HOST = 'https://myurl.com/';

@Injectable()
export class RestService {
  private _app: any;
  constructor() {
    this._app = feathers() // Initialize feathers
      .configure(rest(HOST).superagent(superagent)) // Fire up rest
      .configure(hooks()); // Configure feathers-hooks
  }
}

And i try to use it like this

import { RestService } from './rest.service';
import { Injectable } from '@angular/core';

@Injectable()
export class UsersService {

  private _rest;

  constructor( private _restService: RestService ) {
    this._rest = _restService.getService('users');
  }

}

And i get the error: "Property 'getService' does not exist on type 'RestService'"

I think i have to instantiate the service but i can get it to do it, any help is much appreciated.

Regards,

Body:
I use with the last version 3.0.1, and install with those commands:

npm install @feathersjs/feathers @feathersjs/socketio-client --save
npm install @feathersjs/authentication-client --save
npm install socket.io-client --save

In Angular 4, my service is:

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

import feathers from '@feathersjs/feathers';
import socketio from '@feathersjs/socketio-client';
import authencl from '@feathersjs/authentication-client';

import io from 'socket.io-client';

@Injectable()
export class AppService {

  private urlServer = 'http://localhost:3030';
  private socket = io(this.urlServer, {
    transports: ['websocket'],
    forceNew: true
  });

  app: any;

  constructor() {
    this.app = feathers()
        .configure(socketio(this.socket))
        .configure(authencl());
  }
}


问:
Autofac SingleInstance WebApi Performance
We've improved the performance of our API's adding services without state to .SingleInstance() , but I've a question, regarding the demo code attached,

The IBusAppService that we are using on the controller is set to SingleInstance(), but inside the BusAppService, we are using more Interfaces, for example ( IBusRepository or IBusDomainService )

So the question is, in order to increase the performnace, should we set all interfaces to SingleInstance() inside the IBusAppService or the performance is the same because they are inside a SingleInstance??

I'll attach here some code with the workflow :

The ApiController:

```<code>    public class BusApiController : ApiController
    {
        private readonly IBusAppService _iBusAppService;
        private readonly IBusMapper _iBusMapper;
        public BusApiController(IBusAppService iBusAppService,
                                IBusMapper iBusMapper)
        {
            _iBusAppService = iBusAppService;
            _iBusMapper = iBusMapper;
        }

        [HttpGet]
        public BusResponse Get(long id)
        {
            var bus = _iBusAppService.Get(id);

            var busResponse = _iBusMapper.Convert(bus);
            return busResponse;
        }
    }

    public class BusResponse {
       public long Id { get; set; }
    }

    public interface IBusMapper
    {
        BusResponse Convert(Bus bus);
    }

    public class BusMapper : IBusMapper
    {
        public BusResponse Convert(Bus bus)
        {
            if (bus == null) return null;

            var result = new BusResponse{Id = bus.Id};
            return result;
        }
    }

    builder.RegisterType<BusAppService>().As<IBusAppService>().SingleInstance();
    builder.RegisterType<BusMapper>().As<IBusMapper>().SingleInstance();
</code>```

The ApplicationService

```<code>public interface IBusAppService
{
    Bus Get(long id);
}

public class BusAppService : IBusAppService
{
    private readonly IBusRepository _iBusRepository;
    private readonly IBusDomainService _iBusDomainService;
    public BusAppService(IBusRepository iBusRepository, IBusDomainService iBusDomainService )
    {
        _iBusRepository = iBusRepository;
        _iBusDomainService = iBusDomainService;
    }
    public Bus Get(long id)
    {
        var bus = this._iBusRepository.Get(id);
        var busTax = this._iBusDomainService.CalculateTax(bus);

        var result = bus;
        return result;
    }
}
</code>```

答: Anything consumed by a single instance service will end up being single instance due to captive dependencies. You could change them to be single instance, too, but it won't necessarily change the performance related to instantiation cost that you see now.</p>

Body:
We've improved the performance of our API's adding services without state to .SingleInstance() , but I've a question, regarding the demo code attached,

The IBusAppService that we are using on the controller is set to SingleInstance(), but inside the BusAppService, we are using more Interfaces, for example ( IBusRepository or IBusDomainService )

So the question is, in order to increase the performnace, should we set all interfaces to SingleInstance() inside the IBusAppService or the performance is the same because they are inside a SingleInstance??

I'll attach here some code with the workflow :

The ApiController:

    public class BusApiController : ApiController
    {
        private readonly IBusAppService _iBusAppService;
        private readonly IBusMapper _iBusMapper;
        public BusApiController(IBusAppService iBusAppService,
                                IBusMapper iBusMapper)
        {
            _iBusAppService = iBusAppService;
            _iBusMapper = iBusMapper;
        }

        [HttpGet]
        public BusResponse Get(long id)
        {
            var bus = _iBusAppService.Get(id);

            var busResponse = _iBusMapper.Convert(bus);
            return busResponse;
        }
    }

    public class BusResponse {
       public long Id { get; set; }
    }

    public interface IBusMapper
    {
        BusResponse Convert(Bus bus);
    }

    public class BusMapper : IBusMapper
    {
        public BusResponse Convert(Bus bus)
        {
            if (bus == null) return null;

            var result = new BusResponse{Id = bus.Id};
            return result;
        }
    }

    builder.RegisterType<BusAppService>().As<IBusAppService>().SingleInstance();
    builder.RegisterType<BusMapper>().As<IBusMapper>().SingleInstance();

The ApplicationService

public interface IBusAppService
{
    Bus Get(long id);
}

public class BusAppService : IBusAppService
{
    private readonly IBusRepository _iBusRepository;
    private readonly IBusDomainService _iBusDomainService;
    public BusAppService(IBusRepository iBusRepository, IBusDomainService iBusDomainService )
    {
        _iBusRepository = iBusRepository;
        _iBusDomainService = iBusDomainService;
    }
    public Bus Get(long id)
    {
        var bus = this._iBusRepository.Get(id);
        var busTax = this._iBusDomainService.CalculateTax(bus);

        var result = bus;
        return result;
    }
}


问:
Firebase phone auth sends unreadable verification SMS for chinese and japanese language
We are using the library FirebaseUI/Phone. And our ios app is supporting for multiple languages.

The auth UIs are correctly localized but sms message are sometimes unreadable when the app language is Chinese or Japanese. English works fine.

Does someone has a solution for it. (It seems like a bug of some particular sms sending server. )

sms is readable from the number in the first picture and unreadable from the second

We tried to set the languageCode as the document says like
Auth.auth().languageCode = "fr" and auth().useAppLanguage and so on.
No change for japanese and chinese.
As a result we have to set languageCode to en for all languages.

答:
I have tried to reproduce this issue in FirebaseUI for iOS and I wasn't able to. Just to clarify the docs; you should be either set the auth language directly (using Auth.auth().languageCode = "fr") or via the app's current language (using auth().useAppLanguage) but not both.

Please try using Auth.auth().languageCode = "zh-CN" only to set the auth language to Chinese.


问:
First, Second and Third largest number from user provided integer array
In this program, size of array and array elements are taken from user.

This code passes all the cases I have tried but not able to pass, where size of array is 4 and elements are {5,5,5,2}

Here output should be 5 5 5

But I am getting 2 2 5

I am able to figure out the problem is in this part.

```<code>else if((max1 == max2 && max2 == max3 && max1 == max3) && x[i] < max2)
                {
                    max2 = x[i];
                    if(max2 < max3)
                    {
                        max3 = max2;
                    }
                }
</code>```

How can I solve this problem using array only. Don't need solution in collections.

```<code>import java.util.*;
    class ThirdLargest
    {
        public static void main(String[] args)
        {
            Scanner sc = new Scanner(System.in);
            System.out.println("Enter size for array: ");
            int size = sc.nextInt();
            int[] x = new int[size];
            for(int i = 0; i < x.length; i++)
            {
                System.out.println("Enter elements for array: ");
                x[i] = sc.nextInt();
            }
            System.out.println("Array is: ");
            for(int i = 0; i < x.length; i++)
            {
                System.out.print(x[i] +"    ");
            }
            System.out.println();
            if (x.length >= 3)
            {
                int max1 = x[0], max2 = x[0], max3 = x[0];
            for (int i = 1; i < x.length; i++)
            {
                    if(x[i] > max1)
                    {
                        max3 = max2;
                        max2 = max1;
                        max1 = x[i];
                    }
                    else if(x[i] > max2)
                    {
                        max3 = max2;
                        max2 = x[i];
                    }
                    else if (x[i] > max3)
                    {
                        max3 = x[i];
                    }
                    else if((max1 == max2 && max2 == max3 && max1 == max3) && x[i] < max2)
                    {
                        max2 = x[i];
                        if(max2 < max3)
                        {
                            max3 = max2;
                        }
                    }
                    else if(max2 == max3 && x[i] < max3)
                        {
                            max3 = x[i];
                        }
                }
            System.out.println("3rd, 2nd and 1st maximum: " + max3 +"   "+max2+"    "+max1);
            }
            else
            {
                System.out.println("Array size is short");
            }
        }
    }
</code>```

答:
```<code>int[] numbers = {5, 5, 5, 2};
Arrays.stream(numbers).sorted().skip(numbers.length - 3).forEach(System.out::println);
</code>```

We make stream out of your array, then we sort it, we skip arrayLength - n elements (n represents how many max numbers you want to print out) and we print each one of the numbers that are left.

Body:
In this program, size of array and array elements are taken from user.

This code passes all the cases I have tried but not able to pass, where size of array is 4 and elements are {5,5,5,2}

Here output should be 5 5 5

But I am getting 2 2 5

I am able to figure out the problem is in this part.

else if((max1 == max2 && max2 == max3 && max1 == max3) && x[i] < max2)
                {
                    max2 = x[i];
                    if(max2 < max3)
                    {
                        max3 = max2;
                    }
                }

How can I solve this problem using array only. Don't need solution in collections.

import java.util.*;
    class ThirdLargest
    {
        public static void main(String[] args)
        {
            Scanner sc = new Scanner(System.in);
            System.out.println("Enter size for array: ");
            int size = sc.nextInt();
            int[] x = new int[size];
            for(int i = 0; i < x.length; i++)
            {
                System.out.println("Enter elements for array: ");
                x[i] = sc.nextInt();
            }
            System.out.println("Array is: ");
            for(int i = 0; i < x.length; i++)
            {
                System.out.print(x[i] +"    ");
            }
            System.out.println();
            if (x.length >= 3)
            {
                int max1 = x[0], max2 = x[0], max3 = x[0];
            for (int i = 1; i < x.length; i++)
            {
                    if(x[i] > max1)
                    {
                        max3 = max2;
                        max2 = max1;
                        max1 = x[i];
                    }
                    else if(x[i] > max2)
                    {
                        max3 = max2;
                        max2 = x[i];
                    }
                    else if (x[i] > max3)
                    {
                        max3 = x[i];
                    }
                    else if((max1 == max2 && max2 == max3 && max1 == max3) && x[i] < max2)
                    {
                        max2 = x[i];
                        if(max2 < max3)
                        {
                            max3 = max2;
                        }
                    }
                    else if(max2 == max3 && x[i] < max3)
                        {
                            max3 = x[i];
                        }
                }
            System.out.println("3rd, 2nd and 1st maximum: " + max3 +"   "+max2+"    "+max1);
            }
            else
            {
                System.out.println("Array size is short");
            }
        }
    }

Body:
int[] numbers = {5, 5, 5, 2};
Arrays.stream(numbers).sorted().skip(numbers.length - 3).forEach(System.out::println);

We make stream out of your array, then we sort it, we skip arrayLength - n elements (n represents how many max numbers you want to print out) and we print each one of the numbers that are left.