text:
Q: Flurl client lifetime in ASP.Net Core 2.1 and IHttpClientFactory Flurl states that using singleton client is recommended pattern:

HttpClient is intended to be instantiated once and re-used throughout the life of an application. Especially in server applications, creating a new HttpClient instance for every request will exhaust the number of sockets available under heavy loads. This will result in SocketException errors.

But since Asp.Net Core 2.1 there are updated rules for HttpClient lifetime in Net Core 2.1.

When you use the HttpClientFactory to request a HttpClient, you do in fact get a new instance each time, which means we don't have to worry about mutating it's state. This HttpClient may (or may not) use an existing HttpClientHandler from the pool and therefore use an existing open connection.

How to modify Flurl to use IHttpClientFactory under hood? Should I create custom Flurl's settings.HttpClientFactory and there create HttpClient through MS IHttpClientFactory?

A: First, it should be noted that MS's new HttpClientFactory is intended to be used in conjunction with ASP.NET Core 2.1 and its built-in DI container. If you're not injecting FlurlClients into controllers or service classes, and are instead using Flurl like this:
await url.GetJsonAsync();

then it's not even relevant. You should not implement Flurl's IHttpClientFactory to use MS's. It doesn't have the proper context to use the DI container and you'll end up resorting to service location, which is an anti-pattern. Those new socket pooling features you want to take advantage of actually live at a lower level:System.Net.Http.SocketsHttpHandler. Flurl uses HttpClientHander as its message handler by default, but luckily that's been rewritten in .NET Core 2.1 to defer all of its work to SocketsHttpHandler by default. In other words, if you're using Flurl in a .NET Core 2.1 app, you're already getting all the new socket management goodies that MS has been working on.
If you are using FlurlClient explicitly in an ASP.NET Core 2.1 app, as sort of a replacement for HttpClient, and would like to inject it into your classes while taking advantage of what MS's HttpClientFactory has to offer, I would suggest setting up HttpClientFactory in ConfigureServices exactly as prescribed by MS, and when you need a FlurlClient instance, use the constructor that takes an HttpClient instance. For example, when using the typed clients pattern, your service class might look like this:
public class MyService
{
    private readonly IFlurlClient _flurlClient;

    public MyService(HttpClient httpClient)
    {
        _flurlClient = new FlurlClient(httpClient);
    }
}


text:
Q: OData EndPoint/DataService Using IEnumerable I am using NHibernate with NHibernate.Linq, and have a bunch of dynamically loading modules each with their own POCO's and Mappings (ClassMap<POCO>).
I have created OData services before, but normally with a datacontext and IQueryable as Properties/Getters.
What I want is to create the service by passing in IEnumerable, into the constructor
IEnumerable<IQueryable>> queryableObjects;
var dataService = new DataService(queryableObjects);

Is this at all possible?

A: It is doable, but it requires some more work. The way to do this is to implement your customer provider. A very nice guide how to do this is here:
https://blogs.msdn.microsoft.com/alexj/2010/01/07/custom-data-service-providers/
There are also nice samples as part of the OData provider toolkit, which can be found on OData SDK - Sample Code.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to check if an Android device can be rebooted programmatically? I am using a Android device having custom ROM and need to reboot that device. I am able to reboot the device from hardware side, but I want to programmatically check if the device can be rebooted.
Is there any way to do that?

A: Check the device is rooted or not.If the device is rooted, then request root permission and you can reboot the device.
Here is how to check root access is available or not.


text:
Q: Spring @MVC how to obtain a List of JavaBeans from request params without wrapping the list inside an object I need to have this controller:
@RequestMapping("/path/to/my/app")
public String process(List<JavaBean> javaBeans){
    // Do something with the list
}

At client I need to manually create the list on user actions, like so
<form action="/path/to/my/app">
    <input name="javaBeans[0].field1"/>
    <input name="javaBeans[0].field2"/>
    <input name="javaBeans[0].field3"/>
    <br/>
    <input name="javaBeans[1].field1"/>
    <input name="javaBeans[2].field2"/>
    <input name="javaBeans[3].field3"/>
    <!-- and so forth -->
</form>

My primary problem is that I receive empty list inside the contoller. I have to wrap it inside another javabean to make the code work. Like following
public class BeanWrapper{
    private List<JavaBean> javaBeans;

    // Getter and setter
}

and in controller
@RequestMapping("/path/to/my/app")
public String process(BeanWrapper wrapper){
    List<JavaBean> list = wrapper.getJavaBeans();
    // Do something with the list
}

This version works but I have to unnecessarily wrap my list around an object. Is there a way around?
Thanks in advance.

A: You can try this:
public String process(@RequestParam("javaBeans[]") List<JavaBean> javaBeans) {

Update:
The syntax using indices (javaBeans[1]) is currently not supported by the Spring default binding. As mentioned in the comments you can get around this limitation by using the @RequestBody annotation.
public String process(@RequestBody List<JavaBean> javaBeans)

This requires a POST request, and either the data to be sent in a different format (e.g. JSON) or implementing your own message converter.


text:
Q: AWS Aurora Serverless spewing 2 particular errors continuously Looking in CloudWatch logs, I see these errors repeated continuously, approximately twice a second:
2019-03-10 00:56:12 2b1be9674700[AWS_OSCAR_ERROR]:Failed to read persisted replica status info. Error code = 11
2019-03-10 00:56:12 2b1be9674700[AWS_OSCAR_ERROR]:Failed to update replication status table (stage 2)

Does anyone know what these are? I've tried Googling the exact and partial errors and was amazed to see that there's nothing out there (well Google, anyway, has never seen them!)
I am concerned because --even if they are nothing to worry about-- they are generating millions of log entries and thus costing me lots in AWS fees.
Thanks in advance.

A: This looks like an aurora internal error message (that explains why google didn't have much to offer when you searched for it). I think the right way ahead is to contact AWS Support.


text:
Q: Wifi signal logger device I am working on indoor gps tracking and for this I need a wifi signal logger which can receive the signals from different smartphone(whose wifi is turned on) an send it to a remote server. I wanted to know, where I can get this kind of hardware, having capability to receive signals from different smartphones and log its signal strength and mac address in a remote server.
Please let me know the details.
Thank you in advance.
Pravin Prasad

A: In simple terms, Wifi clients(smartphones, notebooks etc.) send periodic Probe Request packets to actively seek wifi access points and Wifi APs(routers, gateways etc.) send periodic Beacon packets to advertise the presence of WLAN network.
You can use any wifi capable device like a smartphone or notebook to log the above packets.

*

*Configure your wireless card in monitor mode.

*Use a packet sniffer(for example, wireshark) to capture the traffic on the wireless interface or write your own with libpcap. You may filter on the packet type, source, destination etc.


text:
Q: Wrong principal in request (SSH/ GSSAPI/Kerberos/Debian) I've set up two VMs on an "internal" (in VirtualBox meaning) network, one being a DNS server (dns1.example.com) and the other - a KDC and Kerberos admin server (kdc.example.com). The default and the only realm is EXAMPLE.COM. Both machines use freshly installed Debian Squeeze.
The problem:
I can login via ssh on kdc.example.com from kdc.example.com, but I can't login via ssh from dns1.example.com.
On kdc.example.com, sshd in debug mode says:
debug1: Unspecified GSS failure.  Minor code may provide more information
Wrong principal in request

debug1: Got no client credentials
debug3: mm_request_send entering: type 41
debug3: mm_request_receive entering
debug1: userauth-request for user tom service ssh-connection method gssapi-with-mic
debug1: attempt 2 failures 1
debug2: input_userauth_request: try method gssapi-with-mic
debug1: userauth-request for user tom service ssh-connection method gssapi-with-mic
debug1: attempt 3 failures 1
debug2: input_userauth_request: try method gssapi-with-mic

at which point the client is asked for a password. A tcpdump file processed by Wireshark shows there has been some exchange of crypted packets, but I can't deduct more as they are, well, crypted :). After 2 days of googling I'm stuck and would appreciate any help.
Even more would I appreciate any advice /links/hints on a general sane configuration debugging strategy, when it comes to Kerberos and friends. For example, I'm out of ideas where to look for what's wrong with 'Wrong principal', and what is that principal the server receives instead of the right one. Something tells me the real adventures are yet to come :).
Below are configs and diagnostic outputs. Hope I haven't forgot anything.
kdc:~# cat /etc/krb5kdc/kdc.conf
[kdcdefaults]
    kdc_ports = 750,88

[realms]
    EXAMPLE.COM = {
        database_name = /var/lib/krb5kdc/principal
        admin_keytab = FILE:/etc/krb5kdc/kadm5.keytab
        acl_file = /etc/krb5kdc/kadm5.acl
        key_stash_file = /etc/krb5kdc/stash
        kdc_ports = 750,88
        max_life = 10h 0m 0s
        max_renewable_life = 7d 0h 0m 0s
        master_key_type = des3-hmac-sha1
        supported_enctypes = aes256-cts:normal arcfour-hmac:normal des3-hmac-sha1:normal des-cbc-crc:normal des:normal des:v4 des:norealm des:onlyrealm des:afs3
        default_principal_flags = +preauth
    }

kdc:~# kadmin.local -q 'listprincs'
Authenticating as principal root/admin@EXAMPLE.COM with password.
K/M@EXAMPLE.COM
host/dns1.example.com@EXAMPLE.COM
host/kdc.example.com@EXAMPLE.COM
host/localhost@EXAMPLE.COM
host/www.example.com@EXAMPLE.COM
kadmin/admin@EXAMPLE.COM
kadmin/changepw@EXAMPLE.COM
kadmin/history@EXAMPLE.COM
kadmin/kdc.example.com@EXAMPLE.COM
krbtgt/EXAMPLE.COM@EXAMPLE.COM
root/admin@EXAMPLE.COM
tom@EXAMPLE.COM

kdc:~# cat /etc/ssh/sshd_config |grep '^[^#]'
Port 22
ListenAddress 172.16.3.3
Protocol 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
UsePrivilegeSeparation yes
KeyRegenerationInterval 3600
ServerKeyBits 768
SyslogFacility AUTH
LogLevel INFO
LoginGraceTime 120
PermitRootLogin yes
StrictModes yes
RSAAuthentication yes
PubkeyAuthentication yes
IgnoreRhosts yes
RhostsRSAAuthentication no
HostbasedAuthentication no
PermitEmptyPasswords no
ChallengeResponseAuthentication no
GSSAPIAuthentication yes
GSSAPIKeyExchange yes
GSSAPICleanupCredentials yes
X11Forwarding yes
X11DisplayOffset 10
PrintMotd no
PrintLastLog yes
TCPKeepAlive yes
AcceptEnv LANG LC_*
Subsystem sftp /usr/lib/openssh/sftp-server
UsePAM yes

/etc/krb5.conf is identical on both kdc and dns1.
dns1:~$ cat /etc/krb5.conf
[libdefaults]
    default_realm = EXAMPLE.COM
    dns_lookup_realm = true
    dns_lookup_kdc = true
    forwardable = true
[realms]
    EXAMPLE.COM={
        admin_server = kdc.example.com
    }
[domain_realm]
    example.com = EXAMPLE.COM
    .example.com = EXAMPLE.COM
[logging]
    kdc = FILE:/var/log/krb5kdc.log
    admin_server = FILE:/var/log/kadmin.log
    default = FILE:/var/log/krb5lib.log

The TGT is forwardable. On ssh client:
dns1:~$ klist -f
Ticket cache: FILE:/tmp/krb5cc_1000
Default principal: tom@EXAMPLE.COM

Valid starting     Expires            Service principal
01/03/12 20:00:03  01/04/12 06:00:03  krbtgt/EXAMPLE.COM@EXAMPLE.COM
    renew until 01/04/12 20:00:00, Flags: FRIA
01/03/12 20:00:21  01/04/12 06:00:03  host/kdc.example.com@EXAMPLE.COM
    renew until 01/04/12 20:00:00, Flags: FRAT

Keytab does also seem to be OK:
dns1:~# klist -k
Keytab name: WRFILE:/etc/krb5.keytab
KVNO Principal
---- --------------------------------------------------------------------------
   5 host/dns1.example.com@EXAMPLE.COM
   5 host/dns1.example.com@EXAMPLE.COM
   5 host/dns1.example.com@EXAMPLE.COM
   5 host/dns1.example.com@EXAMPLE.COM

DNS (incl. PTR, TXT, SRV) works as it should.
dns1:~# cat /var/cache/bind/db.example.com
$ORIGIN example.com.
$TTL    86400
@   IN  SOA dns1.example.com. root.example.com. (
            2012010301  ; Serial
             604800     ; Refresh
              86400     ; Retry
            2419200     ; Expire
              86400 )   ; Negative Cache TTL
;
@   IN  NS  dns1.example.com.
dns1    IN  A   172.16.3.2
www IN  A   172.16.3.8
mail    IN  A   172.16.3.9
fed IN  A   172.16.3.100

kdc IN  A   172.16.3.3
;kds    IN  A   172.16.3.4

_kerberos   TXT "EXAMPLE.COM"

krb IN  CNAME   kdc

_kerberos._udp      SRV 0 0 88  kdc
_kerberos-master._udp   SRV 0 0 88  kdc
_kerberos-adm._tcp  SRV 0 0 749 kdc
_kpasswd._udp       SRV 0 0 464 kdc

dns1:~# cat /var/cache/bind/db.3.16.172.in-addr.arpa
$ORIGIN 3.16.172.in-addr.arpa.
$TTL    86400
@   IN  SOA dns1.example.com. root.example.com. (
            2012010102  ; Serial
             604800     ; Refresh
              86400     ; Retry
            2419200     ; Expire
              86400 )   ; Negative Cache TTL
;
@   IN  NS  dns1.example.com.
2   IN  PTR dns1.example.com.
3   IN  PTR kdc.example.com.

8   IN  PTR example.com.
9   IN  PTR mail.example.com.

A: Found this while Googling for exactly the same error on a new server build - pointed me in the right direction :)
In my case, I had incorrect reverse DNS - when I updated this and cleared my caching nameservers' caches, it worked.

A: I have to be more attentive. There was a line left in /etc/hosts resolving 127.0.0.1 to FQDN (now commented out):
kdc:~$ cat /etc/hosts
127.0.0.1   localhost
#127.0.0.1  kdc.example.com kdc
172.16.3.3  kdc.example.com kdc

After purging the related principals from DB and keytab and restarting both VMs, everything works as desired. Ufff...

A: Try this below.
edit /etc/ssh/sshd_config
find PermitRootLogin no
change PermitRootLogin => yes
command> /etc/init.d/sshd restart


text:
Q: Efficient way to find missing rows across multiple joins Given the following schema, where members can share ownership of posts:
member: id, name, ...
post_owner: member_id, post_id
post: id, created, ...

What's the most efficient query to find users who haven't made a post in the last 90 days.
I thought of this, but it seems inefficient:
select *
from member
where member_id not in (
    select member_id
    from post p
    join post_owner po on po.post_id = p.id
    where created > subdate(now(), 90))

Assume there is an index on post(created) and all foreign keys.

A: what about this?
SELECT m.id, m.name
From post p
INNER JOIN post_owner po ON po.post_id = p.id AND
RIGHT JOIN member m ON m.id = po.member_id
where  DATE_SUB(CURRENT_DATE(), INTERVAL 90 DAY) <= created

A: SELECT m.id, m.name
FROM member m
LEFT JOIN post_owner po ON m.id = po.member_id
LEFT JOIN post p ON po.post_id = p.id AND p.created >= DATE_SUB(CURRENT_DATE(), INTERVAL 90 DAY)
WHERE p.id IS NULL

Hint: compare p.created to a constant so as to make use of indexes.

A: Try this:
SELECT m.id, m.name
FROM member m
LEFT JOIN post_owner po ON m.id = po.member_id
LEFT JOIN post p ON po.post_id = p.id AND DATEDIFF(CURRENT_DATE(), p.created) <= 90
WHERE p.id IS NULL


text:
Q: istio JWT authentication for single service behind ingress gateway I have 2 services running on AKS (v1.16.13) and deployed the following istio (v1.7.3) configuration. First one is a UI where I invoke the OIDC flow and get JWT token, second one is a backend service which should require a valid JWT token.
apiVersion: networking.istio.io/v1beta1
kind: Gateway
metadata:
  name: myapp-gateway
  namespace: "istio-system"
spec:
  selector:
    istio: ingressgateway
  servers:
  - hosts:
    - myapp.com
    port:
      name: http-myapp
      number: 80
      protocol: HTTP
    tls:
      httpsRedirect: true
  - hosts:
    - myapp.com
    port:
      name: https-myapp
      number: 443
      protocol: HTTPS
    tls:
      credentialName: myapp-credential
      mode: SIMPLE
---
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: myapp
  namespace: myapp
spec:
  gateways:
  - istio-system/myapp-gateway
  hosts:
  - myapp.com
  http:
  - match:
    - uri:
        prefix: /ui
    route:
    - destination:
        host: myapp-ui.myapp.svc.cluster.local
        port:
          number: 4200
  - match:
    - uri:
        prefix: /backend/
    rewrite:
      uri: /
    route:
    - destination:
        host: myapp-service-backend.myapp.svc.cluster.local
        port:
          number: 8080
---
apiVersion: security.istio.io/v1beta1
kind: RequestAuthentication
metadata:
  name: myapp-jwt-backend
  namespace: myapp
spec:
  jwtRules:
  - issuer: https://oktapreview.com
  selector:
    matchLabels:
      app: myapp-service-backend

With that config I would expect to get 401 if I invoke myapp.com/backend but that's not the case. Request authentication doesn't kick in.
After some further research (https://discuss.istio.io/t/cannot-use-jwt-policy-with-an-externalname-virtualservice-target/2794/3), I found out that I can't apply RequestAuthentication on a VirtualService but only on a Gateway which is quite odd to me but ok. I've changed the RequestAuthentication to the following but still nothing has changed after invoking backend:
apiVersion: security.istio.io/v1beta1
kind: RequestAuthentication
metadata:
  name: myapp-jwt-backend
  namespace: istio-system
spec:
  jwtRules:
  - issuer: https://oktapreview.com
  selector:
    matchLabels:
      istio: myapp-gateway

Do you have any idea how can I setup istio for my use case? Assuming the RequestAuthentication would work on a gateway, do I need 2 gateway? 1 for UI and the second for backend? Seems like an overkill.

A: Thanks to the sachin's comment and going again through the documentation made me realized that I need AuthorizationPolicy on top of RequestAuthentication:
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: myapp-require-jwt-backend
spec:
  action: ALLOW
  rules:
  - from:
    - source:
        requestPrincipals:
        - https://xxx/*
  selector:
    matchLabels:
      app: myapp-service-backend

The request authentication is only making sure that when a JWT token is provided, it has to be a valid one. If there is no token, it will just pass through the request.


text:
Q: Intuitive reason why $\sqrt a\cdot\sqrt b \neq \sqrt {ab}$ when $a$ and $b$ are negative As a rule of thumb I have learnt that $\sqrt a\cdot\sqrt b \neq \sqrt {ab}$ if $a$ and $b$ are negative.
I have not understood why this was a problem and took the word of my teacher.
Is this something so fundamental that it should be taken for granted or is there a reason why we can't
I'm sorry for this basic question but I would like to understand this concept a bit more .

A: To disprove a statement, you need only provide one counterexample. We have
$$\sqrt{-1}\sqrt{-1} = -1 \neq 1 = \sqrt{(-1)(-1)}.$$

A:
$T = \sqrt{a} \times \sqrt{b}$ where $a,b$ are each negative.

If the focus is on Real Analysis, then (for example) $\sqrt{a}$ is undefined, so the equation above is gibberish.
If the focus is on Complex Analysis, and $a < 0, i = \sqrt{-1}$, then $$\sqrt{a} = i\sqrt{|a|}, \tag1$$
so $$T = (i^2) \sqrt{|a|} \times \sqrt{|b|} = -1\sqrt{|ab|}.\tag2$$
It just so happens that when $a,b < 0$, then $(ab) = |ab|.$
In that event, within the Complex Analysis framework, you have
$$T = (-1)\sqrt{(ab)}.$$
Actually, the situation in Complex Analysis is somewhat more convoluted.  In Real Analysis, there is the generally accepted convention that (for example) $\sqrt{4}$ refers to $+2$ rather than $-2$.
In Complex Analysis, it is unclear (at least to me) how generally accepted the convention is that (for example) $\sqrt{-4} = 2i$, rather than $-2i$.

A: The reason for the subtlety is that the square root is a multivalued function, i.e. for any $y$ there is more than one (two, in fact) $x$ such that $x^2 = y$. For example, if $y = 4$, then $x=2$ or $x=-2$, if $y = -9$ then $x = 3i$ or $x = -3i$ where $i$ is the imaginary unit.
In order to see how the multivalued nature of the square root undermines the product rule $\sqrt{a}\sqrt{b} = \sqrt{ab}$, recall that every complex number can be written in the polar form as $z = re^{i\theta}$ for a non-negative $r$ and an angle $\theta$ called the argument. This notation makes it clear that raising $z$ to a power $z^a$ corresponds to multiplying the angle $\theta$ by the exponent $a$. Thus, taking a square root corresponds to halving $\theta$. Note that $\theta$ is periodic
$$
e^{i\theta} = e^{i(\theta + 2\pi)}.
$$
Halving the angles on the left hand side and the right hand side allows us to arrive at two different square roots: both $e^{i\theta/2}$ and $e^{i(\theta/2 + \pi)}$ are valid square roots of $e^{i\theta}$. Because $e^{i\pi} = -1$ (see Euler's identity), the two square roots differ in sign (c.f. $2$ and $-2$, $3i$ and $-3i$ in the examples above).
The reason that the product rule $\sqrt{a}\sqrt{b} = \sqrt{ab}$ fails is that due to periodicity in argument the two sides can "wind around" a different number of times. Using the example from one of the other answers
$$
\sqrt{-1}\sqrt{-1} = \sqrt{e^{i\pi}}\sqrt{e^{i\pi}} = e^{i\pi/2}e^{i\pi/2} = e^{i\pi} = -1 \\
\sqrt{(-1)(-1)} = \sqrt{e^{i\pi}e^{i\pi}} = \color{green}{\sqrt{e^{i2\pi}} = \sqrt{e^0}} = \sqrt{1} = 1.
$$
Note how in the step marked in green we have reduced the angle $2\pi$ to zero. This corresponds to taking the principal value of a multivalued function. If we chose not to do this and instead halved the angle in that step then we would have obtained the same result as in the first equation
$$
\sqrt{(-1)(-1)} = \sqrt{e^{i\pi}e^{i\pi}} = \color{red}{\sqrt{e^{i2\pi}} = e^{i2\pi/2}} = e^{i\pi} = -1.
$$
Note however that the transformation in red is in fact incorrect, because it fails to choose the principal value of a multivalued function.
Thus, the product rule fails because to use square root in algebraic expressions (and to treat it as a function more generally) we force it to take the principal value and that arbitrary choice cannot be made consistently across expressions that wind the argument different number of times, such as $\sqrt{a}\sqrt{b}$ and $\sqrt{ab}$. More concretely, in $\sqrt{ab}$ the product of $a$ and $b$ is allowed to wind a full $2\pi$ argument before being forced to the principal value by square root, but in $\sqrt{a}\sqrt{b}$ each argument is halved before they can add up to a full $2\pi$.
In summary, in an expression like $\sqrt{a}\sqrt{b} = \sqrt{ab}$ the principal value is chosen from among the set of valid square roots at different stages of the calculation and it turns out that exactly when you take the principal value affects the result.

Remark: Note that the principal value of the square root of a non-negative real number does in fact satisfy the product rule, so if $a > 0$ and $b > 0$ then $\sqrt{a}\sqrt{b} = \sqrt{ab}$.

A: According to Varberg, Purcell & Rigdon, the symbol $\sqrt{ \quad}$ means the positive root for a number, so, the property doesn't hold for negative numbers because there's no positive root. That's a possible reason why your teacher gave the property as a default.
On the other hand I would start proving that $\sqrt{a}\sqrt{b} = \sqrt{ab}$ to get more knowledge of the property
Firstly I would say that, $\sqrt{a} = x $ and $\sqrt{b} = y$ and with some algebra we also have the following equalities $x^2 = a$ and $y^2 = b$ then to start the prove
$$
\begin{align*}
x^2    &= a \\
x^2y^2 & = ab \\
\sqrt{x^2y^2} & = \sqrt{ab} \\
\sqrt{x^2}\sqrt{y^2} & = \sqrt{ab} \\
xy & = \sqrt{ab} \\
\end{align*}
$$
On the other hand,
$$
\begin{align*}
x    &= \sqrt{a} \\
x \sqrt{b}  &= \sqrt{a}\sqrt{b} \\
xy  &= \sqrt{a}\sqrt{b} \\
\end{align*}
$$
So, we can conclude that
$$
\sqrt{a}\sqrt{b} = \sqrt{ab} \quad \dagger
$$
The proof shows that in order to the property to hold, squared numbers where used, so, those must be positive numbers.
Hope was useful


text:
Q: Scaling for spring boot application using spring cloud I am using spring boot with Kubernetes and Eventhub. To connect with Azure Eventhub i use spring cloud stream. What is the math to determine the number of pods assuming non reactive spring boot application with apache tomcat?
Edit 1: to reframe my question, how do you factor in spring boot performance , request rate , user count, etc while scaling the pods?

A: In general the number of pods can be managed with a Deployment in Kubernetes. For more information you can see here kubernetes.io. In a Deployment you tell Kubernetes how many Replicas you want, which means how many Pods should be running. I don't know what you mean with non reactive spring boot application with apache tomcat. I also don't know about spring cloud stream.


text:
Q: Cloudfront decision to fetch data from cache or server? From Amazon cloud front

Amazon CloudFront is a web service that speeds up distribution of your
  static and dynamic web content, such as .html, .css, .php, and image
  files, to your users. CloudFront delivers your content through a
  worldwide network of data centers called edge locations.

Per mine undserstanding, CloudFront must be caching the content with URL as key. URL can serve both static and dynamic content. Say i have 100 weburl's , out of which 30 serves the static content and 70 serves dynamic content(user specific data). I have one question each on static and dynamic content
Dynamic content :-
Say user_A access his data through url_A from  US. That data has been cached . He updates the first name. Now same user will access the data from same location in US or from
another location in UK. We he see data prior to updation. If yes how will edge location come to know data needs to fetched from server not from cache ?
Does edge location  continue to display the  data from cache for configurable amount of time and if time is passed then fetch it from server ?
Does cloudfront allows to configure specific URL's that needs to fetched from server instead of cache always ?
Static content :-
There are chances that even static data may change will with each release. How cloud front will know that cached static content is stale  and needs to be fetched from server ?

A: Amazon CloudFront uses an expiration period (or Time To Live - TTL) that you specify.
For static content, you can set the default TTL for the distribution or you can specify the TTL as part of the headers. When the TTL has expired, the CloudFront edge location will check to see whether the Last Modified timestamp on the object has changed. If it has changed, it will fetch the updated copy. If it is not changed, it will continue serving the existing copy for the new time period.
If static content has changed, your application must send an Invalidation Request to tell CloudFront to reload the object even when the TTL has not expired.
For dynamic content, your application will normally specify zero as the TTL. Thus, that URL will always be fetched from the origin, allowing the server to modify the content for the user.
A half-and-half method is to use parameters (eg xx.cloudfront.net/info.html?user=foo). When configuring the CloudFront distribution, you can specify whether a different parameter (eg user=fred) should be treated as a separate object or whether it should be ignored.
Also, please note that each CloudFront edge location has its own cache. So, if somebody accessed a page from the USA, that would not cause it to be cached in the UK.
See the documentation: Specifying How Long Objects Stay in a CloudFront Edge Cache (Expiration)


text:
Q: Looping through a dynamic List of objects I'm trying to implement a snippet where we can loop through a dynamic list of objects.
using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var l = new List<int>();
        l.Add(1);
        l.Add(2);
        l.Add(3);
        l.Add(4);

    foreach(var i in l){
        Console.WriteLine(i);
        if(i==3){
            l.Add(5);
        }

    }

}

}

This is throwing below run time error.
1
2
3
Run-time exception (line 15): Collection was modified; enumeration operation may not execute.

Stack Trace:

[System.InvalidOperationException: Collection was modified; enumeration operation may not execute.]
  at Program.Main(): line 15

Any help is appreciated. Thanks.

A: This can be achieved by replacing foreach with for loop
for (var i = 0; i < l.Count; i++)
{
     Console.WriteLine(l[i]);
     if (l[i] == 3)
     {
        l.Add(5);
     }
}


text:
Q: Python3: Merging multiple dictionaries into a new dictionary I apologize if this is a duplicate.  I'm sure it is, I think I just don't know how to frame the question I'm trying to ask to be able to search for the correct answers.
I have a function that returns a dictionary per line, like so:
{'symbol_name': 'AUDIOUSDT', 'timeframe_name': '1m', 'scenario': 1, 'continuity': 1}
{'symbol_name': 'AUDIOUSDT', 'timeframe_name': '3m', 'scenario': 2, 'continuity': 1}
{'symbol_name': 'AUDIOUSDT', 'timeframe_name': '5m', 'scenario': 1, 'continuity': 1}
{'symbol_name': 'AUDIOUSDT', 'timeframe_name': '15m', 'scenario': 1, 'continuity': 1}
{'symbol_name': 'AUDIOUSDT', 'timeframe_name': '30m', 'scenario': 2, 'continuity': 1}
{'symbol_name': 'AUDIOUSDT', 'timeframe_name': '1h', 'scenario': 2, 'continuity': 1}
...
{'symbol_name': 'TRBUSDT', 'timeframe_name': '1m', 'scenario': -2, 'continuity': 0}
{'symbol_name': 'TRBUSDT', 'timeframe_name': '3m', 'scenario': 2, 'continuity': 1}
{'symbol_name': 'TRBUSDT', 'timeframe_name': '5m', 'scenario': 1, 'continuity': -1}
{'symbol_name': 'TRBUSDT', 'timeframe_name': '15m', 'scenario': 1, 'continuity': -1}
{'symbol_name': 'TRBUSDT', 'timeframe_name': '30m', 'scenario': 2, 'continuity': 1}
{'symbol_name': 'TRBUSDT', 'timeframe_name': '1h', 'scenario': 2, 'continuity': 1}

I want to create a new dictionary line that merges the data for the lines that have a common symbol_name, like so:
{'symbol_name': 'AUDIOUSDT', '1m_scenario': 1, '1m_continuity': 1, '3m_scenario': 2, '3m_continuity': 1, '5m_scenario': 1, '5m_continuity': 1, '15m_scenario': 1, '15m_continuity': 1, '30m_scenario': 2, '3m_continuity': 1, '1h_scenario': 2, '1h_continuity': 1 }
...
{'symbol_name': 'TRBUSDT', '1m_scenario': -2, '1m_continuity': 0, '3m_scenario': 2, '3m_continuity': 1, '5m_scenario': 1, '5m_continuity': -1, '15m_scenario': 1, '15m_continuity': -1, '30m_scenario': 2, '3m_continuity': 1, '1h_scenario': 2, '1h_continuity': 1 }

I'm having a hard time figuring out how to do this.  I've tried to break this down into small bite-size chunks so I can get the hang of it, starting with just getting each timeframe into  a new dictionary based on symbols_name:
data = {}
for item in query:
    symbol = item['symbol_name']
    timeframe = item['timeframe_name']
    data[symbol] = {}
    data[symbol][timeframe] = {}

print(data)

# returns:
{'AUDIOUSDT': {'1h': {}}, ... 'TRBUSDT': {'1h': {}}}

In the above example, I thought I would see the other timeframe keys in the new dictionary line I'm trying there other than just 1h, because each time the loop runs, timeframe_name is different, but I just see the last timeframe_name.
I tried a different variation, but it just got me back to where I had started:
for item in query:
    symbol = item['symbol_name']
    timeframe = item['timeframe_name']
    data = {}
    data[symbol] = {}
    data[symbol][timeframe] = {}
    print(data)

# returns:
{'AUDIOUSDT': {'1m': {}}}
{'AUDIOUSDT': {'3m': {}}}
{'AUDIOUSDT': {'5m': {}}}
{'AUDIOUSDT': {'15m': {}}}
{'AUDIOUSDT': {'30m': {}}}
{'AUDIOUSDT': {'1h': {}}}
...
{'TRBUSDT': {'1m': {}}}
{'TRBUSDT': {'3m': {}}}
{'TRBUSDT': {'5m': {}}}
{'TRBUSDT': {'15m': {}}}
{'TRBUSDT': {'30m': {}}}
{'TRBUSDT': {'1h': {}}}

Any pointers?

A: You can use setdefault and update methods of dict:
data = {}

for item in query:
    symbol = item['symbol_name']
    timeframe = item['timeframe_name']
    d = data.setdefault(symbol, {})
    d.update({'symbol_name': symbol,
              f'{timeframe}_scenario': item['scenario'],
              f'{timeframe}_continuity': item['continuity']})

>>> list(data.values())
[{'symbol_name': 'AUDIOUSDT',
  '1m_scenario': 1,
  '1m_continuity': 1,
  '3m_scenario': 2,
  '3m_continuity': 1,
  '5m_scenario': 1,
  '5m_continuity': 1,
  '15m_scenario': 1,
  '15m_continuity': 1,
  '30m_scenario': 2,
  '30m_continuity': 1,
  '1h_scenario': 2,
  '1h_continuity': 1},
 {'symbol_name': 'TRBUSDT',
  '1m_scenario': -2,
  '1m_continuity': 0,
  '3m_scenario': 2,
  '3m_continuity': 1,
  '5m_scenario': 1,
  '5m_continuity': -1,
  '15m_scenario': 1,
  '15m_continuity': -1,
  '30m_scenario': 2,
  '30m_continuity': 1,
  '1h_scenario': 2,
  '1h_continuity': 1}]

Old answer (to avoid duplicate answer with @AkshaySehgal)
Use defaultdict from collections module
from collections import defaultdict

data = collections.defaultdict(dict)

for item in query:
    symbol = item['symbol_name']
    timeframe = item['timeframe_name']
    data[symbol].update({'symbol_name': symbol,
                      f'{timeframe}_scenario': item['scenario'],
                      f'{timeframe}_continuity': item['continuity']})

Output:
>>> list(data.values())
[{'symbol_name': 'AUDIOUSDT',
  '1m_scenario': 1,
  '1m_continuity': 1,
  '3m_scenario': 2,
  '3m_continuity': 1,
  '5m_scenario': 1,
  '5m_continuity': 1,
  '15m_scenario': 1,
  '15m_continuity': 1,
  '30m_scenario': 2,
  '30m_continuity': 1,
  '1h_scenario': 2,
  '1h_continuity': 1},
 {'symbol_name': 'TRBUSDT',
  '1m_scenario': -2,
  '1m_continuity': 0,
  '3m_scenario': 2,
  '3m_continuity': 1,
  '5m_scenario': 1,
  '5m_continuity': -1,
  '15m_scenario': 1,
  '15m_continuity': -1,
  '30m_scenario': 2,
  '30m_continuity': 1,
  '1h_scenario': 2,
  '1h_continuity': 1}]

A: Assuming you have a list of dicts as shown above...
You can do this with collections.defaultdict to group the dicts by symbol_name, and create the expected keys, and update the dict with them.
Try this -
from collections import defaultdict

l= [{'symbol_name': 'AUDIOUSDT', 'timeframe_name': '1m', 'scenario': 1, 'continuity': 1},
    {'symbol_name': 'AUDIOUSDT', 'timeframe_name': '3m', 'scenario': 2, 'continuity': 1},
    {'symbol_name': 'AUDIOUSDT', 'timeframe_name': '5m', 'scenario': 1, 'continuity': 1},
    {'symbol_name': 'AUDIOUSDT', 'timeframe_name': '15m', 'scenario': 1, 'continuity': 1},
    {'symbol_name': 'AUDIOUSDT', 'timeframe_name': '30m', 'scenario': 2, 'continuity': 1},
    {'symbol_name': 'AUDIOUSDT', 'timeframe_name': '1h', 'scenario': 2, 'continuity': 1},
    {'symbol_name': 'TRBUSDT', 'timeframe_name': '1m', 'scenario': -2, 'continuity': 0},
    {'symbol_name': 'TRBUSDT', 'timeframe_name': '3m', 'scenario': 2, 'continuity': 1},
    {'symbol_name': 'TRBUSDT', 'timeframe_name': '5m', 'scenario': 1, 'continuity': -1},
    {'symbol_name': 'TRBUSDT', 'timeframe_name': '15m', 'scenario': 1, 'continuity': -1},
    {'symbol_name': 'TRBUSDT', 'timeframe_name': '30m', 'scenario': 2, 'continuity': 1},
    {'symbol_name': 'TRBUSDT', 'timeframe_name': '1h', 'scenario': 2, 'continuity': 1}]

d = defaultdict(dict)

for i in l:
    k = {'symbol_name':i['symbol_name'],
         i['timeframe_name']+'_scenario':i['scenario'],
         i['timeframe_name']+'_continuity':i['continuity']}
    d[i['symbol_name']].update(k)

output = list(d.values())
print(output)

[{'symbol_name': 'AUDIOUSDT', '1m_scenario': 1, '1m_continuity': 1, '3m_scenario': 2, '3m_continuity': 1, '5m_scenario': 1, '5m_continuity': 1, '15m_scenario': 1, '15m_continuity': 1, '30m_scenario': 2, '30m_continuity': 1, '1h_scenario': 2, '1h_continuity': 1},
 {'symbol_name': 'TRBUSDT', '1m_scenario': -2, '1m_continuity': 0, '3m_scenario': 2, '3m_continuity': 1, '5m_scenario': 1, '5m_continuity': -1, '15m_scenario': 1, '15m_continuity': -1, '30m_scenario': 2, '30m_continuity': 1, '1h_scenario': 2, '1h_continuity': 1}]

A: Here is my suggestion:
query = [{'symbol_name': 'AUDIOUSDT', 'timeframe_name': '1m', 'scenario': 1, 'continuity': 1},
{'symbol_name': 'AUDIOUSDT', 'timeframe_name': '3m', 'scenario': 2, 'continuity': 1},
{'symbol_name': 'AUDIOUSDT', 'timeframe_name': '5m', 'scenario': 1, 'continuity': 1},
{'symbol_name': 'AUDIOUSDT', 'timeframe_name': '15m', 'scenario': 1, 'continuity': 1},
{'symbol_name': 'AUDIOUSDT', 'timeframe_name': '30m', 'scenario': 2, 'continuity': 1},
{'symbol_name': 'AUDIOUSDT', 'timeframe_name': '1h', 'scenario': 2, 'continuity': 1},
{'symbol_name': 'TRBUSDT', 'timeframe_name': '1m', 'scenario': -2, 'continuity': 0},
{'symbol_name': 'TRBUSDT', 'timeframe_name': '3m', 'scenario': 2, 'continuity': 1},
{'symbol_name': 'TRBUSDT', 'timeframe_name': '5m', 'scenario': 1, 'continuity': -1},
{'symbol_name': 'TRBUSDT', 'timeframe_name': '15m', 'scenario': 1, 'continuity': -1},
{'symbol_name': 'TRBUSDT', 'timeframe_name': '30m', 'scenario': 2, 'continuity': 1},
{'symbol_name': 'TRBUSDT', 'timeframe_name': '1h', 'scenario': 2, 'continuity': 1}]

res = {}

for i in query:
    res[i['symbol_name']] = {'symbol_name':i['symbol_name']}

for i in query:
    x = i['timeframe_name']
    scen_key = x + '_' + 'scenario'
    con_key = x + '_' + 'continuity'
    if scen_key in res[i['symbol_name']]:
        res[i['symbol_name']][scen_key] += i['scenario']
    else:
        res[i['symbol_name']][scen_key] = i['scenario']
    if con_key in res[i['symbol_name']]:
        res[i['symbol_name']][con_key] += i['continuity']
    else:
        res[i['symbol_name']][con_key] = i['continuity']

print(res)

Output:
{'AUDIOUSDT': {'symbol_name': 'AUDIOUSDT', '1m_scenario': 1, '1m_continuity': 1, '3m_scenario': 2, '3m_continuity': 1, '5m_scenario': 1, '5m_continuity': 1, '15m_scenario': 1, '15m_continuity': 1, '30m_scenario': 2, '30m_continuity': 1, '1h_scenario': 2, '1h_continuity': 1}, 'TRBUSDT': {'symbol_name': 'TRBUSDT', '1m_scenario': -2, '1m_continuity': 0, '3m_scenario': 2, '3m_continuity': 1, '5m_scenario': 1, '5m_continuity': -1, '15m_scenario': 1, '15m_continuity': -1, '30m_scenario': 2, '30m_continuity': 1, '1h_scenario': 2, '1h_continuity': 1}}

if you want result as list, you can get it with res.values()


text:
Q: Adjective for a person who deeply understands and appreciates another (really gets them) Instead of saying "she is the kind of person that really gets other, she really understands them deeply", I want an adjective for that.  It's not empathetic.

A: Even if you said that it's not empathetic, I think that what you're looking for might be:
Empathetic
Someone who has the ability to understand and  share someone's feelings and emotions.
Understanding
Someone who is aware of someone's condition, is tolerant and doesn't judge.
Sympathetic
Someone who is concerned about somebody and cares about them and what they feel.
Supportive
Someone who understands somebody, helps and encourages them.


text:
Q: Starting Golang webserver inside a Docker container I am in the process of creating a service that, amongst other things, allows users start/stop a Golang web server at will.  To get a Nodejs server running under similar circumstances I  simply issue a nodejs /path/to/index.js  &disown from within a batch file that I run when the container starts up.  The essential bits
ADD gorun.sh /usr/local/bin/gorun.sh
RUN chmod +x /usr/local/bin/gorun.sh

...
ENTRYPOINT ["/bin/bash"]
CMD ["/usr/local/bin/gorun.sh"]

This works perfectly, every time. In gorun.sh I have the nodejs /path/to/index.js & disown line.
Now that I am trying to get a Golang web server running under similar conditions I thought I would try the same approach.  I modified the gorun.sh script to read
#! /bin/bash
go run /path/to/index.go & disown;
ps aux | grep go

Now here is the odd thing.  I have tried to get the Go server started in two ways

*

*Purely as an experiment I started the Docker container with a terminal attached at called gorun from the terminal. The Golang server fired up right away and everything was hunky-dory.

*To better emulate the way things work in the real world - I placed a file, startgo.txt at a pre-determined location which then gets picked up by a CRON job that calls gorun. This time round, no joy - the server does not start up.

Why not just call go run /path/to/index.go & disown from the Docker container start-up script? Tried that too, with the same result: the server does not start up.
It is not clear to me what is happening here.  Why does the Nodejs server fire up whilst the Golang server refuses point blank?  Why does it fire up if I run the same script from within a terminal?

A: This issue drove me round the bend with looming deadlines and it took me a whole 24h to figure out what was happening.  The problem is a rather subtle one. So here is an explanation for the benefit of anyone running into this thread.
Never forget: For Golang to deliver its magic the OS has to be able to find it.  Enter the $GOPATH environment variable.  If you are anything like me you will have followed instructions somewhere on the net on how to do this. I followed the instructions in this post on Vultr.  The gist of what they suggest
echo export GOPATH=/opt/gopkg >> ~/.bashrc
echo export GOROOT=/opt/go >> ~/.bashrc
echo export PATH=$PATH:$GOROOT/bin:$GOPATH/bin >> ~/.bashrc

Excellent instructions - thank you Vultr.
The Key Isssue
As I mention in my original question what puzzled me was that when I executed the batch file gorun containing
go run /path/to/index.go &

from a terminal session attached to the Docker session it worked. However, when I tried to execute it from a bash script executed at the start of the Docker session it did not.
When you think about this a bit and look at what is happening in the Vultr instructions above it is all blindingly obvious. The path variables are being set ONLY WHEN AN INTERACTIVE TERMINAL IS OPEN! - i.e. NOT when you attempt to execute a go dosomething instruction from any old batch file - for instance the one you run when the Docker container is launched.
If you want to have Golang operate correctly from within a Docker container right at the top of the bash script you run on container startup you will need to issue
export GOPATH="/opt/gopkg";
export GOROOT="/opt/go";
export PATH=$PATH:$GOPATH/bin:$GOROOT/bin;


text:
Q: Identity non-English words in a column in pandas dataframe using Wordnet I have a column in pandas dataframe with millions of rows. Many words are non-English (e.g. words from other languages or that do not mean anything, like "**5hjh"). I thought of using Wordnet as a comprehensive English dictionary to help me clean up this column, which comprises lists. Ideally, the output should be a new column with English words only.
I have tried the following code, which I got from Stackoverflow, but it does not seem to be working as it returns an empty column with no words whatsoever:
from nltk.corpus import wordnet

def check_for_word(s):
    return ' '.join(w for w in str(s).split(',') if len(wordnet.synsets(w)) > 0)

df["new_column"] = df["original_column"].apply(check_for_word)

A: This expression str(s).split(',') creates a list of strings that contain whitespace as the first character for all words except the first one (assuming the str(s) worked as expected). When you then do this: wordnet.synsets(w) you basically look up w which has the whitespace as the first character in wordnet and it is not there, so all synsets will be of length 0.
E.g. len(wordnet.synsets(' october')) will be zero.
I recommend debugging to

*

*check that the str(s) really creates a proper string and

*make sure your 'w's are actually the words (e.g. do not start with whitespace). A simple solution could be to use the .trim() method if the only issue is the whitespace

If you provide a df and a screenshot of your output for that df, it would be easier to pinpoint the issue.
Update: addiditional points based on your comments above:
Thank you, Fernanda. I've read your comments above (in the main thread). Here are a few more items you might find relevant:

*

*wordnet contains only a few adverbs, so in your approach, you might be losing some adverbs

*the synset counting is a bit slow. I'd use instead:

if in wordnet.synsets(word):

syntaxis. Maybe it will be faster

*

*be careful with the idea of using word occurrence counting idea, as a large proportion of totally valid words is rare (appear only once in the corpus even for large corpora). This is related to Zipf law.

*consider regular expressions based method to filter out words which contain unusual characters


text:
Q: Function from 1-dim. sphere to real line This is either trivial or wrong:
Let $f:\mathbb S^1 \to \mathbb R$, where $\mathbb S^1 = [-1/2,1/2]/(-1/2\sim1/2)$ is the one-dimensional sphere, be such that $f\in L^1\big(\mathbb S^1\big)$; does it make sense to define $\tilde f:\mathbb R \to \mathbb R$ such that $\tilde f(x)= f(x)$ if $x\in (-1/2,1/2]$, and $\tilde f(x)= 0$ otherwise, and to say that for any $\kappa\in \mathbb Z$ $$\mathcal F \tilde f(u)|_{u=\kappa}:=\int_{\mathbb R}\tilde f(x)e^{2\pi i \kappa x }dx=\int_{\mathbb S^1} f(x) e^{2\pi i \kappa x }dx=:\mathcal F f(\kappa)?$$
I have some results about Fourier transforms of functions on $\mathbb R$ that I now need for functions on $\mathbb S^1$ and this argument would allow me to avoid reproving them. The definition of $\tilde f$ and the equality above seem to make sense computationally but for some reason my intuition tells me that they do not mathematically.

A: The manipulation you described is correct, but it usually does not give an easy way to obtain results for the Fourier transform on $S^1$ from the results for the Fourier transform on $\mathbb{R}$. For example, $\tilde f$ is typically discontinuous even if $f$ is continuous, which is an obstacle to relating the smoothness of $f$ to the decay of its Fourier coefficients.
What happens in such cases is: $\mathcal F\tilde f$ has slow decay at infinity, but dips toward zero at integer points, thus aligning with the quickly decaying Fourier coefficients $\hat f(n)$. A simple illustration is $f\equiv 1$, where all Fourier coefficients except one are zero. Since $\tilde f=\chi_{[-1/2,1/2]}$, its Fourier transform is the sinc function with some normalization: it is pretty heavy-tailed (not in $L^1(\mathbb{R})$) but duly vanishes at the integers.
A relevant result on the relation between the Fourier transform of a function and the Fourier series of its periodization is the Poisson summation formula.


text:
Q: Does the Siri remote gyroscope work on tvOS simulator? If I connect my Siri remote to my MacBook via bluetooth and then run the tvOS simulator, will it detect motion events?

A: Yes, motion events coming in from the Siri Remote accelerometer are usable with the simulator. But: You need a Mac with Bluetooth Low Energy support to be able to pair the remote. All systems labeled as Bluetooth 4 compatible work. Older systems can be upgraded to work, by purchasing a compatible bluetooth dongle, but that is probably beyond the scope of this question...


text:
Q: Is it possible to access the GetLongPathName() Win32 API in Python? I need to convert paths in 8.3 convention to full path.
In Perl, I can use Win32::GetLongPathName() as pointed out in How do I get full Win32 path from 8.3 DOS path with Perl? But, I need to do it in Python.

A: Use ctypes which is available in the Python standard without the need of using the pywin32 API. Like this:
from ctypes import *

buf = create_unicode_buffer(260)
GetLongPathName = windll.kernel32.GetLongPathNameW
rv = GetLongPathName(path, buf, 260)
print buf.value

From http://mail.python.org/pipermail/python-win32/2008-January/006642.html

A: Use the GetLongPathName function from win32file
import win32file
print win32file.GetLongPathName(r'C:\progra~1')

outputs:
C:\Program Files


text: Q: Why do positives and negatives not usually co-exist? If I drink half of a bottle of water, there's half of a bottle of water and there's not half of a bottle of water. However, why is the negative sentence not usually used? Is it a wrong sentence?


text:
Q: C:Why does a seemingly right algorithm goes wrong as input gets big? The original question is:
Define a function that produces the n'th Fibonacci number, according to the defeintion:
   fib(0)=1;fib(1)=1;fib(n)=fib(n-1)+fib(n-2)
I was trying to solve this with if & else structure in C programming . I did it successfully and tested it with some small inputs. When the input number is '45', everything seems alright. However when input '46', the result became negative which indicates something must have gone wrong.
   Really hope that someone can tell me why's that, and what was I doing wrong?
The result when input 45
the result when input 46
Source Code:
include
int fib(int i)
{
    if (i == 0)
     return 1;
    else if (i == 1)
      {
        int result_1 = fib(i - 1);
        return result_1;
    }
    else
    {
        int result_2= fib(i-1) + fib(i-2);
        return result_2;
    }
}

int main(void)
{
    printf("The final result is %d\n", fib(i));
    return 0;
}

A: This is probably due to int is signed and becomes negative after 2e16 - 1.
Try using unsigned int. But even if this works, you are still limited but int maximum size.
You can try using unsigned long or unsigned long long or double to check how far you can get with your function.


text:
Q: How to set Unity SplashScreen Logo in Prebuild We are trying to programatically generate and set the Unity SplashScreen for Android and iOS.
The code below works when called from Unity [MenuItem("VoodooSauce/TEST")] but doesn't work when called from IPreprocessBuildWithReport-OnPreprocessBuild or RegisterBuildPlayerHandler ...
PlayerSettings.SplashScreen.logos = new[] {PlayerSettings.SplashScreenLogo.Create(3f, splashScreenSprite)};

We dynamically generate the "splashScreenSprite" and can successfully save it as a PNG.
We can even reload this PNG file as a Sprite.
However, regardless of what we do, the SplashScreen.logos code does not work ...
Strangely, regardless of where we call our code, it always updates the other fields in PlayerSettings.SplashScreen such as BackgroundColor, etc.

A: I ran into this issue as well. The thing that worked for me, was to make sure I saved the generated sprite as an asset to disk.
After generating the texture, and using Sprite.Create() to create the sprite object itself, I called AssetDatabase.CreateAsset() (after deleting the last one if it still existed.) I followed up with a call to AssetDatabase.SaveAssetIfDirty() just to ensure it got written to disk.
Then, in my IPreprocessBuildWithReport, updating the logos just like you did, worked.
Hope this helps.


text:
Q: Including list of params in OPENQUERY I'm trying to get the values from an external Database server executing the following code:
DECLARE @TSQL VARCHAR(8000), @VAR CHAR(2)
DECLARE @Prefixos VARCHAR(MAX);

WITH cte AS
(
    SELECT DISTINCT prefixo
    FROM ARH.arh.UorPos
)
SELECT @Prefixos = COALESCE(@Prefixos + ', ', '') + prefixo
FROM cte
ORDER BY prefixo
--SELECT @Prefixos --print a list of values separated by comma. eg.: 1, 2, 3

SELECT  @TSQL = 'SELECT * FROM OPENQUERY(DICOI_LINKEDSERVER,''SELECT * FROM ssr.vw_sigas_diage where cd_prf_responsavel in ('''''  + @Prefixos + ''''''') order by cd_prf_responsavel, codigo'
EXEC (@TSQL)

But I'm getting:

OLE DB provider "MSDASQL" for linked server "DICOI_LINKEDSERVER" returned message "ERRO: syntax error at the end of input;
  No query has been executed with that handle".
Msg 7350, Level 16, State 2, Line 1
  Cannot get the column information from OLE DB provider "MSDASQL" for linked server "DICOI_LINKEDSERVER".

I've researched the above links to try to resolve it:

*

*How to concatenate text from multiple rows into a single text string in SQL server?

*including parameters in OPENQUERY

*Join query result to a single line of values separated by comma [duplicate]

Can anyone help me to resolve it ?
Thanks in advance.

A: Before running your query with EXEC, it's best to just check first how the generated SQL string will look like.
For example by selecting the variable

DECLARE @TSQL VARCHAR(8000), @VAR CHAR(2)
DECLARE @Prefixos VARCHAR(MAX);

WITH cte AS
(
    SELECT DISTINCT prefixo
    FROM (values ('1'),('2'),('3')) q(prefixo)
)
SELECT @Prefixos = COALESCE(@Prefixos + ', ', '') + prefixo
FROM cte
ORDER BY prefixo

SELECT  @TSQL = 'SELECT * FROM OPENQUERY(DICOI_LINKEDSERVER,''SELECT * FROM ssr.vw_sigas_diage where cd_prf_responsavel in ('''''  + @Prefixos + ''''''') order by cd_prf_responsavel, codigo'

select @TSQL as TSQL
-- EXEC (@TSQL)

Then you can visually check if there's something odd about it.
Or just try running that sql yourself and see if it fails or not.
From that T-SQL it returns this result :
SELECT * FROM OPENQUERY(DICOI_LINKEDSERVER,'SELECT * FROM ssr.vw_sigas_diage where cd_prf_responsavel in (''1, 2, 3''') order by cd_prf_responsavel, codigo

Notice that there's a bit to many single-quotes in that string.
When using an IN with numbers, the single-quotes are not needed.
And something is missing at the end.
...  in ('+ @Prefixos +') order by cd_prf_responsavel, codigo'');';


text:
Q: Detect what page the user came from I have a few websites:
- https://ictsupport.ga
- https://auth.ictsupport.ga
- https://account.ictsupport.ga
- https://admin.ictsupport.ga
A user needs to be authenticated on the auth.ictsupport.ga site. After the user has logged in, it needs to be redirected to the protected page where the user came from (ictsupport.ga, account.ictsupport.ga or admin.ictsupport.ga)
How can I do this?

A: On all your pages, (or single index.php) after you have called session_start()
set $_SESSION['lastUrl'] = $_SERVER['REQUEST_URI'] at the end of the script. so the rest of your script can access the previous url before it is later revalued.

A: Use the $_SERVER['HTTP_REFERER'] it will give the last page url whether it is from same application or from a external site.
$lastUrl = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';

A: First possibility: You need to make cross-domain authentication.
Second possibility: On first site (account.ictsupport.ga, admin.ictsupport.ga) generate token for user, store it in database and redirect user with token in address (www.finaldestination.com/?token=someTokenizedToken). On you final site, you can lookup associated user with this token and authenticate him as admin or other user. You can make small api point restricted to ip of your finaldestination site for receiving information about user for token. Maybe restrict it to n requests per m time. You can limit lifespan of token for few seconds, because the redirect will be automatic, so it should be more secure.


text:
Q: Plumb error to set local host in R programming I'm writing some toy APIs on Plumber in order to get familiar with this tool. Reading various tutorials and documentations to set the local host, it is recommended these lines
library(plumber)
r = plumb("Apitest.R")
r$run(port = 1030, host = "0.0.0.0") # or r$run(port=8000)

#* Return the multiplication of two numbers
#* @param a Multiplier
#* @param b Multiplicand
#* @post /multiplication
function(a, b){
  as.numeric(a) * as.numeric(b)
}

when I run the code (with r$run(port = 1030, host = "0.0.0.0") or with r$run(port=8000)) I get this error:
> plumb(file='APItest.R')$run()
    Error in stopOnLine(lineNum, file[lineNum], e) :
      Error on line #4: '' - Error in stopOnLine(lineNum, file[lineNum], e): Error on line #4: '' - Error in stopOnLine(lineNum, file[lineNum], e): Error on line #4: '' - Error in stopOnLine(lineNum, file[lineNum], e): Error on line #4: '' - Error in stopOnLine(lineNum, file[lineNum], e): Error on line #4: '' - Error in stopOnLine(lineNum, file[lineNum], e): Error on line #4: '' - Error in stopOnLine(lineNum, file[lineNum], e): Error on line #4: '' - Error in stopOnLine(lineNum, file[lineNum], e): Error on line #4: '' - Error in stopOnLine(lineNum, file[lineNum], e): Error on line #4: '' - Error in stopOnLine(lineNum, file[lineNum], e): Error on line #4: '' - Error in stopOnLine(lineNum, file[lineNum], e): Error on line #4: '' - Error in stopOnLine(lineNum, file[lineNum], e): Error on line #4: '' - Error in stopOnLine(lineNum, file[lineNum], e): Error on line #4: '' - Error in stopOnLine(lineNum, file[lineNum], e): Error on line #4: '' - Error in stopOnLine(lineNum, file[lineNum], e

A: I faced a similar issue recently. Unfortunately the error message is not very helpful and this behavior is not well documented. In my case the problem was I was calling r$run(foo) from the same script that had the endpoint defined and this was causing the recursion problem. Hope this helps someone.


text:
Q: Shorter and less verbose condition when using Html.DisplayFor() There is the following razor code.

@Html.DisplayFor(modelitem => item.Price)

Now, I need to display text "Free" when the price is 0. So I did the following.

  @(item.Price == 0 ? "Free" : string.Format("{0:$0.00}", item.Price))

It looks very verbose. Is there a better way to do it?

A: You can use DisplayTemplates, So first create your template in (~/Views/Shared/DisplayTemplates/Price.cshtml):
@model float

    @(Math.Abs(Model) < 1 ? "Free" : string.Format("{0:$0.00}", Model))

Then use this way:
@Html.DisplayFor(p => item.Price, "Price")

A: In your model try [DisplayFormat(NullDisplayText = "FREE")]

A: you can write ExtensionMethods for htmlHelper to check your situation and run proper DisplayFor()


text:
Q: Generate a validation set from a Kaggle's training set As Kaggle provides a training set and a test set, I would like to know a way to generate a validation set (dev set) from this training set.
The goal is to have three sets :
- Training set + Validation set = Kaggle's training set
- Test set = Kaggle's test set
The fact is that the validation set has to have the same distribution as the test one. I would like to know if there exists a (simple) way to generate a validation set which respects this property. I am coding with Python 3 if that can help you to answer me.
Many thanks

A: The simplest way to split the training data into train and validation set is to use train_test_split method from sklearn.
from sklearn.model_selection import train_test_split
train_set, val_set = train_test_split(train_data, test_size=0.2)

However, the split of data will happen at random and not ensure equal distribution of classes or some other feature. Let's assume that we want to split based on distribution of target label (eg - train_data['y']). Then we should use StratifiedShuffleSplit instead.
from sklearn.model_selection import StratifiedShuffleSplit
split = StratifiedShuffleSplit(n_splits=1, test_size=0.2)
for train_index, val_index in split.split(train_data, train_data['y']):
    strat_train_data = train_data.loc[train_index]
    strat_val_data = train_data.loc[val_index]

In this case, the training data will be split into train and val set, and the distribution of 'y' will be similar in both strat_train_data and strat_val_data. If we want the split to happen based on a particular feature (eg - gender, income group etc), replace the y-parameter of split() function accordingly.


text:
Q: How can I make git list all changed files of a certain type in a specific path for a specific bug? I would like to know how to make git list all changed files

*

*of a certain type (e.g. all php files)

*filed under a certain bug no. or which are still uncommitted

*and are in a specific path

I'll start with laying out an example situation for my question.
Say I have changed the following files:
Uncommitted changes
/site/main.php
/site/main.html
/site/includes/lib.php

Commit 3
Commit message: "Bug xyz: Made some changes"
/site/main.php
/site/main.html
/site/main.js
/test/test.php
/test/test.html

Commit 2
Commit message: "Bug xyz: Made some more changes"
/site/main.php
/site/main.html
/site/includes/include.php

Commit 1
Commit message: "Bug abc: Note that this is another bug"
/site/login.php

Say I'm still working on bug xyz. Now I need a list of all php files that have been changed so far in the site directory for this bug. So I would need the following list as output:
/site/main.php
/site/includes/lib.php
/site/includes/include.php

What command can do this?

A: This is close:
git log --grep=xyz -- '*.php'

The --grep argument is applied to the commit messages.  The single quotes on the files argument ensures that git does the expansion.
A test:
ebg@ebg(328)$ git log --oneline
f687708 bar x, y, not a
dfb4b96 foo d, e, f
df18118 foo a, b, c
ebg@ebg(329)$ git log --oneline --grep=a
f687708 bar x, y, not a
df18118 foo a, b, c
ebg@ebg(330)$ git log --oneline --grep=a -- 'a.*'
df18118 foo a, b, c

The file expansion might need something to handle subdirectories.  Sort of:
git log --oneline --grep=a -- '*/a.*' 'a.*'


text:
Q: GRUB problem after creating new partition - not able to boot live-cd I've created a new NTFS partition under windows - after reebooting I've received the following error:
Unknown file system
Entering rescue mode
Grub rescue >
I would've booted one of my ubuntu live cds, but it won't even boot any of those, it hows an idle underscore blinking, and after a while the CD stops running. Tried this with 3 different ubuntu live-cds, the system refuses to boot any distribution.
Does anyone knows how to resolve this?
I'm not able to format my hard disk, even if I wanted to :(


text:
Q: Iframe aspect ratio 16:9 with fixed height I am trying to include a YouTube video in my website, but i am struggeling to get an aspect ratio of 16:9 on my iframe.
My problem is, I am working with a fixed height, but am flexible in my width. As this is a rather unusual case, I cannot seem to find a solution to my problem in any documentations, or on other StackOverflow questions.
Those all have a fixed width, and are then using padding-bottom: 56,25%; to fith the height.
I am using bootsrap classes to style my HTML, but I still apply a style tag here and there, to customize the design, that is why the code I have included below might seem a bit messy.
Next to the iframe (right side) there should be another div element, which is marked in the code with the id="text-next-to-iframe"
I have tried using said method of including a specific padding in a div surronding my iframe, and then setting the width and height of the actual iframe to 100% as you would do in a fixed height cenario, but that did not work.
I have also tried to set my iframe height to 29vh (the height I need it to be) and setting the width to different vw-values (trying to find the right value), but I ended up with the iframe not showing at all with both methods.

            Video wird geladen...

                    BAUMorg

                    Subscribe

A: I hope I didn't misunderstand this question but hopefully, this will help.
To configure the aspect ratio you want to divide the screen or container width by 16 and multiply that result by 9 to get your height.
screenWidth = containerWidth / 16
screenHeight = screenWidth * 9
Vh is relative to 1% of the viewport, and you said you need 29vh for your height. So we need to do this in reverse to get the opposite (width).
screenHeight = 29vh
screenWidth = (screenHeight / 9) * 16
which is equal to 51.5 if we drop the trailing 5's and round up it is 52vh.
Hope this helps.


text:
Q: What is the difference between data type and data structure? I found out this question has been answered before, but not very clear to me.
I understand data type can somehow called user defined class actually it is same as class in python.
But in some books dictionary (dict) is called data structure some books call it data type.
What is the difference?

A: A dictionary (or map or associative-array) is a data-structure with keys and values.
In Python, that data structure can be used as the dict datatype

So, to answer the question more broadly, all languages have built-in data types.
Not all languages have built-in data structures, but they generally can be implemented by using the data types that are available

Can we construct a class for specific data structure?

Sure, for example, I would make a class LinkedList or class BinaryTree, but as mentioned, those are composed of more simpler types.

A: Data structure is a general computer science concept. It is just a way of organizing data to make certain operations easier or harder.
Data type is a concept specific to a programming language. In a way, it is a concrete implementation of a data structure in a particular programming language. But the actual definition of what constitutes a "type" varies among programming languages. For example, in C, you can define a struct and use it as a type. There are also basic types like int, float, char etc. In python, you can use the built-in types like list, set etc. or define your own types using classes.


text:
Q: Como validar dados recebidos e retornar erros caso necessário com API Django? Bom, pessoal. Estou com uma certa dificuldade para validar e criar determinados dados no Banco de Dados recebidos via API DRF.
Seguinte, eu já tenho implementado com ModelViewSet a serialização dos dados recebidos do usuário para consultas/cadastros de novas Pessoas. Porém, dentro dessa mesma ViewSet eu estendi a função create() para que além de salvar no BD os dados recebidos para Pessoa, que também seja feito o save() da instância de User, que se trata da criação direta de um usuário para cada nova pessoa existente.

Talvez essa não seja a melhor forma de fazer a criação desse usuário, mas até o momento foi como consegui fazer. Aceito sugestões de mudança para essa tarefa também :)

Então, o código:
class PessoaViewSet(viewsets.ModelViewSet):
    queryset = Pessoa.objects.all()
    serializer_class = PessoaSerializer
    permissions_classes = [permissions.IsAuthenticated]

"""função para criar uma nova pessoa e novo usuário através da requisição via API"""
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        data = dict(self.request.data.lists())
        rgm = data['rgm'][0]
        email = data['email'][0]
        user = User.objects.create_user(username=rgm, email=email, password=rgm)
        user.save()
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

O problema que eu identifiquei foi que, sempre que enviado uma requisição POST e essa retorna algum erro na validação do formulário, ainda assim o usuário é criado.
Se após corrigir os dados no formulário e fizer outra requisição, o Django retorna outro erro na página por já existir usuário cadastrado com os dados passados na requisição.

O que eu preciso fazer:
Implementar essa funcionalidade no sistema de modo que se já houver um Usuário cadastrado no sistema com algum dos dados passados, seja retornado uma mensagem via API para o usuário, da mesma forma que é validado o erro na criação da Pessoa.

Esclarecendo: Apliquei a criação desse Usuário junto á criação da Pessoa por ser uma necessidade da aplicação, pois esse cadastro de Pessoa será feito via upload de xls e não desejamos que o usuário ou qualquer administrador do sistema precise criar um usuário para tal pessoa manualmente.

A: Basicamente o que vai precisar fazer é tratar o erro para fornecer uma resposta inteligível ao usuário.
Segue um exemplo de implementação:
from django.db import IntegrityError
from pessoa.models import Pessoa
from rest_framework import viewsets
from pessoa.serializers import PessoaSerializer
from rest_framework.response import Response
from rest_framework import status

class PessoaViewSet(viewsets.ModelViewSet):
    serializer_class = PessoaSerializer
    def get_queryset(self):
        queryset = Pessoa.objects.all()
        return queryset

    def create(self, request):
        pessoa_data = PessoaSerializer(data=request.data)
        if pessoa_data.is_valid():
            try:
                pessoa = Pessoa.objects.create(username=pessoa_data.validated_data['rgm'], email=pessoa_data.validated_data['email'], password=pessoa_data.validated_data['rgm'])
                serialized_data = PessoaSerializer(instance=pessoa)
                return Response(serialized_data.data,status=status.HTTP_201_CREATED)
            except IntegrityError:
                content = {'erro': 'Já existe uma pessoa com esse username em nossos registros'}
                return Response(content, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response(pessoa_data._errors, status=status.HTTP_400_BAD_REQUEST)

Vai ser basicamente este fluxo que deve seguir. Em caso de dúvida consulte a documentação.


text:
Q: How can I suppress private method invocation in constructor? I have a very very simple class which has a private method. The question is how to suppress this method invocation?
Here is my code:
public class Example {
    private int value;

    public Example(int value) {
        this.value = value;
        method();
    }

    private void method() {
        throw new RuntimeException();
    }

    public int getValue() {
        return value;
    }
}

And code of test (attempt at least):
public void test() throws Exception {

    PowerMockito.doNothing().when(Example.class, "method");
    final int EXPECTED_VALUE = 1;
    Example example = new Example(EXPECTED_VALUE);
    int RETRIEVED_VALUE = example.getValue();

    assertEquals(RETRIEVED_VALUE, EXPECTED_VALUE);
    verifyPrivate(Example.class, times(1)).invoke("method");
}

UPD
For me is important to comply with these two terms:

*

*PowerMockito.doNothing().when(Example.class, "method");

*PowerMockito.verifyPrivate(Example.class, times(1)).invoke("method");

A: Since you can't modify the code under test. I think there isn't a perfect solution. You need  to partially mock the Example instance.
List list = new LinkedList();
List spy = spy(list);
//You have to use doReturn() for stubbing
doReturn("foo").when(spy).get(0);

but you can't do this since you have to instantiate your object at first.

So i propose the following workaround composed of two tests. The first test remove the private method from the class, instantiate the Example and verify that the Example is correctly initialized.
The second test instantiate the Example and verify that a RuntimeException (the private method side effect).
import static org.junit.Assert.assertEquals;
import static org.powermock.api.support.membermodification.MemberMatcher.method;
import static org.powermock.api.support.membermodification.MemberModifier.suppress;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(Example.class)
public class ExampleTest {
    @Test
    public void constructor_should_initialize_the_v2alue() throws Exception {
        suppress(method(Example.class, "method"));

        final int EXPECTED_VALUE = 1;
        Example example = PowerMockito.spy(new Example(EXPECTED_VALUE));
        int RETRIEVED_VALUE = example.getValue();

        assertEquals(RETRIEVED_VALUE, EXPECTED_VALUE);
    }

    @Test(expected=RuntimeException.class)
    public void constructor_should_invoke_the_private_method() throws Exception {
        new Example(1);
    }
}


text:
Q: Any ideas about how to style this DIV? I have this , and i want to move the total reviews(The ones that show how many reviews are with how many stars)
Here's how it looks https://i.gyazo.com/a766d0a8804da7ed34d4b295976414b5.png
The mark up is like

{if $reviews}

{$review_stats.avg_rating}
 ({$review_stats.total} review{if $review_stats.total > 1}s{/if})

I could've made first div inline block and give it a width of 50% but the line won't go across the whole div anymore. Any ideea is welcome.


text:
Q: is it a routing loop? nodes cannot communicate in picture case 1, all the network nodes are able to ping each other,
adding another node as in picture case 2, I start having a problem
case 1:  case 2:

*

*machine h1 is acting as a router with two ethernet cards.

*h1 is connected to h2 via a switch,

*h1 is connected to machine h3 directly via an ethernet port with a cross cable and

*h3 is connected to h4 via a switch.

settings on h1 are
#ip addr add 172.16.192.1/22 dev eth0
#ip addr add 172.16.131.254/25 dev eth1
#ip forwarding is set to 1 in /etc/sysctl.conf

settins on h2 are
#ip addr add 172.16.192.2/22 dev eth0
#ip route add 172.16.131.128/25 via 172.16.192.1

settings on h3 are
#ip addr add 172.16.131.130/25 dev eth1
#ip addr add 172.16.131.129/25 dev eth0
#ip route add 172.16.192.0/22 via 172.16.131.254

settings on h4 are
#ip addr add 172.16.131.131/25 dev eth0
#ip route add 172.16.192.0/22 via 172.16.131.254

if one looks at the pictures of case1 and case2, it will be noticed that in case two node h4 was added, doing this machine h2 cannot ping machine h3 anymore, but in case 1 the ping was possible.
Now please don't tell me to change the network topology. It has to be exactly like this..and a condition is that a bridge cannot be used!
I'm wondering if there is a sort of a loop because in the routing table of h3 it has two entries to it's own subnet via both eth0 and eth1.
Anyway how can I make h4 be able to ping h2? with this exact same setting?

A: There's no loop, quite the opposite.
The first problem, when you have a router "in the middle" of a subnet, is that its neighbouring devices are unable to send ARP queries through it. In your case, h1 thinks that h4's IP address is "local" on eth1 (because the subnet mask says so) and makes an ARP query for it, but ARP queries cannot cross routers – and even if they did, the result would be unusable because packets to h4's MAC couldn't cross a router either.
(And if they could cross a router, then it would no longer be a router: it would become a bridge. You said you don't want a bridge.)
Normally, to solve this, the h1–h3 and h3–sw–h4 connections need to be distinct subnets.
To solve this without changing subnets, you need to enable "proxy ARP" on the router h3 in the middle. It will answer h1's ARP queries meant for h4 with its own MAC address (and will do the same with h4's ARP querires meant for h1).
Proxy-ARP is a built-in kernel feature, but if it's too limited or inflexible, it can also be performed by a userspace daemon (parpd, parprouted).

The second problem, when you have two routes for the same subnet, is that the OS doesn't know which route to use – it always picks the same one, regardless of which interface the device is behind. In your case, most likely the ping replies always go through eth0, even though the gateway towards h2 is on eth1.
If you know upfront which devices are on which side, you can add more-specific static routes for them (and delete all-but-one subnet routes):
# ip route del 172.16.131.128/25 dev eth0
# ip route add 172.16.131.131/32 dev eth0

(You can simplify this by directly configuring the eth0 IP address as a /32 instead of a /25.)
To automate this, you can also use daemons like "parprouted" which perform ARP proxying and automatically add host routes corresponding to ARP responses.


text:
Q: javascript manipulate json object For example, I have the following JSON object json_obj1
json_obj1 = {x:{id:1,bars:{show:true,barWidth:0.4}}}

Now, how could I add the following object (using javascript):
   y:{id:2,bars:{show:true,barWidth:0.4}}

to json_obj1 so that it will be:
{x:{id:1,bars:{show:true,barWidth:0.4}},y:{id:2,bars:{show:true,barWidth:0.4}}}

A: You can just set the field y of your json_obj1
json_obj1 = {x:{id:1,bars:{show:true,barWidth:0.4}}}
json_obj1.y = {id:2,bars:{show:true,barWidth:0.4}}

Now json_obj1 = {x:{id:1,bars:{show:true,barWidth:0.4}},y:{id:2,bars:{show:true,barWidth:0.4}}}

A: It doesn't appear as if your question actually involves JSON. The first code fragment is just a JavaScript object literal. Given your description of the problem, something like this should work:
json_obj1 = {x:{id:1,bars:{show:true,barWidth:0.4}}};
json_obj1.y = {id:2,bars:{show:true,barWidth:0.4}};

This will give you the desired contents in json_obj1;


text:
Q: AudioKit - audio engine configuration changes periodically I have an app that uses samplers to play loops. I am in the process of converting my app from using AVAudioEngine to AudioKit. My app now works well except for this: Approximately every 1-3 minutes, my app receives two .AVAudioEngineConfigurationChange notifications in a row. There is no apparent pattern to its repetition and this happens on both my iPhone 6s and new iPad.
Here is my init code for my "conductor" singleton:
init() {
    //sampler array
    //sampler array is cycled through as user changes sounds
    samplerArray = [sampler0, sampler1, sampler2, sampler3]

    //start by loading samplers with default preset
    for sampler in samplerArray {
        //get the sampler preset
        let presetPath = Bundle.main.path(forResource: currentSound, ofType: "aupreset")
        let presetURL = NSURL.fileURL(withPath: presetPath!)

        do {
            try sampler.samplerUnit.loadPreset(at: presetURL)
            print("rrob: loaded sample")
        } catch {
            print("rrob: failed to load sample")
        }
    }

    //signal chain
    samplerMixer = AKMixer(samplerArray)
    filter = AKMoogLadder(samplerMixer)
    reverb = AKCostelloReverb(filter)
    reverbMixer = AKDryWetMixer(filter, reverb, balance: 0.3)
    outputMixer = AKMixer(reverbMixer)

    AudioKit.output = outputMixer

    //AKSettings.enableRouteChangeHandling = false
    AKSettings.playbackWhileMuted = true

    do {
        try AKSettings.setSession(category: AKSettings.SessionCategory.playback, with: AVAudioSessionCategoryOptions.mixWithOthers)
    } catch {
        print("rrob: failed to set audio session")
    }

    //AudioBus recommended buffer length
    AKSettings.bufferLength = .medium

    AudioKit.start()

    print("rrob: did init autoEngine")

}

Any AudioKit experts have ideas for where I can start troubleshooting? Happy to provide more info. Thanks.


text:
Q: Entering mixed fractions into java I am trying to enter 1 5/8 into my code but keep getting the following error:
run:
Exception in thread "main" java.lang.NumberFormatException: For input string: "1 5/8"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1241)
at java.lang.Double.parseDouble(Double.java:540)
at ClientCode.main(ClientCode.java:42)

Java Result: 1
BUILD SUCCESSFUL (total time: 17 seconds)

this is my code:
[code] public double findFrac(int whole, String frac) {
  if (frac == null || frac.equals(""))
    return whole;
String[] parts = frac.split("/");
return whole + Integer.parseInt(parts[0]) / (double)Integer.parseInt(parts[0]);

A: Java number parsing routines do not recognize mixed numbers like "1 5/8", or even fractions like "5/8". You will need to implement the logic for evaluating those strings yourself. One way is to separate your mixed number (by splitting the string on the space character), evaluate each piece separately, and add the results. When you evaluate the "5/8" part, you will need to split on the"/", evaluate the leading and trailing parts, and do float or double division.
For instance:
String data = "1 5/8";
String[] parts = data.split(" ");
float value = Integer.parseInt(parts[0]);
if (parts.length > 1) {
    // has fractional part
    parts = parts[1].split("/");
    float numerator = Integer.parseInt(parts[0]);
    float denominator = Integer.parseInt(parts[1]);
    value += numerator / denominator;
}
// value contains 1.625

Here's the same thing as a utility method:
public static float evaluateMixedFraction(String data)
    throws NumberFormatException
{
    String[] parts = data.split(" ");
    float value = Integer.parseInt(parts[0]);
    if (parts.length > 1) {
        // has fractional part
        parts = parts[1].split("/");
        float numerator = Integer.parseInt(parts[0]);
        float denominator = Integer.parseInt(parts[1]);
        value += numerator / denominator;
    }
    return value;
}

For a real application, you would probably want some additional error checking.

A: The Double.parseDouble method doesn't understand fractions at all.  It doesn't know what to do with 1 5/8; it needs something like 1.625.
To parse fractions, you must either parse it yourself, or possibly some library somewhere might perform this task.
The Double.valueOf method, which also parses Strings (it just creates a Double instead of a double) goes to lengths to specify what is allowed and won't throw a NumberFormatException.

A: You can't do fractions in java, or most other languages for that matter. Try this class instead.

A: For this problem, you just have to deal with strings. If the input is correct, you have at least a part and at most three parts. These parts are only separated by space and slash, so you can separate them with a regular expression. e.g.:
public class Main {
    public static void main(String[] args) {
        System.out.println(parseFraction("1 4/2"));
        System.out.println(parseFraction("6/2"));
        System.out.println(parseFraction("3"));
    }

    public static double parseFraction(String input) {
        String[] array = input.split("[ /]");
        switch (array.length) {
        case 1: // e.g. "1"
            return Double.parseDouble(array[0]);
        case 2: // e.g. "1/2"
            return Double.parseDouble(array[0]) / Double.parseDouble(array[1]);
        case 3: // e.g. "1 2/3"
            return Double.parseDouble(array[0]) +
                    Double.parseDouble(array[1]) / Double.parseDouble(array[2]);
        default:
            throw new IllegalArgumentException("Wrong input!");
        }
    }
}

The inputs are equivalent, so that output is the same for all cases:
3.0
3.0
3.0

A: I would recommend regular expressions to parse the input.
the following is an example of how to parse the fraction:
static final String numberPatern="[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?";
static final Pattern pWhole = Pattern.compile("^("+numberPatern+")([\\s\\+-]|$)");
static final Pattern pFrac = Pattern.compile("("+numberPatern+")/("+numberPatern+")$");

static double fracToDouble(String in) {

    Matcher mWhole = pWhole.matcher(in);
    Matcher mFrac = pFrac.matcher(in);
    double d = 0;
    if (mWhole.find()) {
        String whole = mWhole.group(1);
        d += Double.valueOf(whole);
    }
    if (mFrac.find()) {
        String num = mFrac.group(1);
        String den = mFrac.group(3);
        d += Double.valueOf(num) / Double.valueOf(den);
    }
    return d;
}

it will correctly return 1.625 for one and five eights if any of the components is specified as a valid java floating point value:

*

*"1 5/8"

*"1+5/8"

*"1e0 -500e-2/-0.00080e4"


text:
Q: Any dlopen flag to avoid name conflict? I have used RTLD_NOW flag in dlopen. The global variable declared in this library is getting clashed with variable(with same name) defined in other library. Do I need to set any other flag to avoid this conflicting issue? Not only variable, the function with same name also producing a conflict
RTLD_DEEPBIND- it looks within library first ahead of global symbols defined in other. But specifying this option also futile. Is there any other solution to avoid this issue?


text:
Q: How does Websphere implement DRS? I've read about Websphere's Data Replication Services (DRS), which is the backbone of its clustering services.
What I don't know is what is its implementation - how does it transfer data and reconcile possible differences? Is it based on RMI or JMS or something altogether different?

A: HAManager. Read more here and here.


text: Q: Autopilot white glove deployment install applications Right now we have multiple applications in Intune and when we enroll a computer the applications get installed depending on what group the user is a part of. So we want to implement the white glove deployment. Since with the white glove deployment the user doesnt have to login first how can we make sure that they get the right applications?


text:
Q: How to create a two-colored navbar? I'm currently working on a website and I need to have a wide navigation bar with only three links/"buttons" there. The problem is that all the so-called buttons are of different colours (attached a screenshot from the actual mockup):
Hence, I've applied the the dark yellow colour to the main navbar itself, so there's no problem with the first button (since it's supposed to be yellow), the second one also plays nicely, but the third one is naturally interrupted and the navbar background colour shows up about 200px in the right. I've tried to make a kind of hack by creating an empty navbar-right with the appropriate colour, height and width, but since the site is supposed to be responsive this navbar-right solution only creates additional trouble.
So here's my markup (I'm using the standard Bootstrap 3 navbar):

Achievements

Resources

Overall Points

And the CSS is as follows:
#mainav {
height: 100px;
border: none;
border-radius: 0;
background-color: #fec708;
}

#mainav li:first-child {
height: 100px;
padding-top: 25px;
margin-left: 120px;
width: 330px;
text-align: center;
background-color: #fec708;
}

#mainav li:nth-child(2) {
height: 100px;
padding-top: 25px;
width: 320px;
text-align: center;
background-color: #ff7e00;
}

#mainav li:nth-child(3) {
height: 100px;
padding-top: 25px;
width: 330px;
text-align: center;
background-color: #db0104;
}

#mainav li a {
font-family: "Open Sans", sans-serif;
color: #ffffff;
font-weight: 300;
font-size: 37px;
}

I'd appreciate if you could share your thought and possible workarounds regarding this particular problem.
Thanks!

A: If you know for certain that this will always remain three buttons and the second one is centered, you could just style the center button orange and set a background gradient to the navbar with 50% yellow and 50% red:
#mainnav {
    background-image: -webkit-gradient(
        linear,
        left top,
        right top,
        color-stop(0.5, #FEC908),
        color-stop(0.5, #DB0104)
    );
    background-image: -o-linear-gradient(right, #FEC908 50%, #DB0104 50%);
    background-image: -moz-linear-gradient(right, #FEC908 50%, #DB0104 50%);
    background-image: -webkit-linear-gradient(right, #FEC908 50%, #DB0104 50%);
    background-image: -ms-linear-gradient(right, #FEC908 50%, #DB0104 50%);
    background-image: linear-gradient(to right, #FEC908 50%, #DB0104 50%);
}


text:
Q: MySQL and index on sum I've got a table with some data. For simplicity it looks like:
id - auto_increment
c1 - int
c2 - int
created - date

There might be lots of  data
The way I get the data is such:
SELECT * FROM my_table WHERE created >= DATE_SUB(NOW(), INTERVAL 1 HOUR) ORDER by c1 + c2 DESC LIMIT 10
How to make index for c1 + c2? Is it possible? Should I add it, I mean will it slow the query?

A: The only index that is useful for
SELECT *            -- I assume many fields here
    FROM my_table
    WHERE created >= DATE_SUB(NOW(), INTERVAL 1 HOUR) -- useful
    ORDER by c1 + c2 DESC   -- expressions cannot be indexed
    LIMIT 10         -- does not matter

is
INDEX(created)

For more discussion on creating the optimal index, see my index cookbook.
Hot off the press:  5.7 can create and index materialized virtual columns, such as (c1+c2).  Hence, a composite index starting with that col and ending with created might be better in 5.7.

A: You can just create a index with both fields.
Something like:
ALTER TABLE my_table ADD INDEX sumC1C2 (c1,c2)