text:
Q: how to terminate ssl at ingress-gateway in istio? I am trying to experiment ssl connection in istio ingress gateway.
From here istio ssl gateway without termination, i assume that istio ingress gateway by default should terminate ssl.
I have installed istio with demo profile, via istioctl.
I have also installed my service svc1.
Apart from these, below are what my resources are with routng logic:
apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
  name: vs-gateway
  namespace: myns
spec:
  selector:
    istio: ingressgateway # use istio default controller
  servers:
  - port:
      number: 443
      name: https
      protocol: HTTPS
    tls:
      mode: SIMPLE
      serverCertificate: /etc/istio/ingressgateway-certs/tls.crt
      privateKey: /etc/istio/ingressgateway-certs/tls.key
    hosts:
    - "*"
---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: vs
  namespace: myns
spec:
  hosts:
  - "*"
  gateways:
  - vs-gateway
  http:
  - match:
    - uri:
        prefix: "/svc1/"
    rewrite:
      uri: "/"
    route:
    - destination:
        host: svc1
        port:
          number: 80

I found the Gateway url via this.
For experiment i had also enabled http on ingress gateway. That way curl http://172.17.0.2:<http_node_port> works with 200 response. Later i removed http from ingress gateway and kept only https (as https is my primary goal to be recieved by ingress gateway)
And then trying curl with https on gateway url. I get 503.
$ curl -ivk https://172.17.0.2:<https_node_port>/svc1/user
*   Trying 172.17.0.2...
* TCP_NODELAY set
* Connected to 172.17.0.2 (172.17.0.2) port 30278 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: /etc/ssl/certs
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* TLSv1.3 (IN), TLS handshake, Server hello (2):
* TLSv1.3 (IN), TLS Unknown, Certificate Status (22):
* TLSv1.3 (IN), TLS handshake, Unknown (8):
* TLSv1.3 (IN), TLS handshake, Certificate (11):
* TLSv1.3 (IN), TLS handshake, CERT verify (15):
* TLSv1.3 (IN), TLS handshake, Finished (20):
* TLSv1.3 (OUT), TLS change cipher, Client hello (1):
* TLSv1.3 (OUT), TLS Unknown, Certificate Status (22):
* TLSv1.3 (OUT), TLS handshake, Finished (20):
* SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384
* ALPN, server accepted to use h2
* Server certificate:
*  subject: C=US; ST=CA; O=Abc; CN=example.com
*  start date: Dec 31 08:22:32 2019 GMT
*  expire date: Jan 30 08:22:32 2020 GMT
*  issuer: C=US; ST=CA; O=Abc; CN=example.com
*  SSL certificate verify result: self signed certificate (18), continuing anyway.
* Using HTTP2, server supports multi-use
* Connection state changed (HTTP/2 confirmed)
* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
* TLSv1.3 (OUT), TLS Unknown, Unknown (23):
* TLSv1.3 (OUT), TLS Unknown, Unknown (23):
* TLSv1.3 (OUT), TLS Unknown, Unknown (23):
* Using Stream ID: 1 (easy handle 0x55c961626580)
* TLSv1.3 (OUT), TLS Unknown, Unknown (23):
> GET /svc1/user HTTP/2
> Host: 172.17.0.2:30278
> User-Agent: curl/7.58.0
> Accept: */*
>
* TLSv1.3 (IN), TLS Unknown, Certificate Status (22):
* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
* TLSv1.3 (IN), TLS Unknown, Unknown (23):
* Connection state changed (MAX_CONCURRENT_STREAMS updated)!
* TLSv1.3 (OUT), TLS Unknown, Unknown (23):
* TLSv1.3 (IN), TLS Unknown, Unknown (23):
< HTTP/2 503
HTTP/2 503
< content-length: 95
content-length: 95
< content-type: text/plain
content-type: text/plain
< date: Thu, 02 Jan 2020 08:13:49 GMT
date: Thu, 02 Jan 2020 08:13:49 GMT
< server: istio-envoy
server: istio-envoy

<
* Connection #0 to host 172.17.0.2 left intact
upstream connect error or disconnect/reset before headers. reset reason: connection termination

I also enabled sidecar istio proxy debuggin on svc pod sidecar. I got below logs
[Envoy (Epoch 0)] [2020-01-02 06:53:19.392][28][debug][filter] [external/envoy/source/extensions/filters/listener/original_dst/original_dst.cc:18] original_dst: New connection accepted
[Envoy (Epoch 0)] [2020-01-02 06:53:19.392][28][debug][filter] [external/envoy/source/extensions/filters/listener/tls_inspector/tls_inspector.cc:72] tls inspector: new connection accepted
[Envoy (Epoch 0)] [2020-01-02 06:53:19.392][28][debug][filter] [src/envoy/tcp/mixer/filter.cc:30] Called tcp filter: Filter
[Envoy (Epoch 0)] [2020-01-02 06:53:19.392][28][debug][filter] [src/envoy/tcp/mixer/filter.cc:40] Called tcp filter: initializeReadFilterCallbacks
[Envoy (Epoch 0)] [2020-01-02 06:53:19.392][28][debug][filter] [external/envoy/source/common/tcp_proxy/tcp_proxy.cc:204] [C88] new tcp proxy session
[Envoy (Epoch 0)] [2020-01-02 06:53:19.392][28][debug][filter] [src/envoy/tcp/mixer/filter.cc:133] [C88] Called tcp filter onNewConnection: remote 10.244.0.5:34148, local 10.244.0.16:3000
[Envoy (Epoch 0)] [2020-01-02 06:53:19.392][28][debug][filter] [external/envoy/source/common/tcp_proxy/tcp_proxy.cc:347] [C88] Creating connection to cluster inbound|80|serviceport|svc1.myns.svc.cluster.local
[Envoy (Epoch 0)] [2020-01-02 06:53:19.392][28][debug][pool] [external/envoy/source/common/tcp/conn_pool.cc:83] creating a new connection
[Envoy (Epoch 0)] [2020-01-02 06:53:19.392][28][debug][pool] [external/envoy/source/common/tcp/conn_pool.cc:364] [C89] connecting
[Envoy (Epoch 0)] [2020-01-02 06:53:19.392][28][debug][connection] [external/envoy/source/common/network/connection_impl.cc:711] [C89] connecting to 127.0.0.1:3000
[Envoy (Epoch 0)] [2020-01-02 06:53:19.393][28][debug][connection] [external/envoy/source/common/network/connection_impl.cc:720] [C89] connection in progress
[Envoy (Epoch 0)] [2020-01-02 06:53:19.393][28][debug][pool] [external/envoy/source/common/tcp/conn_pool.cc:109] queueing request due to no available connections
[Envoy (Epoch 0)] [2020-01-02 06:53:19.393][28][debug][conn_handler] [external/envoy/source/server/connection_handler_impl.cc:333] [C88] new connection
[Envoy (Epoch 0)] [2020-01-02 06:53:19.393][28][debug][connection] [external/envoy/source/common/network/connection_impl.cc:559] [C89] connected
[Envoy (Epoch 0)] [2020-01-02 06:53:19.393][28][debug][pool] [external/envoy/source/common/tcp/conn_pool.cc:285] [C89] assigning connection
[Envoy (Epoch 0)] [2020-01-02 06:53:19.393][28][debug][filter] [external/envoy/source/common/tcp_proxy/tcp_proxy.cc:541] TCP:onUpstreamEvent(), requestedServerName:
[Envoy (Epoch 0)] [2020-01-02 06:53:19.393][28][debug][filter] [src/envoy/tcp/mixer/filter.cc:143] Called tcp filter completeCheck: OK
[Envoy (Epoch 0)] [2020-01-02 06:53:19.395][28][debug][filter] [src/istio/control/client_context_base.cc:139] Report attributes: attributes {
  key: "connection.event"
  value {
    string_value: "open"
  }
}
attributes {
  key: "connection.id"
  value {
    string_value: "38a9b348-1730-4e0b-9664-fbbaeedd9215-88"
  }
[Envoy (Epoch 0)] [2020-01-02 06:53:19.395][28][debug][filter] [src/envoy/tcp/mixer/filter.cc:100] [C88] Called tcp filter onRead bytes: 664
[Envoy (Epoch 0)] [2020-01-02 06:53:19.396][28][debug][filter] [src/envoy/tcp/mixer/filter.cc:123] [C88] Called tcp filter onWrite bytes: 28
[Envoy (Epoch 0)] [2020-01-02 06:53:19.398][28][debug][filter] [src/envoy/tcp/mixer/filter.cc:123] [C88] Called tcp filter onWrite bytes: 0
[Envoy (Epoch 0)] [2020-01-02 06:53:19.398][28][debug][filter] [src/envoy/tcp/mixer/filter.cc:100] [C88] Called tcp filter onRead bytes: 34
[Envoy (Epoch 0)] [2020-01-02 06:53:19.398][28][debug][connection] [external/envoy/source/common/network/connection_impl.cc:527] [C88] remote close
[Envoy (Epoch 0)] [2020-01-02 06:53:19.398][28][debug][connection] [external/envoy/source/common/network/connection_impl.cc:193] [C88] closing socket: 0
[Envoy (Epoch 0)] [2020-01-02 06:53:19.398][28][debug][filter] [src/envoy/tcp/mixer/filter.cc:174] [C88] Called tcp filter onEvent: 0 upstream 127.0.0.1:3000
[Envoy (Epoch 0)] [2020-01-02 06:53:19.398][28][debug][filter] [src/istio/control/client_context_base.cc:139] Report attributes: attributes {
  key: "connection.duration"
  value {
    duration_value {
      nanos: 6151000
    }
  }
}
attributes {
  key: "connection.event"
  value {
    string_value: "close"
  }
}
at
[Envoy (Epoch 0)] [2020-01-02 06:53:19.398][28][debug][connection] [external/envoy/source/common/network/connection_impl.cc:104] [C89] closing data_to_write=34 type=0
[Envoy (Epoch 0)] [2020-01-02 06:53:19.398][28][debug][conn_handler] [external/envoy/source/server/connection_handler_impl.cc:88] [C88] adding to cleanup list
[Envoy (Epoch 0)] [2020-01-02 06:53:19.398][28][debug][filter] [src/envoy/tcp/mixer/filter.cc:35] Called tcp filter : ~Filter
[Envoy (Epoch 0)] [2020-01-02 06:53:19.399][28][debug][connection] [external/envoy/source/common/network/connection_impl.cc:589] [C89] write flush complete
[Envoy (Epoch 0)] [2020-01-02 06:53:19.399][28][debug][connection] [external/envoy/source/common/network/connection_impl.cc:193] [C89] closing socket: 1
[Envoy (Epoch 0)] [2020-01-02 06:53:19.399][28][debug][pool] [external/envoy/source/common/tcp/conn_pool.cc:124] [C89] client disconnected
[Envoy (Epoch 0)] [2020-01-02 06:53:19.399][28][debug][pool] [external/envoy/source/common/tcp/conn_pool.cc:238] [C89] connection destroyed

With the logs, it seems like ingress gateway is forwarding ssl request to svc. (please correct here if i am wrong)
So in the end, can anyone please help me out getting ssl terminated at ingress gateway, and forward plain http request to svc?

A: Based on this github issue and this istio documentation

Named service ports: Service ports must be named. The port name key/value pairs must have the following syntax: name: [-]. See Protocol Selection for more details.

Based on mockserver service
ports:
    - name: serviceport

I would recommend to change it to http/https like mentioned there and confirmed by community member who had same issue on github.
Manual protocol selection

Protocols can be specified manually by naming the Service port name: [-]. The following protocols are supported:

*

*grpc

*grpc

*web

*http

*http2

*https

*mongo

*mysql*

*redis*

*tcp

*tls

*udp

*These protocols are disabled by default to avoid accidentally enabling experimental features. To enable them, configure the corresponding Pilot environment variables.


text:
Q: lombok compile error in Android project using Intellij I am not able to compile and run my android project using Intellij IDE in which i have used the lombok plugin.
I have added the plugin to Intellij and my project also.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trying to nest React components I'm new to React.js and am trying to use it to build myself a website. What I'm trying to do is to nest a child component within a parent component; the parent component should be rendered in the main page with the child component nested inside. I've included an example below of my attempt.
My approach thus far has been to

*

*Create the child component in 'childComponent.js'

*Export that child component as 'childComponent'

*Import 'childComponent' to parent component

*Render 'childComponent' in that parent component

*Export that parent component as 'parentComponent'

*Import 'parentComponent' to 'index.js'

*Render 'parentComponent' in 'index.js'

The problem here is that 'childComponent' is never visible in my React app. Am I taking the wrong approach here? Is there a fundamental mechanic that I'm not understanding?
Thanks in advance!!
--
The child component (childComponent.js):
import React, { Component } from 'react';
import './childComponent.css';

class childComponent extends Component {
  render() {
    return (

        Hello World

    );
  }
}

export default childComponent

childComponent.css:
.child-component {
  width: 100vw;
  height: 300pt;
  background-color: #F4F4F4;
  display: flex block;
  justify-content: center;
  align-items: center;
  align-content: center;
}

The parent component (parentComponent.js):
import React, { Component } from 'react';
import childComponent from './childComponent.js';
import './parentComponent.css';

class parentComponent extends Component {
  render() {
    return (

        <childComponent></childComponent>

    );
  }
}

export default parentComponent;

The main page (index.js):
import React from 'react';
import ReactDOM from 'react-dom';
import parentComponent from './parentComponent';
import './index.css';

ReactDOM.render(
  <parentComponent/>,
  document.getElementById('root')
);

A: Your first, and maybe only, issue is that react components must start with a capital letter.

Capitalized types indicate that the JSX tag is referring to a React component. These tags get compiled into a direct reference to the named variable, so if you use the JSX  expression, Foo must be in scope.

From: https://facebook.github.io/react/docs/jsx-in-depth.html#html-tags-vs.-react-components
The comment advising removal of CSS and moving everything into one file is also good advice for debugging and the early stages of a React app.


text:
Q: Flatten JSON array into long form I am having trouble flattening a json array into the format that I need. It is a fairly complex json with nested parts for various sections - see a simplified version below.
{
"RESPONSE":{"@VersionID":"1.1","@ResponseID":"A0001"},
"SUMMARY": {
      "@PersonID": "Person01",
      "@_Name": "Attributes",
      "_DATA_SET": [
        {
          "@_Name": "Number of accounts",
          "@_Value": "27"
        },
        {
          "@_Name": "Average age of open accounts",
          "@_Value": "35"
        },
        {
          "@_Name": "Number of closed accounts",
          "@_Value": "4"
        }
                    ]
                   }
}

I have a dataset where one of the columns contains a json like the one above in each row. For each row, I want to parse the summary section (specifically _DATA_SET) into a long format so that I can eventually pivot each @Name into a different column.
Current data:

row_id | json_example
1      | json_example1
2      | json example2

Desired output:

row id | Number of accounts | Average age of open accounts | Number of closed accounts
1      | 27                 | 35                           | 4
2      | 27                 | 35                           | 4

I have tried the following code which will parse my json_example into various columns of which one of them is the summary column, but I can not figure out how to further parse that into various rows which I can then pivot into columns.
pd.json_normalize(df.json_example.apply(json.loads)) yields

RESPONSE.VersionID | RESPONSE.ResponseID | SUMMARY.@PersonID | SUMMARY.@_Name| SUMMARY._DATA_SET
                                                                               [{'@_Name': 'Number of accounts'...


text:
Q: Index based on the value of a converted unix timestamp in logstash I need to index records based on the value of a UNIX timestamp (seconds since epoch) field, however the index needs to be in the form of YYYY-MM-dd. However the value of the timestamp field needs to remain a UNIX timestamp.
So the question is two parts.

*

*How can I convert the timestamp file to YYYY-MM-dd without destroying the UNIX timestamp?

*How can I apply the YYYY-MM-dd value to the index?

Here is what I have so far.
input {
    tcp {
            port => 5000
    }
}

filter {
    csv {
            separator => "  " # <- this white space is actually a tab
            skip_empty_columns => true
            # other fields omitted for brevity
            columns => ["timestamp"]
    }

    #grok {
    #       match => {"indexdate" => "%{NUMBER:timestamp}"}
    #}

    date {
            match => ["timestamp", "YYYY-MM-DD"]
            target => "@timestamp"
    }

    mutate {
            # omitted for brevity
            remove_field => []
    }
}

output {
    elasticsearch {
            hosts => "elasticsearch:9200"
            index => "indexname-%{+YYYY-MM-dd}"
    }
}

I have made several different grok attempts but no luck so far.

A: Simply change your date filter like this and it should work. The pattern you use in the date filter should match the pattern of the field you're parsing, since you have epoch seconds, then the pattern should be UNIX:
date {
        match => ["timestamp", "UNIX"]
        target => "@timestamp"
}

Note that you might need to add a convert setting in your csv filter to make sure that the timestamp field is an integer
csv {
   ...
   convert => { "timestamp" => "integer" }
}


text:
Q: c# XmlDsig. Set signature elements inside root element I have an XML like this:
<raiz>
  <nro_orden>123</nro_orden>
  <datos>Dadada</datos>
</raiz>

I need to sign it with this format:
<raiz>
  <Signature>
   (...)
   <nro_orden>123</nro_orden>
   <datos>Dadada</datos>
 </Signature>
</raiz>

I have tried two ways (using enveloping and enveloped method). But with first method I get the signature elements in top of the data:
<Signature>
   (...)
   <Object Id="20150924105053">
    <raiz>
     <nro_orden>123</nro_orden>
     <datos>Dadada</datos>
    </raiz>
</Object>
</Signature>

And with second method (enveloped) I get the signature elements in the bottom of the data:
<raiz>
 <nro_orden>123</nro_orden>
 <datos>Dadada</datos>
 <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
 (...)
 </Signature>
</raiz>

I just need that the root element () wraps the whole XML (including signature). I know that after an XML is signed, there's no way to modify something or the signing gets corrupt. So, please if you have an idea to my problem let me know.
Thank you in advance for taking the time.

A: Well, I resolved it in a funny way. I didn't think it'll work but did (the external web service accepted it).
I converted the signed XML to string and concatenate it with  tag at the start and the end like this:
string some = "<raiz>"+ xmlSigned.ToString() + "</raiz>";

It didn't change any value of the sign. If it helps someone...


text:
Q: find difference in two arrays of objects using javascript I have two arrays that contain a list of "message" objects. Each message object has a property 'receivedTime'.
I can sort the two arrays by 'receivedTime' so that newest messages are first.
Now, using underscorejs (if applicable)...is there a way I can pop off the difference in the two arrays? The newer array will have newer messages than the original list.
I only want new messages that are not in the original array.
For some context, I can only get all messages from the API. so I need to keep doing that in a timer, and add any new messages to the table on the page (this part I can do, I just need the difference in the list from one call to the next).

A: What is format of recievedTime ? if it's timestamp then , How about saving last recievedTime and querying list to filter only new ones.
You can use pure javascript
var newones = items.filter( function(item){return (item.recievedTime>lastRecievedTime);} );

A: After sorting both arrays, pass them to for loop and check if value is in second array.
for(var i = 0; i < newMessages.length; i++) {
    if(Messages[i] == newMessages[i]) {
         newMessages.splice(i, 1);
    }
}

Else find length of Messages and remove that number of elements present in newMessages array.

A: Try using filter and then specifying a function that returns only those not in the original array, something along the lines of this:
_.filter(newer_array, function(message) {
    return _.contains(older_array,message);
});

A: Or, another option would be.. after sorting both arrays, find the receivedTime of the newest message in the "older" array, and then iterate through the "newer" array until you get to the receivedTime found earlier. Something along these lines...
var split = older[0].receivedTime
var difference = []

var i = 0
while(newer[i].receivedTime !== split) {
    difference.push(newer[i]);
}


text:
Q: Add name attr to generated  I am using this line of code:
initWords($('').addClass('word').text(data.word).appendTo('#wordBank'));

Along with creating a word I want too add name="WORD HERE" to the  tag.
I see that $(".word").attr("name"), but is this how I set the attr name to the span.word?

A: To set an attribute use 2 parameters:
$(".word").attr("name", "somevalue");

A: If you use
$(".word").attr("name")

you finds the name attribute of the first span in the page.
If you want to set a value using the following syntax:
1) Use "attr(key, value)" to set a single property to a value, the matched element(s):
$("img").attr("key", "value");

2) Use "attr(properties)" to set some attributes for the matched element(s):
$("img").attr({ key1: "value1", key2: "value2" });


text:
Q: Find something that is occupying lots of memory and not visible in `ps` or similar I have a VM that's having memory issues. One of the tasks I'd like to run in it is crashing with out-of-memory errors.
However, when it crashes, the system still stays memory starved. I'm not sure if this is just a process I'm missing, or an actual bug (this is in hyper-v, with the new kernel extensions that allow memory-ballooning for linux hosts, so it could very well be a genuine kernel bug).
durr@sqlbox:~$ free -h
             total       used       free     shared    buffers     cached
Mem:          3.1G       2.6G       541M        88K       7.4M        39M
-/+ buffers/cache:       2.5G       588M
Swap:         1.0G       6.2M       1.0G

Free tells me that it's not just cached, there is actually something that appears to be live taking up 2.6G of memory.
However, looking through the output of PS sorted by virtual size is not enlightening:
durr@sqlbox:~$ ps -e ax -o pid,vsz,comm | sort --numeric-sort --key=2
[ ... snip ... ]
  PID    VSZ COMMAND
   96      0 rcuob/23
   97      0 rcuob/24
   98      0 rcuob/25
   99      0 rcuob/26
 1124   4368 acpid
59863  10016 ps
 1031  15668 upstart-file-br
 1047  15820 getty
 1050  15820 getty
 1055  15820 getty
 1056  15820 getty
 1058  15820 getty
 1167  15820 getty
 1023  15920 upstart-socket-
 1076  19140 atd
 1099  19188 irqbalance
  428  19476 upstart-udev-br
59864  21860 sort
59267  22644 bash
59234  22664 bash
59280  22808 bash
 1075  23656 cron
59261  26928 screen
59279  27380 htop
59262  28472 screen
    1  33776 init
  749  39240 dbus-daemon
  816  43452 systemd-logind
  432  51348 systemd-udevd
 1090  61364 sshd
  871 255844 rsyslogd
59184 269028 sshd
59233 269028 sshd

So the biggest memory consumer is sshd, and it's using..... 269K? Where is all my memory going?
Looking into /proc/meminfo shows:
durr@sqlbox:~$ cat /proc/meminfo
MemTotal:        3266904 kB
MemFree:          554228 kB
Buffers:            7596 kB
Cached:            41104 kB
SwapCached:         3032 kB
Active:            32552 kB
Inactive:          34292 kB
Active(anon):      13224 kB
Inactive(anon):     5008 kB
Active(file):      19328 kB
Inactive(file):    29284 kB
Unevictable:           0 kB
Mlocked:               0 kB
SwapTotal:       1044476 kB
SwapFree:        1038084 kB
Dirty:                 0 kB
Writeback:             0 kB
AnonPages:         15656 kB
Mapped:             9196 kB
Shmem:                88 kB
Slab:              33488 kB
SReclaimable:      14532 kB
SUnreclaim:        18956 kB
KernelStack:        2352 kB
PageTables:         2748 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:     2677928 kB
Committed_AS:      56148 kB
VmallocTotal:   34359738367 kB
VmallocUsed:       34360 kB
VmallocChunk:   34359695660 kB
HardwareCorrupted:     0 kB
AnonHugePages:         0 kB
HugePages_Total:       0
HugePages_Free:        0
HugePages_Rsvd:        0
HugePages_Surp:        0
Hugepagesize:       2048 kB
DirectMap4k:       44456 kB
DirectMap2M:     3491840 kB

Obviously, it appears that something has Vmalloced an enormous amount of memory, but I'm not sure if that's relevant.

A: It may be possible that your program used shared memory and didn't clean that up.
There are three variants of shared memory on linux:
1.) POSIX shared memory (the one implemented by glibc) is accessible via files on the tmpfs pseudo-filesystem and are usually mounted by the system on places like /dev/shm, /run, /run/shm or /run/lock. The best way to find out for sure is to enter mount | grep -E '^tmpfs' (more portable) or grep -E '^tmpfs' /proc/mounts (best for linux) in a shell.
Note that it is possible for a process to call unlink() on a mmap()'ed file in shared-memory, rendering the file inaccessible via filename (e.g. one needs a previously allocated file handle to continue accessing it). However, unlink()ed files are usually deleted upon exiting of all processes that had it open()'ed - maybe if your program finished, there still is another process still holding a handle to it.
2.) SysV IPC shared memory, which is not visible via the tmpfs pseudo-filesystem, but rather via /proc/sysvipc/shm, linux syscalls (only if you are a hacker), its libc wrapper or, most recently, via ipcs -m -p -[tclu]. You need to find a matching process ID in any of these lists, and then inspect that process further.
3.) Anonymous mapped shared memory, in which case the memory is not backed by any file, but rather the memory is initially shared between a process and all of its children. AFAIK such anonymous mapped shared memory is freed when the process that mmap()'ed it exit()s. So, in case your program terminated and all of its child processes did as well, they shouldn't AFAIK further occupy any memory.


text:
Q: How to limit bandwidth of file upload? I am trying to upload a file to Microsoft Azure server using their Android mobile services. But the problem is during upload, a single file upload eats off all the available bandwidth.
Is there any way to limit bandwidth of single upload?
What I have tried?
Azure service can take files in chunks. So I defined chunk size to 50kb and max bandwidth limit per connection is 100kb/s
{
  t1=geTimeInMilliseconds();
  uploadChunk();
  t2=geTimeInMilliseconds();
  t3=t2-t1;
  if(t3<500ms){
   sleep(500-t3);
  }
}

I am sure this is not the perfect way of doing it. Any suggestion on this would be a great help..

A: Starting from the principle of I/O streaming, the simple thinking of the bandwidth limit for uploading as follow.

*

*Assumption for the speed limit of I/O streaming is M Byte/sec, then the cost time of sending the N Byte data is N/M sec.

*Assumption for sending the N Byte data at now, then the cost time should be N/M s. However, the actual cost time is T s, so the sending thread should sleep (N/M - T) sec for implementing the limit speed.

Here is a sample code in Java as reference.
int BUF_SIZE = 1024;
long speed = 12800L; // 100 Kbit/s = 100 * 1024 / 8 Byte/s = 12800 Byte/s
File file = new File("<file path>");
OutputStream outs = ...;
FileInputStream fis = new FileInputStream(file);
byte[] buf = new byte[BUF_SIZE];
long cur = 0L;
long startTime = System.currentTimeMillis();
while((n = fin.read(buf)) != -1) {
    cur += n;
    out.write(buf);
    if(cur > speed) {
        long idleTime = (cur-speed)*1000/speed;
        Thread.sleep(idleTime);
        cur = 0;
        startTime = System.currentTimeMillis();
    }
}
fin.close();
outs.flush();
outs.close();


text:
Q: Sort posts according to a numeric value entered with ACF I've tried a little bit of everything, but I still can't find the right solution.
I need to sort my posts according to a numeric value that is entered in each post. I'm using the following PHP code, but it's not working:
$args['meta_query'] = array(
    array(
        'key' => 'key',
        'type' => 'numeric',
    )
);

I also tried this code:
$args['meta_key'] = 'costo_attrazioni_ridotti_18_25';

Then of course I have these other values in the args as well:
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$args=array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'posts_per_page' => 10,
        'meta_key' = 'costo_attrazioni_ridotti_18_25',
        'order' => 'ASC',
        'orderby' => 'meta_value_num',
        'paged' => $paged,
);
$the_query = new WP_Query( $args );
if ($the_query->have_posts()):
    while ($the_query -> have_posts()) : $the_query -> the_post();?>
        ...
    endwhile;
endif; unset($the_query); wp_reset_query();

How can I solve it? Thank you.


text:
Q: Slow transfer speed between two Windows 7 computers over local wifi? I have two PCs running Win7 sitting next to each other. They both have identical TP-Link WiFi PCI cards and are connected to an Enkom router which is in the same room as the computers (which claims to have 802.11g WiFi).
I've set file sharing between the computers (not Homegroup), set "Enable file sharing for devices that use 40- or 56-bit encryption" in Advanced file sharing settings, disabled TCP autotuning and turned off Remote Differential Compression.
Regardless of the changes I made, I can't get the transfer rate between the computers to go above 350KBps either way (when a copy dialog is initially opened, it starts at 512KBps but that immediately drops below 400KBps).
Is there anything else I can try doing? My Internet download speeds are literally faster (over Wifi) so this makes no sense.


text:
Q: Buttons going below screen in landscape mode I am learning iphone app development and I am using swift. I took the lynda tutorial and I have created a very basic UI which is View Controller > View .
In the View I added a segmented control, two buttons(horizontal, facing each other), three labels, one textarea and two other buttons(horizontal, facing each other).
So I have these UIcomponents arranged vertically and I used 'Reset to suggested constraints' and made all the buttons equal width and equal height and everything is fine in potrait mode  but as soon as I go to landscape mode  the last two buttons disappear, if I add a constraint from bottom edges the whole UI gets messed up i.e. only one label and part of an upper button appears.
What should I do to make all the UI components visible both in potrait and landscape mode?

A: There are many ways to go about this. I've set up a github project to show you one way to achieve it.
Short resume of what I did manually without the help of the Interface Builder:

*

*I've pinned the segmented control to the left, top and right of the parent view

*The red button below has a vertical constraint to the segmented control and a leading constraint to the parent view. It also als a horizontal space constraint to the green button

*The green button has a trailing constraint to the parent view, top aligned to the red button and widths set to equal to the red button.

This setup ensures, that the segmented control is responsible for specifying the distance to the top of the parent view and the red button specifies the width of itself and the green button (test it, by changing the value of the horizontal space constraint)
I've turned the same principle upside down. So the views in the bottom are always pinned to the bottom. But as I said, there are many ways to achieve this. You could also create 3 container views for the elements in the top, center and bottom and pin those to the top, center and bottom.
The running app looks like this:

A: If you would like to display your content differently in landscape mode, it is possible (and most likely preferable) to create an alternate landscape interface.
Quoting the Apple developer's page on the subject:
"To support an alternate landscape interface, you must do the following:

*

*Implement two view controller objects. One to present a portrait-only
interface, and the other to present a landscape-only interface.

*Register for the UIDeviceOrientationDidChangeNotification notification.
In your handler method, present or dismiss the alternate view controller based on the current device orientation."
For more information about this, check out this apple developer page and scroll down to "creating an alternate landscape interface".
https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/RespondingtoDeviceOrientationChanges/RespondingtoDeviceOrientationChanges.html


text:
Q: extjs: Grid Buffered Scrolling with Row Editing/Deletion/Addition Has anybody seen any sample of extjs grid with buffered scrolling with new row, row editing and row deletion support?
Can CellEditing and RowEditing plugins be used with Buffered Scrolling?
Is row editing even possible with buffered scrolling?
Cheers,
Avi

A: I had opened a thread at Ext forum and got the response, insertion and deletion is NOT supported with buffered scrolling.
http://forums.ext.net/showthread.php?27969-Buffered-Scrolling-with-Row-Editing-Deletion-Addition&p=124559&posted=1#post124559
Cheers,
Avi

A: I changed this example http://docs.sencha.com/extjs/4.2.2/#!/example/grid/infinite-scroll.html, added the row editor. Open this example: http://jsfiddle.net/zAnZg/1/, click on record, change values and then click "Update"

Ext.require([
    'Ext.grid.*',
    'Ext.data.*',
    'Ext.util.*',
    'Ext.grid.plugin.BufferedRenderer'
]);

Ext.onReady(function(){
    Ext.define('ForumThread', {
        extend: 'Ext.data.Model',
        fields: [
            'title', 'forumtitle', 'forumid', 'username', {
                name: 'replycount',
                type: 'int'
            }, {
                name: 'lastpost',
                mapping: 'lastpost',
                type: 'date',
                dateFormat: 'timestamp'
            },
            'lastposter', 'excerpt', 'threadid'
        ],
        idProperty: 'threadid'
    });

    // create the Data Store
    var store = Ext.create('Ext.data.Store', {
        id: 'store',
        model: 'ForumThread',
        remoteGroup: true,
        // allow the grid to interact with the paging scroller by buffering
        buffered: true,
        leadingBufferZone: 300,
        pageSize: 100,
        proxy: {
            // load using script tags for cross domain, if the data in on the same domain as
            // this page, an Ajax proxy would be better
            type: 'jsonp',
            url: 'http://www.sencha.com/forum/remote_topics/index.php',
            reader: {
                root: 'topics',
                totalProperty: 'totalCount'
            },
            // sends single sort as multi parameter
            simpleSortMode: true,
            // sends single group as multi parameter
            simpleGroupMode: true,

            // This particular service cannot sort on more than one field, so grouping === sorting.
            groupParam: 'sort',
            groupDirectionParam: 'dir'
        },
        sorters: [{
            property: 'threadid',
            direction: 'ASC'
        }],
        autoLoad: true,
        listeners: {

            // This particular service cannot sort on more than one field, so if grouped, disable sorting
            groupchange: function(store, groupers) {
                var sortable = !store.isGrouped(),
                    headers = grid.headerCt.getVisibleGridColumns(),
                    i, len = headers.length;

                for (i = 0; i < len; i++) {
                    headers[i].sortable = (headers[i].sortable !== undefined) ? headers[i].sortable : sortable;
                }
            },

            // This particular service cannot sort on more than one field, so if grouped, disable sorting
            beforeprefetch: function(store, operation) {
                if (operation.groupers && operation.groupers.length) {
                    delete operation.sorters;
                }
            }
        }
    });

    function renderTopic(value, p, record) {
        return Ext.String.format(
            '{0}',
            value,
            record.data.forumtitle,
            record.getId(),
            record.data.forumid
        );
    }

    var rowEditing = Ext.create('Ext.grid.plugin.RowEditing', {
        clicksToMoveEditor: 1,
        clicksToEdit: 1,
        autoCancel: false,
        listeners:{
            edit: function(editor, e){
                Ext.MessageBox.alert(
                    'Just create Ajax recuest here. Post changed record:
' +
                    Ext.JSON.encode(e.record.data)
                );
            }
        }
    });

    var grid = Ext.create('Ext.grid.Panel', {
        width: 700,
        height: 500,
        collapsible: true,
        title: 'ExtJS.com - Browse Forums',
        store: store,
        loadMask: true,
        selModel: {
            pruneRemoved: false
        },
        multiSelect: true,
        viewConfig: {
            trackOver: false
        },
        features:[{
            ftype: 'grouping',
            hideGroupedHeader: false
        }],
        plugins: [rowEditing],
        // grid columns
        columns:[{
            xtype: 'rownumberer',
            width: 50,
            sortable: false
        },{
            tdCls: 'x-grid-cell-topic',
            text: "Topic",
            dataIndex: 'title',
            flex: 1,
            renderer: renderTopic,
            sortable: true,
            editor: {
                allowBlank: false
            }
        },{
            text: "Author",
            dataIndex: 'username',
            width: 100,
            hidden: true,
            sortable: true
        },{
            text: "Replies",
            dataIndex: 'replycount',
            align: 'center',
            width: 70,
            sortable: false,
            editor: {
                xtype: 'numberfield',
                allowBlank: false,
                minValue: 1,
                maxValue: 150000
            }
        },{
            id: 'last',
            text: "Last Post",
            dataIndex: 'lastpost',
            width: 130,
            renderer: Ext.util.Format.dateRenderer('n/j/Y g:i A'),
            sortable: true,
            groupable: false,
            editor: {
                xtype: 'datefield',
                allowBlank: false,
                format: 'm/d/Y',
                minValue: '01/01/2006',
                minText: 'Cannot have a start date before the company existed!',
                maxValue: Ext.Date.format(new Date(), 'm/d/Y')
            }
        }],
        renderTo: Ext.getBody()
    });
});


text:
Q: Distinct count of users with net balance > 0 My data looks like this.

I tried with below DAX but I am getting an error:
Distinct Users = CALCULATE(DISTINCTCOUNT(MyList[User]),SUM(MyList[Balance]) > 0)

Error message: A function 'SUM' has been used in a True/False
  expression that is used as a table filter expression. This is not
  allowed.

A: You could do this by using a calculated column to evaluate the balance and then use that to calculate the measure:
Column:
Distinct Users Test =
        VAR User = MyList[User]
RETURN CALCULATE(SUM(MyList[Balance]),
                FILTER(MyList,MyList[User]=User))

Measure:
Distinct Users = CALCULATE(DISTINCTCOUNT(MyList[User]),
                            MyList[Distinct Users Test]>0)

Hope this helps.
Edit: If you want it as a single measure, You can make use of summarize and calculatetable:
Distinct Users New = COUNTX(
                            CALCULATETABLE(SUMMARIZE(MyList,MyList[User],
                                            "Bal",
                                            SUM(MyList[Balance]))),
                            [Bal]>0)


text:
Q: Accessing object property in Firebase Realtime Database ruleset I store data about trips in a Firebase Realtime Database. I have defined some user groups. I want only users from group "vips" to read trips that have freePlaces == 0 and all the others to read the remaining trips.
I tried to set such access rules:
{
  "rules": {
      "trips":{
          "$trip":{
            ".read": "root.child('users').child('vips').child(auth.uid).exists() || $trip.child('freePlaces') > 0"
           }
       }
   }
}

but Firebase tells me $trip has no method/property 'child'.
I tried to do it in a different way
{
  "rules": {
      "trips":{
          "$trip":{
            ".read": "root.child('users').child('vips').child(auth.uid).exists() || root.child('trips').child($trip).child('freePlaces') > 0"
           }
       }
   }
}

but Firebase says Invalid > expression: left operand must be a number or string.
What went wrong?

A: I recommend playing close attention to the type of each expression in your rules:

*

*$trip is a string, which explains why you can't call .child on it. If you want to get a child of the node, you can just do: data.child('freePlaces').

*root.child('trips').child($trip).child('freePlaces') is a location in the database, which can't be compared with >. If you want the value of the node, use .val().

So combining these, your first snippet should be:
data.child('freePlaces').val() > 0


text:
Q: Run a script based on sheet names for different sheets depending on another script yesterday I posted my first issue (Archive rows from different sheets and remove them to initial position (to initial sheet) when I want to unarchive (google sheets)) that has been fixed (thanks again if you are reading me).
I completed my script by the following code (starting at When a client is mentioned in Col3, fill automatically Col23 or W by the PM name).
function onEdit(event) {
  // assumes source data in sheet named Elisa-Miriam-Victor
  // target sheet of move to named Archive
  // getColumn with check-boxes is currently set to column 2 or B
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = event.source.getActiveSheet();
  var r = event.source.getActiveRange();

  // Archive a project with checked box from Archive Sheet
 if((s.getName() == "Elisa"||s.getName() == "Miriam" )&& r.getColumn() == 2 && r.getValue() == true) { // copy past every time a new PM-sheet is added
    var row = r.getRow();
    var numColumns = s.getLastColumn();
    var targetSheet = ss.getSheetByName("Archive");
    var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
    s.getRange(row, 1, 1, numColumns).moveTo(target);
    s.deleteRow(row);
  }
  // Unarchive a project from Archive sheet to respective owner
  else if(s.getName() == "Archive" && r.getColumn() == 2 && r.getValue() == false) {
    var row = r.getRow();
    var nameColumn = 23;
    var name = s.getRange(row, nameColumn).getValue();
    var numColumns = s.getLastColumn();
    var targetSheet = ss.getSheetByName(name);
    var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
    s.getRange(row, 1, 1, numColumns).moveTo(target);
    s.deleteRow(row);

    // When a client is mentioned in Col3, fill automatically Col23 or W by the PM name
    {
  var s = SpreadsheetApp.getActiveSheet();
  var data = s.getRange("C9:C").getValues();
  var data_len = data.length;
  for(var i=8; i<data_len; i++) {
  if(data[i][0].length == 0) {
    s.getRange(i+1,23).setValue("");
  } else {
    s.getRange(i+1,23).setValue("Miriam");
  }
  }
}
}
}

So from now, if, on Miriam's sheet, there is a new client mentioned in Col3, Col 23 is automatically filled by her name. But I need to standardize this part of the script because every new employee has his own sheet (his name) and for every employee's sheet, anytime Col3 is filled, I need to automatically fill Col23 under the name of the sheet.
Does anyone have an idea of how to write the script for Elisa and Miriam for example?
Thank you for your help!

A: Objective:
Write the Sheet's name if there is a new client added in Col3
Procedure:
You can check the last row of Col23 to see if it's empty and copy the name of the Sheet. The change would only happen if someone manually edits the Col3.
Code:
This is an example. You would have to integrate it into your current code.
function onEdit(event){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = event.source.getActiveSheet();
  var r = event.source.getActiveRange();

  var lastRow = s.getLastRow();
  var col23 = s.getRange(lastRow, 23).getValue();

  if (r.getRow() == lastRow && r.getColumn() == 3 && col23 == ""){

    s.getRange(lastRow, 23).setValue(s.getSheetName());
 }
}

References:

*

*getSheetName()

*getLastRow()

*setValue()


text:
Q: vb.net DateTimePicker remove time 12:00:00 AM im having a problem when viewing date on my listview.
on my SQL its okay that on my column "2016-28-11" that is fine
but when i view it on my listview in vb.net it said that "2016-28-11 12:00:00 am"
on my datetimepicker
Value: 11/28/2016
custom format: yyyy-MM-dd
format: custom
when i save the date it adds that time. can anyone help me?

A: When you add the date in your listview just use something like that:
 Dim NewItem As New ListViewItem
 NewItem.Text = "My Item"
 NewItem.SubItems.Add(mydate.tostring("yyyy-MM-dd"))
 ListView1.Items.Add(NewItem)

Just keep in mind mydate.tostring("yyyy-MM-dd") where mydate is a datetime.
Considerate your comments, here is the code:
.SubItems.Add(ds.Tables("studnum").Rows(i).Item(4).ToString)
Dim MyDate As DateTime = CDate(ds.Tables("studnum").Rows(i).Item(5).ToString)
.SubItems.Add(MyDate.ToString("yyyy-MM-dd"))


text:
Q: Huge Block Time in Profiler in Azure App Service Response My Web App is running on Basic 2 Tier in Azure. But from past few days I'm Getting Huge Block Time when seen in the profiler. So, Is anyone having any idea about there is so much block Time in request processing.
Profiler Image


text:
Q: how to get the inner html of the title i was trying to link my page to another page without refreshing the page and i did it successfully, but the title of the 2nd page did not change it was still the title of the first page. the 2nd page has its own title tag that contains the title of the page, but it is not reflecting when i redirect it, how can i fix that.
here is my code:
let script = document.createElement("script");
script.src = "https://code.jquery.com/jquery-3.4.1.min.js";
script.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(script);

function goto(name_of_page) {

  // go get the page and paste it on the current page
  var request = new XMLHttpRequest();
  request.open("GET", name_of_page, true);
  request.onload = function() {
    if (request.status >= 200 && request.status < 400) {
      let resp = request.responseText;

  let link = name_of_page.split(".");
  let name = link[0];
  $("body").load(`${name_of_page}`);

  if (
    location.href.includes("localhost") ||
    location.href.includes("www")
  ) {
    window.history.pushState(name_of_page, "Title", name);
    console.log("has www or localhost");
  } else {
    window.history.pushState(name_of_page, "Title", name_of_page);
    console.log("does not have www");
  }

}
};
 request.send();

}

A: You can parse your loaded data to an HTML Content Template, so once you have the data:
/*...*/

let resp = request.responseText;

const tpl = document.createElement('template');
tpl.innerHTML = resp;

document.title = tpl.content.querySelector('title').textContent;

/*...*/


text:
Q: How to test event based rule created using DTM? I have created a event based rule and on submit have given the ID of the submit button. Now my question is how to test event based rule? I test page load rule using Adobe DTM switch. But event based rules doesn't show there. Can any one please tell me how to test this?

A: Initialization
They are event based, so they appear after they are initialized, so after submit button click.
Form behavior
The question is, what happens after you submit button. Redirect? If yes, you have to add some delay before redirect. If not and only AJAX happens, then use DTM SWITCH as usual and you will see it in console. You can either extend console log by _satellite.notify("My custom event base rule",1);

A: As was mentioned, the DTM switch is an excellent (free) tool to help with your validation. Using _satellite.notify at the time of the event trigger will allow you to see what's happening in the browser.
I actually use a short-hand global wrapper function that uses _satellite.notify but doesn't require me to write it out each time I want to use it.
You can read about it here:
Three quick tips for validating your Adobe DTM implementation
Hope this helps.

A: Also, if you don't have access to DTM Switch, or don't like plugins, Chrome or Firefox, you can call
_satellite.setDebug(true);

in your browser developer tools console. It accomplishes the same thing as turning the DTM Switch 'Debug' button to 'On'.


text:
Q: update Dictionary that contains a various key and struct from any type I'm trying to convert string collection type to dictionary that contain various types of keys and values(the value will be a struct most of the time.
each string in the string collection will contain the key in the first element and the rest of the string will contain the struct elements(The Values of the Dictionary), of course that the string will contain the right type of each element in the struct we just need to decode the struct elements' type...
i tried to do so but i ran into dead end and no possibility...
i tried to google it but my case is pretty hard because it suppose to match to a lot of cases in my program...
this is what i tried to do
     private static void LoadDictionaryFromString<TKey,TValue>(ref IDictionary<TKey,TValue> argetDict,StringCollection SourceString)
    {
        TargetDict.Clear();

        foreach(string strData in SourceString)
        {
            string[] strElements = strData.Split(';');
            int m = 1;
            // i must initialize
            object Key = new object();  // when i try =>   TKey Key = new TKey() it's not working
            object Value = new object();   // the same like previous line...
            foreach (var field in typeof(TValue).GetFields())
            {
                // I can't work this out.... i stuck here
                // in this line i'm getting an exception -> out of index...
                TypeDescriptor.GetProperties(TargetDict.Values)[m].SetValue(Value , strElements[m]);
            }
            TypeDescriptor.GetProperties(TargetDict.Keys)[0].SetValue(Key, strElements[0]);

            TargetDict.Add((TKey)Key,(TValue)Value);
        }
    }

I hope some one can help me with this because I struggled with this a lot.
Thanks
I'm adding a sample for the input of the string collection,
the string collection has been saved before from the same dictionary,
so let's say the current dictionary contains the key and value like this:
 ,
the key is the OrderID
the sample struct contain the fields:
      struct sampleStruct
      {
          string StockName;
          int Quantity;
          int StockType;
          enum_Status StockStatus;       // the declaration: enum enum_Status { Accepted, Cancel, Executed }
          double Price;
          DateTime TradeTime;
      }

now let's say we have two records that contain the values:
OrderID = 155 (for the key part) and for the struct : Apple , 200, 1, Accepted, 250, 12/05/2013 10:00:00
OrderID = 156 (for the key part) and for the struct : IBM, 105, 1, Executed, 200, 12/05/2013 12:34:10

so the saved string collection will be name
StringCollection strCollection;
"155;Apple;200;1;Accepted;250;12/05/2013 10:00:00
156;IBM;105;1;Executed;200;12/05/2013 12:34:10"

now, after a while i have a saved string collection from the kind above and i know that it contains the specified struct above so i run the function like this:
    IDictionary<int, sampleStruct> DictToTarget=new IDictionary<int, sampleStruct>();

    // the Dictionary will be cleared and will contain the data as saved in the string collection
    // the stringCollection will contain the data above
    LoadDictionaryFromString<int, sampleStruct>(ref DictToTarget, strCollection);

I hope that's enough data to help me.
Thanks again.


text:
Q: C++ Syntax Error I'm getting this error:
prog.cpp:1:5: error: expected unqualified-id before '[' token

Form this code:
int [] quick_srt(int array[], int low, int n){

That's the problem, please?
EDIT
int [] quick_srt(int array[], int low, int n){
int lo = low;
int hi = n;
comp++;
if (lo >= n){ // lo is greater then or equal to n
    return array;
}
int mid = array[(lo + hi) / 2];  //Using mid as pivot
comp++;
while (lo < hi){ //lo is less then hi

    comp++;
    while (lo < hi && array[lo] < mid){ //lo less than hi AND array[lo] less than mid
        lo++;
        comp++;
    }

    comp++;
    while (lo < hi && array[hi] > mid) {//lo less than hi AND array[lo] greater than mid
        hi--;
        comp++;
    }

    comp++; //for if
    comp++; //for else
    if(array[lo] == array[hi]){
    break; //for duplicate items
    }
    else if (lo < hi) { // less than
        int T = array[lo];
        array[lo] = array[hi];
        array[hi] = T;
        swaps++;
    }
    comp++;
}
comp++;
if (hi < lo) { //hi is less than lo
    int T = hi;
    hi = lo;
    lo = T;
}
quick_srt(array, low, lo); //recrusie call
quick_srt(array, lo == low ? lo+1 : lo, n); //re-call, if lo = low, increment lo else pass lo and n
return array;
  }

A: You can't return an array from a function.  the int array[] in the parameter list is just syntactic sugar for int *array, and there's no analogue for the return value.  If you want to return a pointer, you'll need to do so explicitly:
int *quick_srt(int array[], int low, int n);

or, equivalently:
int *quick_srt(int *array, int low, int n);

A: int [] is only valid for function arguments. I'd suggest you do this instead:
void quick_srt(std::vector<int>& array, int low)

You don't need the n argument. USe `array.size() instead.

A: One more way is use
void quick_srt(int * array, int low)
I would suggest go with vector its lot more easy


text:
Q: Custom methods in adapter are not resolving in android I have 2 methods inside of adapter class.
addValues(brandMap);
setBrandMap(brandMap);

that I'm trying to call after async call. However, the compiler is complaining that it cannot resolve these methods. What is the issue?
This is complete class.
public class FragmentBrandList extends ListFragment {

    private String TAG =  getClass().getSimpleName();
    private Map<String, Brand> brandMap = new ConcurrentHashMap<>();
    private RecyclerView.Adapter adapter;
    private FirebaseDatabase database = FirebaseDatabase.getInstance();
    private RecyclerView recyclerView;

    private Query query = database.getReference("brands").orderByChild("name");

    public FragmentBrandList() {
    }

    public static FragmentBrandList newInstance(int num) {
        FragmentBrandList f = new FragmentBrandList();
        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putInt("num", num);
        f.setArguments(args);

        return f;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.recycler_list, container, false);
        recyclerView = (RecyclerView) v.findViewById(R.id.recycler_view);

        RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 3);
        RecyclerView.setLayoutManager(mLayoutManager);
        adapter = new FragmentBrandList.MyAdapter(Utility.getBrandMap(), getActivity());
        recyclerView.setAdapter(adapter);

        recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {

            @Override
            public void onClick(View view, int position) {
                Brand brand = Utility.getBrands().get(position);
                Intent intent = new Intent(getActivity(), ActivityProductList.class);
                intent.putExtra("BrandId", brand.getId());
                startActivity(intent);
            }

            @Override
            public void onLongClick(View view, int position) {

            }
        }));

        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
                    Brand brand = dataSnapshot1.getValue(Brand.class);
                    brandMap.put(brand.getId(), brand);
                }
                Utility.setBrandMap(brandMap);

                adapter.addValues(brandMap);
                adapter.setBrandMap(brandMap);
            }

            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                Log.w(TAG, "Failed to read value.", error.toException());
                Utility.displayToast("Failed to read value." + error.toException());
            }
        });
        return v;
}

Adapter class
private class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

        private List<Brand> brandList = new ArrayList<>();
        private Context context;

        public class MyViewHolder extends RecyclerView.ViewHolder {
            ImageView imageView;
            public MyViewHolder(View view) {
                super(view);
                imageView = (ImageView) view.findViewById(R.id.thumbnail);
            }
        }

        public MyAdapter(Map<String, Brand> brands, Context context) {
        //public MyAdapter(List<Brand> brands, Context context) {
            this.brandList = new ArrayList<>(brandMap.values());
            //this.brandList = brands;
            this.context = context;
        }

        public void setBrandMap(Map<String, Brand> brandMap){
            this.brandList = new ArrayList<>(brandMap.values());
            notifyDataSetChanged();
        }

        public void addValues(Map<String, Brand> brands){
            brandList.clear();
            brandList.addAll(brands.values());
            notifyDataSetChanged();
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.card_brand, parent, false);

            return new MyViewHolder(itemView);
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            if (brandList != null && brandList.size() > 0) {
                Brand brand = brandList.get(position);
                Glide.with(context).load(String.valueOf(brand.getImage()))
                        .error(R.drawable.placeholder)
                        .placeholder(R.drawable.placeholder)
                        .into(holder.imageView);
            }
        }

        @Override
        public int getItemCount() {
            return brandList.size();
        }
}

A: You have declared your adapter field as:
private RecyclerView.Adapter adapter;

That means wherever you use it, you'll see it as just a RecyclerView.Adapter, which doesn't have your custom methods on it. It doesn't matter that you've assigned there a subclass of RecyclerView.Adapter that has extra methods. It is because you might've assigned there a different subclass that didn't have those methods.
If you want to use your custom methods then change the declaration to:
private MyAdapter adapter;

Then you can use all methods declared in MyAdapter and inherited from superclasses. The tradeoff is that you cannot assign there any other subclass of RecyclerView.Adapter, but thanks to that compiler can know you can always use your extra methods.

A: The problem is this line.
private RecyclerView.Adapter adapter;

As you are holding your custom adapter object in the Base reference, hence those methods of your custom adapter is not visible to you. Change the reference to the type of your Custom Adapter and it should work fine.


text:
Q: Design Patterns: Should a factory update and delete too? I am currently learning about design patterns. I use a factory to get data from a database, create an object, and return that. But what kind of design patterns can I use when I want to update or delete the data in the database? Can the factory do an update and delete too, or exists another design pattern for that? An example in Java or PHP would be helpful.
Thanks for your support!

A: No, not really. Factories build things, and that's all. In cases where the ActiveRecord pattern is used then entities have a save method. With ORMs like Hibernate the session persists entities.
In Java what happens is you have a SessionFactory (or EntityManagerFactory), that creates Hibernate Sessions (or EntityManagers), and a Hibernate Session has methods like save that take an object and persist it or do whatever with it. The entity object would get updated with new values and then it would be passed as an argument in a call to session.save (though in many cases Hibernate can figure out what changed, so no explicit call to save is required), like this:
EntityManager manager = entityManagerFactory.create();
MyEntity entity = manager.findById(someid);
entity.setName("new name");
manager.save(entity);


text:
Q: Cannot show an error message after creating an error I'm trying to connect to the database using localhost.
<?php
     //Connecting to the Database
     $servername = "localhost";
     $username = "root";
     $password = "";

    // Create a connection
    $conn = mysqli_connect($servername, $username, $password);

    // Die if connection was not successful
    if (!$conn){
        die("Sorry we failed to connect: ". mysqli_connect_error());
    }
    else{
        echo "Connection was successful";
    }
?>

It works if the connection is made but I don't get the
"Sorry we failed to connect" message when I intentionally create an error.
What could be the potential causes of this?

A: As stated in the documentation:

If MYSQLI_REPORT_STRICT is enabled and the attempt to connect to the requested database fails, a mysqli_sql_exception is thrown.

Since you are getting an exception, this must be set. Your code should change as follows in this case:
try {
    $conn = mysqli_connect($servername, $username, $password);
} catch(mysqli_sql_exception $e) {
    die("Sorry we failed to connect: ". mysqli_connect_error());
}
echo "Connection was successful";


text:
Q: Create a Expression in LINQ My LINQ query is like the below code.
 var data2 = data.Where(c => String.Format("{0:MM/dd/yyyy}", c.OrderDate) == "07/04/1996");

I need to customize the predicate for formatted column in the below expression. I need to write the Expression for predicate and filter the data based on format. please check below code.
pred =Expression.Equal(membertype, Expression.Constant(value, type));
lambda = Expression.Lambda(predicate, paramExpression);
source.Where(paramExpression, predicate);

Thanks.

A: Here's a sample that creates the .Where dynamically.
static void DynamicWhereBuilder() {
  var datas = new Data[] {
    new Data { OrderDate  = "07/04/1996"},
    new Data { OrderDate  = "07/04/1990"},
    new Data { OrderDate  = "07/04/2001"},
    new Data { OrderDate  = "2012/04/07"}
  };
  IQueryable<Data> queryableData = datas.AsQueryable<Data>();

  var formatConstant = Expression.Constant("{0:MM/dd/yyyy}", typeof(string));
  var parameter = Expression.Parameter(typeof(Data), "dataArg");
  var property = Expression.Property(parameter, "OrderDate");

  var left = Expression.Call(property, typeof(string).GetMethod("Format", new Type[] { typeof(string), typeof(object) }), formatConstant, property);
  var right = Expression.Constant("07/04/2001", typeof(string));

  var equal = Expression.Equal(left, right);
  var whereCallExpression = Expression.Call(
    typeof(Queryable),
    "Where",
    new Type[] { queryableData.ElementType },
    queryableData.Expression,
    Expression.Lambda<Func<Data, bool>>(equal, new ParameterExpression[] { parameter }));
  var results = queryableData.Provider.CreateQuery<Data>(whereCallExpression); // returns the object with OrderDate = "07/04/2001"
}


text:
Q: Двойное отрицание в jquery В jquery есть двойное отрицание? А то такие условия нагромождают код.
if (index_i == 0) {
    index_i = 1;
} else {
    index_i = 0;
}

Хочется:
index_i = !!index_i;

Через тернарные тоже не хочу.

A: для описанного выше случая можно использовать
index_i ^= 1

вообще если надо менять между 0 и целым числом n
index_i ^= n


text:
Q: Generating a Flicking carousel with React leads to the getComputedStyle error This question is about egjs-flicking library but perhaps problem is more general.
Let us consider two examples of components that will differ only by their render() method. First I provide the whole component.
import React from 'react';

import Flicking, { MoveEvent, FlickingError } from "@egjs/react-flicking";

class Credits extends React.Component {
    constructor(props) {
        super(props);
        this.readtime = 1000;
        this.maxElements = 4;
        this.actionReady = this.actionReady.bind(this);
        this.actionReset = this.actionReset.bind(this);
        this.actionMove = this.actionMove.bind(this);
        this.processFlicking = this.processFlicking.bind(this);
    }

    async actionReady(e) {
        const status = e.currentTarget.getStatus();
        setTimeout(() => {
            e.currentTarget.moveTo(status.position.panel + 1);
        }, this.readTime);
    }

    async actionReset(e, delay) {
        setTimeout(() => {
            e.currentTarget.moveTo(0);
        }, delay);
    }

    async actionMove(e) {
        const status = e.currentTarget.getStatus();
        setTimeout(() => {
            e.currentTarget.moveTo(status.position.panel + 1);
        }, this.readTime);
    }

    async processFlicking(e) {
        const status = e.currentTarget.getStatus();
        const remaining = status.panels.length - status.position.panel;
        if (remaining == this.maxElements) {
            this.actionReset(e, this.readtime*this.maxElements);
        } else {
            this.actionMove(e);
        }
    }

    getMStyle() {
        return {
            'overflow': 'hidden'
        };
    }

    render() {
        // this is where the examples differ
    }
}

Static case
Now the first case is the children of the Flicking container are pre-defined.
render() {
        const PanelComponent = this.props.panelComponent;
        return (
            <Flicking
              style={this.getMStyle()}
              circular={false}
              align={"prev"}
              horizontal={false}
              onReady={this.actionReady}
              onMoveEnd={this.processFlicking}
            >

hello

sup

how are u

cze

konnichiwa

salam

namaste

            </Flicking>
        );
    }

which gives the following rendered HTML

hello

sup

how are u

cze

konnichiwa

salam

namaste

Dynamic case
Here they are generated dynamically
render() {
        const PanelComponent = this.props.panelComponent;
        return (
            <Flicking
              style={this.getMStyle()}
              circular={false}
              align={"prev"}
              horizontal={false}
              onReady={this.actionReady}
              onMoveEnd={this.processFlicking}
            >
              { this.props.panels.map((data, index) =>
                  ( <PanelComponent key={index} data={data.content} /> )) }
            </Flicking>
        );
    }

giving the following rendered HTML (identical to previous)

hello

sup

how are u

cze

konnichiwa

salam

namaste

for PanelComponent it was using
class EntryElement extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (

{ this.props.data }

        )
    }
}

to generate each of the panels.
Problem
The static case works perfectly, the dynamic case gives the following error
Uncaught (in promise) TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.
    at getStyle (utils.ts:259:1)
    at Panel.__proto.resize (Panel.ts:323:1)
    at Renderer.ts:163:1
    at Array.forEach (<anonymous>)
    at ReactRenderer.__proto.updatePanelSize (Renderer.ts:163:1)
    at Flicking.<anonymous> (Flicking.ts:1227:1)
    at step (index.ts:1:1)
    at Object.next (index.ts:1:1)
    at fulfilled (index.ts:1:1)

and I am really puzzled why because resulting HTML is identical... Any ideas?

A: Ok I actually found it. All thanks to this GitHub discussion and here is my relevant comment.
From https://naver.github.io/egjs-flicking/docs/quick-start I checked section Bypassing ref forwarding and added useFindDOMNode={true} to my Flicking.
Here is the complete working source that is able to dynamically put children components in Flicking
class Credits extends React.Component {
    constructor(props) {
        super(props);
        this.readtime = 1000;
        this.maxElements = 4;
        this.actionReady = this.actionReady.bind(this);
        this.actionReset = this.actionReset.bind(this);
        this.actionMove = this.actionMove.bind(this);
        this.processFlicking = this.processFlicking.bind(this);
        this.createPanel = this.createPanel.bind(this);
    }

    async actionReady(e) {
        const status = e.currentTarget.getStatus();
        setTimeout(() => {
            e.currentTarget.moveTo(status.position.panel + 1);
        }, this.readTime);
    }

    async actionReset(e, delay) {
        setTimeout(() => {
            e.currentTarget.moveTo(0);
        }, delay);
    }

    async actionMove(e) {
        const status = e.currentTarget.getStatus();
        setTimeout(() => {
            e.currentTarget.moveTo(status.position.panel + 1);
        }, this.readTime);
    }

    async processFlicking(e) {
        const status = e.currentTarget.getStatus();
        const remaining = status.panels.length - status.position.panel;
        if (remaining == this.maxElements) {
            this.actionReset(e, this.readtime*this.maxElements);
        } else {
            this.actionMove(e);
        }
    }

    getMStyle() {
        return {
            'overflow': 'hidden'
        };
    }

    createPanel(panel, index) {
        const PanelComponent = this.props.panelComponent;
        return <PanelComponent data={panel.content} key={index} />;
    }

    createPanels(panels) {
        return panels.map(this.createPanel);
    }

    render() {
        const panels = this.props.panels;
        return (
            <Flicking
              useFindDOMNode={true}
              style={this.getMStyle()}
              circular={false}
              align={"prev"}
              horizontal={false}
              onReady={this.actionReady}
              onMoveEnd={this.processFlicking}
            >
              { this.createPanels(panels) }
            </Flicking>
        );
    }
}


text:
Q: Appium does not start in Mac system Im getting the below error while click Launch button:

"Appium will not work if used or installed with sudo. Please
  rerun/install as a non-root user. If you had to install Appium using
  sudo npm install -g appium, the solution is to reinstall Node using
  a method (Homebrew, for example) that doesn't require sudo to install
  global npm packages."


text:
Q: Current Observation feed from weather.gov forbidden (403) Weather.gov Current Observation feeds have suddenly begun to fail for all requests from an HTTPClient, and likewise I've observed that many websites across the internet that use AJAX to make calls to weather.gov are also failing.
The result of all calls to weather.gov current observation feeds, e.g. http://w1.weather.gov/xml/current_obs/TAPA.xml, return a 403. Said URL resolves properly in a browser.

A: Contacting weather.gov resulted in a really fast response, which was:

Applications accessing resources on weather.gov now need to provide a
  User-Agent header in any HTTP request. Requests without a user agent
  are automatically blocked. We have implemented this usage policy due
  to a small number of clients utilizing resources far in excess of what
  most would consider reasonable.
We recommend providing a user agent string in the following format:
ApplicationName/vX.Y (http://your.app.url/; contact.email@example.com)
This will both uniquely identify your application and allow us to
  contact you and work with you if we observe abnormal application
  behavior that may result in a block.
Please feel free to email us back if you continue to have issues after
  verifying that your application is sending the proper headers.
Thanks for using weather.gov.

=======
Here's a snip of C# code. The key thing is that you need to create the request object then append a custom User-Agent string to it before making the call.
...
var request = new HttpRequestMessage(HttpMethod.Post, httpClient.BaseAddress.AbsoluteUri);
request.Headers.Add("User-Agent", "MyApplication/v1.0 (http://foo.bar.baz; foo@bar.baz)");
var httpResponse = httpClient.SendAsync(request).Result;
...

Hope this helps folks.
Cheers

A: That is great but you cant set "User-Agent" when you are using an XMLDocument and calling Load() Like this (this used to work):
        XmlDocument doc = new XmlDocument();
        string stationName = @"http://w1.weather.gov/xml/current_obs/PASC.xml";
        doc.Load(stationName);  // exception 403 occurs here now

Instead now you need to perform a GET and then set the User-Agent to your company or email and then use the XmlDocument like:
       XmlDocument doc = new XmlDocument();

       string stationName = @"http://w1.weather.gov/xml/current_obs/PASC.xml";

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(stationName);

        request.Method = "GET";
        request.ContentType = "application/x-www-form-urlencoded";
        request.UserAgent = "MyApplication/v1.0 (http://foo.bar.baz; foo@bar.baz)";
        request.Accept = "Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream resStream = response.GetResponseStream();

        doc.Load(resStream);
        try
        {

            XmlNodeList list = doc.GetElementsByTagName("temp_f");
            if (list.Count > 0)
            {
                float fTemperature = float.Parse(list.Item(0).InnerText);

            }
        }

A: On the off chance your finding this from Étude 12-1 from Études for Elixir, here's what ended up working for me
  s_url = "http://w1.weather.gov/xml/current_obs/" <> weather_station <> ".xml"
 :httpc.request(:get, { to_char_list(s_url),
                        [ {'User-Agent','ErlangEtudes/v1.0 (http://example.org;me@example.org)' } ]
                      },[],[] )

A: I had the same problem but was using PowerShell. Here is a way to set User Agent by using HttpWebRequest.
$weather_url = "http://w1.weather.gov/xml/current_obs/KLNK.xml"
$request = [System.Net.HttpWebRequest]::Create($weather_url)
$request.UserAgent = " {Enter your agent} "
$response = $request.GetResponse()

$doc = New-Object System.Xml.XmlDocument
$doc.Load($response.GetResponseStream())

$temp_f = [int] $doc.current_observation.temp_f

A: This answer helped me but actually did not work.  I still received the error response.
I changed the Post to a Get in this line:
var request = new HttpRequestMessage(HttpMethod.Post...

To:
var request = new HttpRequestMessage(HttpMethod.Get...

Then, it worked fine.


text:
Q: Easier way to get one of two variables to have one of two options randomly? I got two variables, x and y. One of these should have random int value from 0 to 721 - this.Width. The other one has to be either value 0 or 721 - this.Width. I've already managed to create this, but such a long code seems stupid for such a small thing. Might be that this is the only (or best) solution, but I'm asking to be sure, is there a shorter way?
Here's my code:
Random random = new Random();
int x, y;
if (random.Next(2) == 1)
{
    x = random.Next(721 - this.Width);
    if (random.Next(2) == 1)
    {
        y = 721 - this.Height;
    }
    else
    {
        y = 0;
    }
}
else
{
    y = random.Next(721 - this.Height);
    if (random.Next(2) == 1)
    {
        x = 721 - this.Width;
    }
    else
    {
        x = 0;
    }
}

A: You could write it like this:
Random random = new Random();
int a = random.Next(2) * (721 - this.Width);
int b = random.Next(721 - this.Width);
int c = random.Next(2) * (721 - this.Height);
int d = random.Next(721 - this.Height);
int x, y;

Boolean t = (random.Next(2) == 1);
x = (t) ? a : b;
y = (t) ? d : c;

Note that this code is no better than yours if you find the longer version easier to understand. There is no right way to write code, and understandability is often more valuable than brevity.

A: If you want it to take up fewer lines then you can do this:
Random random = new Random();
int x, y;
switch (random.Next(2))
{
    case 1:
        x = random.Next(721 - Width);
        y = random.Next(2) == 1 ? 721 - Height : 0;
        break;
    default:
        y = random.Next(721 - Height);
        x = random.Next(2) == 1 ? 721 - Width : 0;
        break;
}

Credit goes to Resharper.

A: It's not too bad. I think the best you can do is move it to a nice helper utility to hide the complexity. Perhaps you can assign the various random.Next(0, 1) results to named booleans:
public class PositionCalculator
{
    private Random random = new Random();

    public Point CalculatePosition(int width, int height)
    {
        int x, y;

        bool favourWidth = RandomBoolean();
        bool useZeroForOther = RandomBoolean();

        int favouredValue = random.Next(721 - (favourWidth ? width : height));
        int otherValue = useZeroForOther ? 0 : (721 - (favourWidth ? height : width));

        if (favourWidth)
        {
            x = favouredValue;
            y = otherValue;
        }
        else
        {
            x = otherValue;
            y = favouredValue;
        }

        return new Point() { X = x, Y = y };
    }

    private bool RandomBoolean()
    {
        return random.Next(2) == 1;
    }
}

At least this way, however you want to play around with the internal implementation it doesn't really matter to the rest of your application. I had this get the Width and Height passed in just to avoid requiring it to have a reference to the UI layer.
EDIT: Really, even with this, I still find the "logic" path hard to follow with the ternary operators. Feel free to use whatever ifs or method structure makes the most sense for you to maintain it and still understand it when you look at the algorithm again months/years from now.

A: var max = 721 - this.Width;
var rand = new Random();
var r = rand.Next(max * 2);
var x = r % max;
var y = (r / max) * max;
if (rand.Next(2) == 1) {var t = x; x = y; y = t;}


text:
Q: Windows PowerShell не работает Когда я ввожу многие команды в PowerShell зачастую я получаю ответ:
PS C:\Users\user> ps
ps : Cannot find drive. A drive with the name '.C' does not exist.
At line:1 char:1
+ ps
+ ~~
    + CategoryInfo          : ObjectNotFound: (.C:String) [], DriveNotFoundException
    + FullyQualifiedErrorId : DriveNotFound

Однако например команда Get-Help рабоатет коректно и ошибки не выдает. Проблема появилась только после переустановки Windows, до этого все работало коректно
Как решить данную проблему?


text:
Q: The /var/lib/pgsql directory has wrong permissions on centos 7,
installing Request Tracker
trying to do postgresql-setup initdb
keep getting:
The /var/lib/pgsql directory has wrong permissions.
i've chowned the folder recursively to the postgres user, and given it all 700 perms. i've verified the permissions and ownership with ls.
i've go no idea what is broken here, or how to fix.

A: fixed by running with sudo. apparently needs root perms to do it


text:
Q: Deducing convergence from bounds on average Assume I have a bound on the summatory function of the form
$$\sum_{n \leqslant x} |a_n|^2 \leqslant x^\alpha$$
Can I then deduce something about the convergence of
$$\sum \frac{a_n}{n^k} ?$$
I was expecting getting something using Cauchy-Schwarz inequality, but it is not enough since $x^\alpha$ diverge and the sum of $n^{-2k}$ only converges, and does not compensate this $x^a$. Am I missing something?

A: By the assumption, we have
$$
\sum_{n= 2^j}^{2^{j+1}-1 }|a_n|^2 \le C_1 2^{\alpha j}
$$ for all $j\ge 0$.
Note that
$$
\sum_{n= 2^j }^{2^{j+1}-1 }\frac{|a_n|}{n^k}\leq C_22^{-kj}\sum_{n= 2^j }^{2^{j+1} -1}|a_n|\leq C_32^{-(k-\frac{1}{2})j}\sqrt{\sum_{n= 2^j }^{2^{j+1}-1 }|a_n|^2}\le C_42^{-(k-\frac{1}{2}-\frac{\alpha}{2})j}
$$ for all $j\ge 0$. Here, $(C_p)_{ 1\le p\le 4}$ is a set of constants depending only on $\alpha$ and $k$. Thus, if $k>\frac{\alpha+1}{2}$, then the sum
$$
\sum_{j=0}^\infty\sum_{n= 2^j }^{2^{j+1}-1 }\frac{|a_n|}{n^k}
$$ converges absolutely. If $k \le \frac{\alpha+1}{2}$, then $a_n = c\cdot n^{\frac{\alpha-1}{2}}$ satisfies $\sum_{j\leq x} |a_j|^2 \le x^\alpha$ for sufficiently small $c>0$, but
$$
\sum_n \frac{a_n}{n^{k}} \ge c\sum_n \frac{1}{n}=\infty.
$$ Hence, the bound $k>\frac{\alpha+1}{2}$ cannot be improved.


text:
Q: How get text with preg_match till end of word? I need to find part of string which is equal to string till end of word.
Example i have texts:

*

*"Start play. I need..."

*"Start playstation play"

*"start play, work"

*"start player"

*"start pay with..."

Then i searching for "/^start play/'i" and found all phrases, but i need only phrases which ends with word play: 1, 3, 5
preg_match('/^start play/i', $text, $key_matches)

I can write in MySQL REGEXP it would be "^Start play[[:>:]]" [[:>:]] - means end of word, but i cant find how to write in PHP?
Can some one help me?

A: preg_match('/^start play\b/i', $text, $key_matches)

\b matches a word boundary.

A: \b is word boundary anchor
http://www.regular-expressions.info/wordboundaries.html


text:
Q: Conversion of String to int not getting desired format I want to convert a string to int like this:
CAST(TestSth3.Emp_Code AS int)
I need output as 1234 in crystal report, shows me correctly when i get the output from database, but in Crystal it again converts to 1,234 instead of 1234.
I am using vb.net 2008 and SQL server.

A: I think you need to try this solution, Replace ',' to '' in the string
Take a look on below code
CAST(REPLACE(TestSth3.Emp_Code, ',', '') AS int) As Clm

A: it is unclear your question i just point out some facts here
if your string is 1234
then when you try select cast(yournum,int) will give you the correct result
example
select cast('1234'as int) as num

will results
1234

or if your string is something like 1,234
then
try the following it will give results
declare  @num varchar(10) ='1,234'

select CONVERT(int, replace(@num,',',''))as number

or
select CAST(replace(@num,',','') AS int)as number2

both results 1234
also you need to double check TestSth3.Emp_Code what is that ?? is it a parameter ??
if yes then need @before that and i think it is not possible to create a parameter name including .(dot) so double check that too.
UPDATE
if the problem based on crystal report then follow below steps

Right mouse click on that field, and select "Format object". Select
  "Custom Style" in the Style list, and click "Customize". Untick
  "Thousands Separator", and any other unwanted formatting.
Failing that, you could try selecting the field and deleting the ","
  value from the property "ThousandSeperator" in your properties window.

or use below formula
CStr(YourField, 0, '')

A: I think this post summarises the problem much better. @MattWhitfield says:

Formatting numbers for display is something that should be done in the
  display layer, and not within the database. So, in whatever
  application this data ends up being used, you should format it there.
  Management Studio, unfortunately, does not offer much control in this
  regard.

Edit: Integers don't have formats. E.g. Six eggs are formatted as eggs, not digits, but they are still 6. The formatting has nothing to do with the number. However if you want to display the integer in a particular format (with or without thousands separator - commas), then convert it back to a string again in the report or VB form, not in the database (or leave it as a string since it's already a string).

A: Easy way is to use crystal report functions:
ToNumber(TestSth3.Emp_Code)


text:
Q: Check server status and output in HTML I'm trying to output the status of a server (online/offline) in html.
I have a PHP snippet that checks the status of the server but I need the output to be in HTML format so I can use it elsewhere on my website.
I'm running wordpress with the tablera plugin, I want to output the status (just online or offline text) in the table but it does not accept PHP, only HTML.
Edit:
This is my PHP snippet:
<?php
$array="www.php.net:80";
$fp = @fsockopen($array[0], $array[1], $errno, $errstr,1);
if(!$fp){
$status = $array[0]."==>online";
}
else{
$status = $array[0]."==>offline";
}
fclose($fp);
echo $status;
?>

It just needs to check if the server is online or offline, if it's online it should display 'online' if its offline, it should display 'offline'.

A: This script checks your server to see if the server is online or not.
<?php
if (fsockopen('www.yourwebsite.com', 80)) {
    echo('Reports Online');
} else {
    echo('Reports Offline');
}
?>


text:
Q: SonataAdminBundle's menu labels tree shows entity path instead entity name it's my first question on SO. I have a problem with SonataAdminBundle. Everythink works fine, but instead name of entity field i get a path to entity.
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services
http://symfony.com/schema/dic/services/services-1.0.xsd">
    <services>
        <service id="sonata.admin.city" class="My\FrontendBundle\Admin\CityAdmin">
            <tag name="sonata.admin" manager_type="orm" group="Dane" label="Miasta"/>
            <argument />
            <argument>My\FrontendBundle\Entity\City</argument>
            <argument>SonataAdminBundle:CRUD</argument>
            <call method="setTranslationDomain">
                <argument>MyFrontendBundle</argument>
            </call>
        </service>
    </services>
</container>

Php class
namespace My\FrontendBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;

class CityAdmin extends Admin
{
    protected $translationDomain = 'MyFrontendBundle';
    //protected $baseRoutePattern = 'city';
    // Fields to be shown on create/edit forms
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->add('name', 'text', array('label' => 'City name'))
            ->add('population', 'number') //if no type is specified, SonataAdminBundle tries to guess it
        ;
    }

    // Fields to be shown on filter forms
    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
            ->add('name')
        ;
    }

    // Fields to be shown on lists
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->addIdentifier('name')
            ->add('population','number')
        ;
    }
}

Photo:

A: You need to define __toString() method in your entity that is linked with your admin My\FrontendBundle\Entity\City and return name of the city in case of edit for add case return your desired text
class City {

    public function __toString() {

        return ( $this->id ) ? $this->getName(): 'New City';

    }
// ...
}

A: Define/override toString() method in your admin class:
class CityAdmin extends AbstractAdmin
{
    /**
     * @inheritdoc
     */
    public function toString($object)
    {
       return (!$object || !$object->getId()) ? 'New City' : $object->getName();
    }

    ...

}


text:
Q: Randomly failing tests jest and supertest Node.js so long story short I'm developing RESTapi that takes a movie title on POST request to the /movies route, fetches info about that movie from external api and saves that object to the database. On POST /comments you add a comment to the different collection but every comment has a 'movie_id' property that has an associated movie.
That's my first bigger project so I'm trying to write integrational tests.
Everything is great, at least in my opinion, except 3 weird test cases that are failing just out of nowhere. Tests could pass 10 times in a row and then suddenly that weird 'jest' timer shows up and 3 cases fail.
I'm using native mongodb driver, express and jest with supertest for testing, dropping test-database BeforeAll and AfterEach, I have no idea whats the reason of that.
Timer thingy:

And after timer this shows up, failed tests:

Full source code is here GITHUB
Other failed cases:

Any ideas, tips?

A: The code seems to return one entry, while the test expects zero. This looks very much like an issue with test independence: Your tests seem to depend on each other (through the database).
I would guess that one test creates the movie and then clears it again. When everything works fine, the second test does not find the movie. But, in some unforunate cases (bad timing, different execution order, ...), the database is not cleared fast enough and the second test finds the movie.
So, you should work hard on making your tests independent. This is not easy with integrated tests, especially when they involve a real database.
Maybe you can create smaller tests (Unit tests, micro tests, ...) to achieve independence. If this is not possible, the test could check it's precondition (database empty or whatever) and wait until it's fulfilled (or until a timeout happens).
Dropping the database in BeforeAll and AfterEach might not be enough, because Jest even runs your tests in parallel: Are tests inside one file run in parallel in Jest?
Also, dropping might not be a completely synchronous and atomic operation, especially when there is some caching in the DB driver. But I don't know mongodb and it's node.js integration well enough to judge that.

A: I was in the same hell "jest parallel tests" problem and i find a solution, maybe not the best but now jest run tests in "queue mode" so when i delete datas in beforeAll my next group of tests is ready to go with "fresh" new inserted datas.

--runInBand
  Alias: -i. Run all tests serially in the current process, rather than creating a > worker pool of child processes that run tests. This can be useful for debugging.

jest source
So in my config.json i have :
    "scripts": {
        "test": "set NODE_ENV=test&& jest ./tests --runInBand --detectOpenHandles --forceExit",
        "server": "set NODE_ENV=development&& nodemon app.js"
    }


text:
Q: WSGI Django 403 Forbidden When I run
sudo service apache2 restart

I get an error
unable to resolve host hostname

When I look at the error.txt it says it's my WSGI configuration.
Here is my WSGI script.
import os
import sys
from django.core.handlers.wsgi import WSGIHandler
import django

os.environ['DJANGO_SETTINGS_MODULE'] = 'app.settings'
sys.executable = '/usr/lib/python2.7/dist-packages'
application = WSGIHandler()

django.setup()

EDIT1:
Here is my apache2 file. I did change the WSGI file to /user/app/app_settings/wsgi.py
    <VirtualHost website:80>
   ServerName website.com
   ServerAlias www.website.com
   ServerAdmin email@website.com

   DocumentRoot /home/user/app/static

   WSGIScriptAlias / /home/user/app/app_settings/wsgi.py
   <Directory /home/user/app/>
      Order allow,deny
      Allow from all
      Require all granted
   </Directory>

   #Alias /robots.txt /var/www/user/app/robots.txt
   #Alias /favicon.ico /var/www/user/app/favicon.ico
   #Alias /images /home/user/app/static/images
   #Alias /static /home/user/app/static/

   ErrorLog /var/www/website/error.log
   #CustomLog /var/www/website/access.log combined
</VirtualHost>


text:
Q: Creating Dynamic Header with Jquery I am trying to create a header that adjusts its contents as the user makes the window smaller, and eventually goes down to just a menu icon at under 850px. The problem is that the header is always the last thing to load on the page with my current Jquery code. Any ideas?
   $( window ).bind("resize load",function() {
    if($(window).width()>1050){
      $('.three-head').show();
      $('.two-head').css("margin-right","90px");
      $('#header').show();
      $('.big-head').show();
      $('.small-head').hide();
    }
else if($(window).width()<1050 && $(window).width()>850){
    $('.two-head').css("margin-right","30px");
    $('#header').show();
    $('.big-head').show();
    $('.small-head').hide();
    $('.three-head').hide();
    $('.four-head').show();
    $('.five-head').show();
}
else if($(window).width()<850){
    $('.small-head').show();
}
});

A: put this code in
    $(document).ready(function(){$(document).ready(function(){
});

and remove
 $( window ).bind("resize load",function()

is load after window load

A: I would try a dynamic function .resize() that will lisen to your window.
$(document).ready(function() {
    $(window).resize(function() {
        if($(window).width()>1050){
            $('.three-head').show();
            $('.two-head').css("margin-right","90px");
            $('#header').show();
            $('.big-head').show();
            $('.small-head').hide();
        } else if($(window).width()<1050 && $(window).width()>850){
            $('.two-head').css("margin-right","30px");
            $('#header').show();
            $('.big-head').show();
            $('.small-head').hide();
            $('.three-head').hide();
            $('.four-head').show();
            $('.five-head').show();
        }
    });
});

You can also implement a onLoad function lik this:
$('#header').load(function () {

    YOUR CODE HERE

)}

Hope this helps


text:
Q: Web Scraping: Taking a lot of time My code below is just a piece and this is where it takes so much time. It works but it takes really long time and I have no idea what to do.
Say I have a list:
ticker=['a','b','c','d','e','h','i','j','k','e']

which I get it from another url
Below is where it takes really really long time. I am sure it is because it gets 10 different urls and find the right pieces.. but how can I make it faster? is that even possible? It took over 3 mins. It has to be within 10-15 secs..
all_data=[]
for tick in ticker:
    url = ("https://finance.yahoo.com/quote/"+tick+"?p="+tick+"&.tsrc=fin-srch-v1")
    yahoo =requests.get(url)
    access2 = BeautifulSoup(yahoo.text,'html.parser')
    rows = access2.find_all('table')[0].tbody.find_all('tr')

A: The bottleneck here is the Request/Response time. Each time you make a request, your program has to wait some time to get the response. This time is almost negligible for one request but it can add up to a significant amount when 10 requests are made.
To solve this problem, you can utilize multi-threading. You can make 10 threads - 1 for each request - and the total execution time will be significantly reduced! Here's a very good article on Threading in Python

A: The below code will speed up the web scraping. It uses multi-threading as suggested by @Moosa.
ticker = ['a', 'b', 'c', 'd', 'e', 'h', 'i', 'j', 'k', 'e']

result = []

def fetch(tick):
    url = ("https://finance.yahoo.com/quote/"+tick+"?p="+tick+"&.tsrc=fin-srch-v1")
    yahoo = requests.get(url)
    access2 = BeautifulSoup(yahoo.text,'html.parser')
    rows = access2.find_all('table')[0].tbody.find_all('tr')
    result.append(rows)

def executor():
    threads = []
    for tick in ticker:
        t = Thread(target=fetch, args=(tick,))  # Create a new thread
        t.start()  # Execute the target of the thread - fetch
        threads.append(t)
    for t in threads:
        t.join()  # Wait for the child thread to complete

    return result

rows = executor()

for row in rows:
    ..... remaining code


text:
Q: Is ArcMap's Fixed Zoom In/Out algorithm documented anywhere? I only occasionally use the Fixed Zoom In/Out buttons on the Tools toolbar of ArcMap and had always assumed that they zoomed in/out by a set scale factor.
However, using ArcGIS for Desktop 10.2, I just set my scale to be 1:10,000,000 and then hit the Fixed Zoom In button 10 times while recording the subsequent scale each time and was surprised to see:
10,000,000
8,000,000
6,000,000
5,000,000
4,000,000
3,000,000
2,500,000
2,000,000
1,500,000
1,250,000
1,000,000

Dividing each scale denominator by its successor shows a sequence of:
1.25, 1.33, 1.2, 1.25, 1.33, 1.2, 1.25, 1.33, 1.2
Curious about what happened in between the scales above I experimented a little to discover that the first issuance of the Fixed Zoom In button simply takes the scale to the first of those listed above and then starts following the same pattern.  Try starting with 1:8,000,001 to see ...
8,000,001
8,000,000
6,000,000
5,000,000
4,000,000
3,000,000

This seems like quite a neat solution, but not one that I had realised was in place - does anyone know if it has been documented anywhere?
I've looked in the Online Help without success.
In answer to @DevdataTengshe, the scales currently in my available list (see below) seem to bear no relation to those used by Fixed Zoom In/Out.

However, when I add 1:7,500,000 into my available list it does seem to insert that as an additional scale step ...
10,000,000
8,000,000
7,500,000
6,000,000
5,000,000
4,000,000

This makes the algorithm being used even more mysterious to me.

A: I have tested this behavior on ArcGIS Desktop 9.3.1 & ArcGIS 10.0
The behavior has changed between 9.3.1 and 10.0; with 10.0, you see the same behavior that PolyGeo has mentioned. With ArcGIS 9.3.1, the zoom in/out factor was always 1.25 from the current scale.
After some testing, the behavior of 10.x is quite easy to decipher; ArcMap internally has a set of scales which are used by these tools.
These scales are:
250,000,000
200,000,000
150,000,000
125,000,000
100,000,000
80,000,000
60,000,000
50,000,000
40,000,000
30,000,000
25,000,000
20,000,000
15,000,000
12,500,000
10,000,000
8,000,000
6,000,000
5,000,000
4,000,000
3,000,000
2,500,000
2,000,000
1,500,000
1,250,000
1,000,000
 and so on.

If you have not touched your scale settings, you'll see that the scales there are a subset of the above scales.
If you manually add a custom scale, such as 7,500,000, then the custom scale is added to the above internal zoom levels; ArcMap's fixed Zoom in and Fixed Zoom out will use the modified set of zoom levels


text:
Q: Inserting color code from OpenStreetMap to ArcMap? I have a color code from OpenStreetMap.
How do I insert this code of color to ArcMap?

A: The question is a little vague, but I assume you mean you have hex color codes.  ArcMap does not support hex codes, so you'll have to convert them to RGB or CMYK.
You can use a color converter tool like this one: http://www.javascripter.net/faq/hextorgb.htm