text:
Q: TextSuggest autocomplete error on Ubuntu 18.04.3 I'm having an issue with TextSuggest - an automcomplete tool for Linux. It only works once, after that the shortcut doesn't open the autocomplete popup anymore. (nothing happens at all)

*

*My Shortcut: SHIFT+CTRL+P

*OS: Ubuntu 18.04.3 LTS.

*I added textsuggest-server in the background to run on startup

Error message after I select a word from the TextSuggest menu and press enter:
    go@tom:~/Desktop/TextSuggest-Pkg$ textsuggest-server
Started server at org.textsuggest.server, PID: 7678…
time get_all_words([English, English]) = 0.001719
Processing 'previous'
    Using processor 'command' from '/usr/share/textsuggest/processors/command'
terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::substr: __pos (which is 18446744073709551615) > this->size() (which is 0)
/usr/bin/textsuggest-server: line 3:  7678 Aborted                 (core dumped) LD_LIBRARY_PATH=/usr/share/textsuggest/libs /usr/share/textsuggest/textsuggest-server "$@"

error 2:
Started server at org.textsuggest.server, PID: 7811…
time get_all_words([English, English]) = 0.00155287
time get_all_words([English, English]) = 0.00150532
Processing 'previous'
    Using processor 'command' from '/usr/share/textsuggest/processors/command'
terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::substr: __pos (which is 18446744073709551615) > this->size() (which is 0)
/usr/bin/textsuggest-server: line 3:  7811 Aborted                 (core dumped) LD_LIBRARY_PATH=/usr/share/textsuggest/libs /usr/share/textsuggest/textsuggest-server "$@"

Any ideas what could be the issue?


text:
Q: Sibling as Child Here is my xml that I want to translate.
<?xml version="1.0" encoding="UTF-8" ?>
<Loop xmlns="http://www.example.org">
  <Loop-2000A>
    <Element-628>81</Element-628>
    <Element-734 nil="nil82"/>
    <Element-735>83</Element-735>
    <Element-736>84</Element-736>
  </Loop-2000A>
  <Loop-2000B>
    <Element-1035>85</Element-1035>
    <Element-1036 nil="nil86"/>
    <Element-1037>87</Element-1037>
  </Loop-2000B>
  <Loop-2000B>
    <Element-1035>98</Element-1035>
    <Element-1036 nil="nil86"/>
    <Element-1037>97</Element-1037>
  </Loop-2000B>
  <Loop-2000C>
    <Element-1031>86</Element-1031>
    <Element-1039 nil="nil86"/>
    <Element-1038>25</Element-1038>
  </Loop-2000C>

  <Loop-2000A>
    <Element-628>89</Element-628>
    <Element-734 nil="nil82"/>
    <Element-735>99</Element-735>
    <Element-736>109</Element-736>
  </Loop-2000A>
  <Loop-2000B>
    <Element-1035>208</Element-1035>
    <Element-1036 nil="nil86"/>
    <Element-1037>87</Element-1037>

  </Loop-2000B>
  <Loop-2000C>
    <Element-1031>92</Element-1031>
    <Element-1039 nil="nil86"/>
    <Element-1038>90</Element-1038>
  </Loop-2000C>
  <Loop-2000B>
    <Element-1035>209</Element-1035>
    <Element-1036 nil="nil86"/>
    <Element-1037>97</Element-1037>
  </Loop-2000B>
</Loop>

The requirement is to make the ...Loop-2000A  parents of ...Loop-2000B  ..and Loop-2000B Parents of 2000-C . Loop2000-C is optional in source xml.Other Loop in xml which are outside Loop-2000A should be transformed as it is.  Hence, the transformed XML should look something like this.
<?xml version = '1.0' encoding = 'UTF-8'?>
<ns2:TargetLoop xmlns:ns2="http://www.target.org">
  <Loop-2000A>
    <Loop-2000B>
      <Element-1035>85</Element-1035>
      <Element-1036 nil="nil86"/>
      <Element-1037>87</Element-1037>

    </Loop-2000B>
    <Loop-2000B>
      <Element-1035>98</Element-1035>
      <Element-1036 nil="nil86"/>
      <Element-1037>97</Element-1037>
      <Loop-2000C>
        <Element-1031>86</Element-1031>
        <Element-1039 nil="nil86"/>
        <Element-1038>25</Element-1038>
      </Loop-2000C>
    </Loop-2000B>
    <Element-628>81</Element-628>
    <Element-734 nil="nil82"/>
    <Element-735>83</Element-735>
    <Element-736>84</Element-736>
  </Loop-2000A>

  <Loop-2000A>
   <Loop-2000B>
      <Element-1035>208</Element-1035>
      <Element-1036 nil="nil86"/>
      <Element-1037>87</Element-1037>
      <Loop-2000C>
        <Element-1031>92</Element-1031>
        <Element-1039 nil="nil86"/>
        <Element-1038>90</Element-1038>
      </Loop-2000C>
    </Loop-2000B>
    <Loop-2000B>
      <Element-1035>209</Element-1035>
      <Element-1036 nil="nil86"/>
      <Element-1037>97</Element-1037>
    </Loop-2000B>
    <Element-628>89</Element-628>
    <Element-734 nil="nil82"/>
    <Element-735>99</Element-735>
    <Element-736>109</Element-736>
  </Loop-2000A>
</Loop>

Any suggestions would be appreciated

A: In XSLT 2.0, you could have probably made use of xsl:for-each-group, using its group-starting-with attribute. In XSLT 1.0 though, this can be achieved by use of keys. You can define a key to look up the Loop-2000B elements by their first preceding Loop-2000A element
<xsl:key name="B" match="ex:Loop-2000B" use="generate-id(preceding-sibling::ex:Loop-2000A[1])" />

Similarlym you could do the same for associating Loop-2000C elements by their first preceding Loop-2000B element (Although this may not be necessary if you say there can be at most only one Loop-2000C element for each Loop-2000B
<xsl:key name="C" match="ex:Loop-2000C" use="generate-id(preceding-sibling::ex:Loop-2000B[1])" />

The generate-id function is an XSLT function that can be used to generate a unique id for each node (If one of their existing child elements could uniquely identify the element, you could also use that). Note the use of the ex: prefix is because all the elements in your XML are in a namespace, so XSLT needs to know which namespaces elements are in.
In your XSLT you would start off by selecting just the Loop-2000A elements.
<xsl:apply-templates select="ex:Loop-2000A" />

Then, within the template that matches ex:Loop-2000A you would select all the associated ex:Loop-2000B elements using the key
<xsl:apply-templates select="key('B', generate-id(current()))" />

You would take a similar approach for getting the ex:Loop-2000C in the template that matches ex:Loop-2000B. Although, if there was ever only going to be at most one such ex:Loop-2000C element, you could do this and not worry about the key in this case:
<xsl:apply-templates select="following-sibling::*[1][self::ex:Loop-2000C]" />

This gets the very following sibling element, but only if it is a Loop-2000C element.
Finally, other existing elements can be matched and copied with the Identity Transform
<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>

Try this XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
     xmlns:ex="http://www.example.org">

  <xsl:output method="xml" omit-xml-declaration="yes" indent="yes" />
  <xsl:key name="B" match="ex:Loop-2000B" use="generate-id(preceding-sibling::ex:Loop-2000A[1])" />
  <xsl:key name="C" match="ex:Loop-2000C" use="generate-id(preceding-sibling::ex:Loop-2000B[1])" />

  <xsl:template match="*[ex:Loop-2000A]">
    <xsl:copy>
      <xsl:apply-templates select="@*"/>
      <xsl:apply-templates select="ex:Loop-2000A" />
      <xsl:apply-templates select="*[not(self::ex:Loop-2000A)][not(self::ex:Loop-2000B)][not(self::ex:Loop-2000C)]" />
    </xsl:copy>
  </xsl:template>

  <xsl:template match="ex:Loop-2000A">
    <xsl:copy>
      <xsl:apply-templates select="@*"/>
      <xsl:apply-templates select="key('B', generate-id(current()))" />
      <xsl:apply-templates />
    </xsl:copy>
  </xsl:template>

  <xsl:template match="ex:Loop-2000B">
    <xsl:copy>
      <xsl:apply-templates select="@*"/>
      <xsl:apply-templates select="key('C', generate-id(current()))" />
      <xsl:apply-templates />
    </xsl:copy>
  </xsl:template>

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

redpajama_set_name: RedPajamaStackExchange


text:
Q: getting NGINX to work with gunicorn web application
This is my first time deploying a FastAPI + gunicorn web application with NGINX and the struggle is real.
My web app is running on an AWS EC2 machine using Docker.
What I've done so far:

*

*register a domain with godaddy - let's call the domain example.club

*Setup a DNS A record pointing to my server's public IP Address (via godaddy DNS management page).

*created a site-conf.conf file and put it into /etc/nginx/sites-available. The file has the following configuration:

server {
    listen 80;
    listen 443;
    server_name example.club;

    location / {
            proxy_pass http://127.0.0.1:8080/;
            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
    }
}

*Linked my .conf file to /etc/nginx/sites-enabled with the following command:
sudo ln -s /etc/nginx/sites-available/site-conf.conf /etc/nginx/sites-enabled/site-conf.conf

*Restarted my NGINX service using the command: sudo systemctl restart nginx.
When looking at the journalctl logs, everything looks normal:
-- Unit nginx.service has begun starting up.
Nov 14 19:14:42 <server-address> nginx[16558]: nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
Nov 14 19:14:42 <server-address> nginx[16558]: nginx: configuration file /etc/nginx/nginx.conf test is successful
Nov 14 19:14:42 <server-address> systemd[1]: Failed to read PID from file /run/nginx.pid: Invalid argument
Nov 14 19:14:42 <server-address> sudo[16537]: pam_unix(sudo:session): session closed for user root
Nov 14 19:14:42 <server-address> systemd[1]: Started The nginx HTTP and reverse proxy server.
-- Subject: Unit nginx.service has finished start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit nginx.service has finished starting up.
--
-- The start-up result is done.

At this point, when opening up http://example.club I can see a "Thanks for using Amazon Linux" page. To me, this confirms that my domain correctly points to my server's IP address + NGINX is setup correctly.

*Now, all I want is to "connect" my NGINX proxy with my dockerized GUNICORN + FastAPI application (in order to expose my APIs to the world).To do this, I use the following Dockerfile:

FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7
WORKDIR /app
COPY . /app
# add files to Docker environment
...
# run app
RUN pip install -r requirements.txt
EXPOSE 8080
CMD ["gunicorn", "-b", "127.0.0.1:8080", "-k", "uvicorn.workers.UvicornWorker", "main:app"]

*Finally, I build my image (sudo docker build -t myimage .) and run the container:

sudo docker run --name mycontainer -e PYTHONUNBUFFERED=1 -p 8080:8080 -d myimage

while making sure I publish port 8080 correctly.
The container's logs look normal:
[2020-11-14 17:32:34 +0000] [1] [INFO] Starting gunicorn 20.0.4
[2020-11-14 17:32:34 +0000] [1] [INFO] Listening at: http://127.0.0.1:8080 (1)
[2020-11-14 17:32:34 +0000] [1] [INFO] Using worker: uvicorn.workers.UvicornWorker
[2020-11-14 17:32:34 +0000] [8] [INFO] Booting worker with pid: 8
[2020-11-14 17:32:34 +0000] [8] [INFO] Started server process [8]
2020-11-14 17:32:34,783 Started server process [8]
[2020-11-14 17:32:34 +0000] [8] [INFO] Waiting for application startup.
2020-11-14 17:32:34,783 Waiting for application startup.
[2020-11-14 17:32:34 +0000] [8] [INFO] Application startup complete.
2020-11-14 17:32:34,784 Application startup complete.

I should also mention that I opened port 8080 for TCP from any IP address by updating inbound rules in the EC2 machine's security group.
Unfortunately, when I try to access one of my APIs (http://example.club/<some-route-defined-with-FastAPI>) I get the NGINX default 404 page.
What am I doing wrong? Why isn't the NGINX proxy recognizing my routes?

A: Try deleting the default config file in /etc/nginx/sites-enabled/ (should just be called default) and in /etc/nginx/sites-available/ and add default_server on your current config in the listen 80 line.
server {
    listen 80 default_server;
    listen 443;
    server_name example.club;
    ...
}

A: For future reference, what I ended up doing was binding to "0.0.0.0":
FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7
WORKDIR /app
COPY . /app
# add files to Docker environment
...
# run app
RUN pip install -r requirements.txt
EXPOSE 8080
CMD ["gunicorn", "-b", "0.0.0.0:8080", "-k", "uvicorn.workers.UvicornWorker", "main:app"]

I also slightly modified my NGINX site-conf.conf (removing the listens):
server {
    server_name example.*;

    location / {
            proxy_pass http://127.0.0.1:8080/;
            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Finally, I installed python-certbot-nginx:
sudo yum install python-certbot-nginx

and ran it with:
sudo certbot --nginx -d example.club -d www.example.club

This setup allowed me to connect to my domain with HTTPS, but I had one more problem: I could still reach my webserver with HTTP by explicitly reaching for port 8080 (curl http://example.club:8080/<api-endpoint>).
To solve that, I headed over to the security group menu in the AWS website, and only allowed access to port 8080 from my machine's IP:
screenshot


text:
Q: Finding the value of an auto-increment field I have a simple registration form which creates a new record in "Students" table:
cur = con.cursor()
query = "INSERT INTO students (Name, Address, Major, Phone, Email, Password) values (%s, %s, %s, %s, %s, %s)"
args = [name, address, major,phone, email, password]

cur.execute(query, args)
con.commit()

The column Id is auto-incremented, so in order to get the last Id, I select Max
query = "SELECT MAX(Id) FROM students;"
cur.execute(query)
id = cur.fetchone()[0]

It works in my little homework-project, but how would it be done in a heavy-loaded project, where there is a possibility of something being created before the select statement?

A: Use lastrowid attribute:
...
cur.execute(query, args)
id = cur.lastrowid


text:
Q: Do some arithmetics with results of regexp searches in elisp Some time ago @Oleg Pavliv explained in https://unix.stackexchange.com/questions/47615/emacs-simple-arithmetics-in-query-replace how to do simple arithmetics in query replace (interactively) in emacs.
Now I want to use the same method for a small elisp program but it doesn't work. Consider for example the following minimal example of elisp code:
(defun Nshift ()
(interactive)
(query-replace-regexp "\\([0-9]+\\)\\.Number" "\\,((+ 3 \\#1)).Number")
)

Now suppose I run Nshift in a buffer which contains for example the string 4.Number then I get the following error message.
match-substitute-replacement: Invalid use of `\' in replacement text

How would a correct elisp implementation of Nshift look like?
Edit:
I don't see how Seans answer generalizes with easy and readable syntax to more complicated replacements (which I need in my application), so for example what would be the correct (and easy to read) equivalent to
(query-replace-regexp "\\([0-9]+\\)\\.Number.\\([0-9]+\\)" "\\,((+ 3 \\#1)).Number.\\,((+ 8 \\#2))")

A: Like this:
(defun Nshift ()
  (interactive)
  (while (search-forward-regexp "\\([0-9]+\\)\\.Number" nil t)
    (replace-match (format "%s.Number" (+ 3 (string-to-number (match-string 1)))))))

EDITED TO ADD:
Your expanded example could be implemented in this way:
(defun Nshift ()
  (interactive)
  (while (search-forward-regexp "\\([0-9]+\\)\\.Number\\.\\([0-9]+\\)" nil t)
    (replace-match
     (number-to-string (+ 3 (string-to-number (match-string 1))))
     nil nil nil 1)
    (replace-match
     (number-to-string (+ 8 (string-to-number (match-string 2))))
     nil nil nil 2)))

It's actually even easier than my original solution, because I forgot that replace-match has an optional fifth argument that causes it to replace just a single subexpression, and saves you from having to duplicate the fixed text (".Number.") in the replacement text.
There's some refactoring that could be done here:
(defun increment-match-string (match-index increment)
  (replace-match
   (number-to-string (+ increment (string-to-number (match-string match-index))))
   nil nil nil match-index))

Then Nshift could be implemented like so:
(defun Nshift ()
  (interactive)
  (while (search-forward-regexp "\\([0-9]+\\)\\.Number\\.\\([0-9]+\\)" nil t)
    (increment-match-string 1 3)
    (increment-match-string 2 8)))


text:
Q: In the mentioned url i need to get only first dictionary from the url? In this order detail array i am having 10 dictionaries but i need to display only first dictionary can any one help me how to implement this ?
http://www.json-generator.com/api/json/get/bUKEESvnvS?indent=2
here is my code shown below
func downloadJsonWithURL() {
        let url = NSURL(string: self.url)
        URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
            if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
               self.orderdetailsArray = (jsonObj!.value(forKey: "Orders detail") as? [[String: AnyObject]])!
                for array in self.orderdetailsArray {
                    let key = "OrderId"
                    let value = "#1000501"
                    for (key,value) in array{
                    if let addressDict = array as? NSDictionary{
                        if let orderid = addressDict.value(forKey: "OrderId"){
                            self.orderid.append(orderid as! String)
                        }
                        if let orderdate = addressDict.value(forKey: "OrderDate"){
                            self.orderdate.append(orderdate as! String)
                        }
                        if let subtotal = addressDict.value(forKey: "SubTotal"){
                            self.subTotal.append(subtotal as! Int)
                        }
                        if let Shipping = addressDict.value(forKey: "Shipping"){
                            self.shippingPrice.append(Shipping as! Int)
                        }
                        if let tax = addressDict.value(forKey: "Tax"){
                            self.tax.append(tax as! Int)
                        }
                        if let grandtotal = addressDict.value(forKey: "GrandTotal"){
                            self.grandTotal.append(grandtotal as! Int)
                        }
                        if let shippingAddress = addressDict.value(forKey: "ShippingAddress"){
                            self.shippingAddress.append(shippingAddress as AnyObject)
                        }
                        if let shippingMethod = addressDict.value(forKey: "ShippingMethod"){
                            self.shippingMethod.append(shippingMethod as AnyObject)
                        }
                        if let billingAddress = addressDict.value(forKey: "BillingAddress"){
                            self.billingAddress.append(billingAddress as AnyObject)
                        }
                        if let paymentMethod = addressDict.value(forKey: "PayMentMethod"){
                            self.paymentMethod.append(paymentMethod as AnyObject)
                        }
                        self.itemsArray = addressDict.value(forKey: "Items detail") as! [[String : AnyObject]]
                    }
                }
                }
                OperationQueue.main.addOperation({
                    self.tableDetails.reloadData()
                })
            }
        }).resume()
    }

A: Hi if you want first dictionary of that
self.orderdetailsArray

then
if let firstDictInfo = self.orderdetailsArray.first as? [String:Any] {
 // Do your stuff here
 print(firstDictInfo["OrderId"])
}

A: Do this. :
let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary

guard let Ordersdetail = jsonObj["Orders detail"] as? [NSDictionary] else {
        print("Cannot find key 'Orderdetails' in \(jsonObj)")
        return
    }

To access the contents of the first dictionary do this:
 var orderid = Ordersdetail[0]["OrderId"]!
 var shippingadress = Ordersdetail[0]["ShippingAddress"]!
 var total = Ordersdetail[0]["GrandTotal"]!
 var subtotal = Ordersdetail[0]["SubTotal"]!
 var tax = Ordersdetail[0]["Tax"]!
 var shipping = Ordersdetail[0]["Shipping"]!

A: Instead of looping through the whole dictionary is dictionaries, you should just take the first dictionary and only parse that. There was also quite a few other conceptual problems with your code. In Swift, don't use NSDictionary, but use the native Swift version, Dictionary, which keeps the type information of its contents. Also, use conditional casting to make sure your program doesn't crash even if the received data is wrong/unexpected and don't use force unwrapping of optionals.
Also, when parsing a JSON response in Swift, in general it is not necessary and not a good idea to iterate through the key-value pairs of the dictionaries in the response. You should know what data structure you expect, otherwise you can't parse it properly and since you can directly access dictionary values in Swift if you know the key it corresponds to, there's no need to iterate through the dictionary in a loop.
func downloadJsonWithURL() {
        let url = URL(string: self.url)
        URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) -> Void in
            if let jsonObj = (try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)) as? [String:Any] {
               guard let self.orderdetailsArray =  jsonObj["Orders detail"] as? [[String: AnyObject]] else {return}
               guard let firstOrderDetails = self.orderdetailsArray.first else {return}
               let key = "OrderId"
               let value = "#1000501"
               if let ordered = firstOrderDetails["OrderId] as? String {
                   self.orderid.append(orderid)
               }
               if let orderdate = firstOrderDetails["OrderDate"] as? String{
                   self.orderdate.append(orderdate)
               }
               if let subtotal = firstOrderDetails["SubTotal"] as? Int{
                   self.subTotal.append(subtotal)
               }
               if let shipping = firstOrderDetails["Shipping"] as? Int{
                   self.shippingPrice.append(shipping)
               }
               if let tax = firstOrderDetails["Tax"] as? Int{
                  self.tax.append(tax)
               }
               if let grandtotal = firstOrderDetails["GrandTotal"] as? Int{
                  self.grandTotal.append(grandtotal)
               }
               if let shippingAddress = firstOrderDetails[ "ShippingAddress"] as? AnyObject{ //why don't you store it as a String?
                  self.shippingAddress.append(shippingAddress)
               }
               if let shippingMethod = firstOrderDetails[ "ShippingMethod"] as? AnyObject{
                  self.shippingMethod.append(shippingMethod)
               }
               if let billingAddress = firstOrderDetails[ "BillingAddress"] as? AnyObject {
                  self.billingAddress.append(billingAddress)
               }
               if let paymentMethod = firstOrderDetails ["PayMentMethod"] as? AnyObject{
                  self.paymentMethod.append(paymentMethod)
               }
               guard let itemDetails = firstOrderDetails["Items detail"] as? [[String : AnyObject]] else {return}
               self.itemsArray = itemDetails
                    }
                }
                }
                OperationQueue.main.addOperation({
                    self.tableDetails.reloadData()
                })
            }
        }).resume()
    }

I haven't compiled and run the code, so make sure you check for any typos/inconsistencies. Also, make sure you change the types of the objects you store are AnyObjects to specific types.


text:
Q: Android device connecting technologies available for development I have searched a lot over internet about device to device connecting technologies in other words device to device connection implementation in the concern of hardware and software.
Someone please tell me a whole list of technologies available for the connection between two specific android device, no matter what hardware specification they have in them.
I want a overview over those technology which are used to make data transfer between two devices using wireless connection, Like : Wifi, Bluetooth, etc.
This question i am asking because of client asking me about a "Acoustic sound technology".
I don't know about it and neither i found something related to it.
Help will be appreciated.
EDIT
Now i know that it is Ultrasonic data transfer which uses device's mic to generate a sort of sound frequency and get the data on the behalf of that frequency, i don't know exactly about that's why i asked it here.
Sorry if it difficult to understand, I am a little bad at English.

A: Hardware layer of connectivity limited by common device modules: Wi-Fi, Bluetooth, NFC, Camera<->Display and Microphone<->Speaker. Each module has it's own software data transferring methods. I think that your client meant ultrasonic data transfer. Basically this method based on high-frequency signals which are emitted by speaker of one device and received by microphone of another device. For instance Yamaha uses ultrasound in InfoSound technology.


text:
Q: Number of ways to sit 6 girls and 6 boys together with no two girls together. As the title of the question explains:
What I thought on the very first instant was that we will make them sit alternate hence the answer will be 2 * 6! * 6!
But then in some book I saw the explanation that there are 7 places where a Girl can sit out of the given 12 seats. Hence the answer is 7C6 * 6! * 6!.
But I don't get how are there 7 places for girls to sit.
I understand that howcome my original assumption of alternate placement was wrong. Because you can do
G B B G B G B G B G B G

And so on. But the authors explanation of 7 seats for girls is still not clear to me.
Cheers.

A: Let the boys arrange themselves in $6!$ ways. Girls can sit in between or besides them such that maximum one girl is between any $2$ boys.
$$\text{1 B 2 B 3 B 4 B 5 B 6 B 7}$$
Clearly, there are $1-7$ places for $6$ girls. $7$ places. I bet you can take from here

A: Another way to look at this problem is to say that either the boys and girls are alternating (2 ways), or there is a pair of two boys somewhere in between two of out of the 6 girls (5 ways to choose where the pair is, since the pair cannot be on the end). So there are 7 possible cases before you choose the ordering of the boys and girls.


text:
Q: Force python subprocesses to run in specific order I have a program in which I need two processes to run simultaneously and one process needs to start before the other one. There are other subprocesses involved based on things like how far along in the script I am and what errors occur during some processes but none of those need to run while the main two are running.
sys.stdout.flush()

proc1 = subprocess.Popen(<command line tool>, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
proc1_data, proc1_stderr = proc1.communicate()
time.sleep(0.1) # allow time proc1 to kick in

proc2 = subprocess.Popen(<command line tool>, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
proc2_data, proc2_stderr = proc2.communicate()

proc2.wait()
proc1.kill()
proc2.kill()

# do error checking among other things in other subprocesses based on this data

This works some of the time, but from looking at LEDs on hardware that turn on during proc1 and proc2, I can see that they are sometimes out of sync, as in proc2 will sometimes run and finish before proc1 turns on.
Is there any way to ensure that the processes start in order? And that proc2 runs before proc1 finishes?

A: Once they're started, subprocesses are independent entities which will run at whatever speed they feel like. You can't control what happens inside each subprocesses - unless you use some form of inter-process communication (IPC) between them.
It's not entirely clear what you're trying to do here, but if it's the case that you don't want subprocess 2 to pass a specific checkpoint until subprocess 1 has passed its own checkpoint, IPC is exactly what you need here. If you're on a Unix-ish system (including macOS), you could use a semaphore: have subprocess 2 call sem_wait to block until subprocess 1 calls sem_post. Windows has a very similar concept.


text:
Q: How can I get my Mic working under Debian GNOME? I recently installed GNOME onto my Debian web server (other PC died so I wanted a desktop).
I'm a total Linux Desktop beginner, I managed to get Skype installed - but Linux appears to not like my Mic.
The Mic / Speakers are on-board, speakers work fine, but the mic just makes a high-pitched squealing noise.
My question is: How should a GNOME beginner go about fixing this?

A: If you're lucky, it's just feedback from the mic setting being so sensitive that it's picking up the output of the speakers. To make sure it's not this, plug in some headphones and listen to them when you turn the mic on.
If it's not that - I remember having a similar problem a while back and it turned out the driver for my soundcard needed upgrading (otherwise they locked up when accessing the mic). Without knowing your sound card, it's hard to say where to find such an upgrade, but what version of Debian are you running?

A: You can consider using a USB headset, which the system sees as a separate sound card.  This works much better for me.


text:
Q: A probably simple combinatorics question I've faced the following problem, it comes from physics actually, but the precise details are of no importance. Consider a set $\{x_{n}\}_{n=1, ..., N}$. We construct the following function
$$F(\{x_{n}\}_{n=1, ..., N}, \{q_{m}\}_{m=1, ..., M})=\sum_{n_{1}=1}^{N}...\sum_{n_{M}=1}^{N}\exp\Bigg(-i\sum_{m=1}^{M}q_{m}x_{n_{m}}\Bigg).$$
The question is as follows: what is the number of terms in the series above such that the number $S\in\{0, ..., M\}$ of $x_{n_{m}}$s in the exponent are equal to one another?
For example for $M=1$ there are $N$ terms with one $x$ equal to itself. for $M=2$ we have $N$ terms with both $x$ being equal and $N(N-1)$ terms with unequal $x$, for $M=3$ we have $N$ terms with all $3$ $x$ being the same, $3N(N-1)$ terms (if I'm correct) with $2$ $x$ equal and not equal to the third, and $N(N-1)(N-2)$ terms with distinct $x$, etc. Is there a general formula in terms of $N$ and $M$ for this thing?
PS Sorry if I was not being clear enough, I'm not versed in these things.
Update: I have a feeling that the number of terms with two of $x$s being equal is given by
$$\frac{1}{2}M(M-1)N(N-1), \ M=1, 2, ...$$

A: We have functions  $\{1,\dots,M\} \rightarrow \{1,\dots,N\}$ and for each $S\in \{1,\dots,M\}$ you want to know how many such functions take on exactly $S$ distinct values.
This is one of the problems in the twelvefold way and the answer is given by $\binom{N}{S}{ M \brace S }S!$ where the curly brackets are stirling coefficients of the second kind.
In particular when $S=1$ we get $\binom{N}{1}{ M \brace 1 } 1! = N\times 1 \times 1 = N$.
When $S>N$ we get $\binom{N}{S}{M \brace S} S! = 0 \times {M \brace S} S! = 0$
when $S=2$ we get $\binom{N}{2}{M \brace 2} 2!= N(N-1)(\frac{2^{M}-2}{2})$
When $S=M$ and $N\geq M$ we get $\binom{N}{M}{ M \brace M} M! = N(N-1)\dots(N-M+1)$

A: It looks like this is equivalent to asking the expected number of duplicates, triplicates, etc. from a series of random draws. Does this answer your question, then?
https://stats.stackexchange.com/questions/57347/expected-number-of-duplicates-triplicates-etc-when-drawing-with-replacement


text:
Q: Arraylist Seems Empty I want to check the nickname is already taken or not data comes from firestorm and adds to the list but before if the statement the list seems empty and I can't control nickname is already taken or not here is my code I have no idea why does it seem empty.
Here is my Code
public class NickName extends AppCompatActivity {
private String userid;
private FirebaseAuth mAuth;
private FirebaseFirestore firestore;
EditText nickText;
String email;
private ArrayList<String> nicklist;
String nickforcheck;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_nick_name);
    mAuth=FirebaseAuth.getInstance();
    nicklist=new ArrayList<>();
    firestore=FirebaseFirestore.getInstance();
    nickText=findViewById(R.id.nicktext);
    Intent intent=getIntent();
    email = intent.getStringExtra("email");
}

public void kayıt(View view){
    CollectionReference collectionReference=firestore.collection("Kullanıcılar ve Skorlar");
    collectionReference.addSnapshotListener(new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) {
            if(error!=null){
                Log.e("tag",error.getLocalizedMessage());
            }
            if(value!=null){
                for(DocumentSnapshot snapshot:value.getDocuments()){
                    Map<String,Object> userdata=snapshot.getData();
                    nickforcheck=(String) userdata.get("nick");
                    nicklist.add(nickforcheck);
                }
            }
        }
    });
    String nick=nickText.getText().toString();
    userid=mAuth.getCurrentUser().getUid();
    DocumentReference documentReference=firestore.collection("Kullanıcılar ve Skorlar").document(userid);
    Map<String,Object> userdata=new HashMap<>();
    System.out.println(nicklist);
    if(nicklist.contains(nick)) {
        Toast.makeText(this, "Bu Kullanıcı İsmi Zaten Mevcut", Toast.LENGTH_SHORT).show();
    }else{
        userdata.put("nick",nick);
        userdata.put("email",email);
        userdata.put("skor",0);
        documentReference.set(userdata).addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void unused) {
                Log.d("Tag","Veri alındı"+userid);
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.d("Tag","işlem başarısız"+e.toString());
            }
        });
        Intent intent=new Intent(NickName.this,Secimekrani.class);
        startActivity(intent);
        finish();
    }

}
}

A: You got empty nickList because ,all code outside addSnapshotListener will be executed before get the snapshot from firestore .so do all work ,once you successfully get snapshot.
  public void kayıt(View view){
    CollectionReference collectionReference=firestore.collection("Kullanıcılar ve Skorlar");
    collectionReference.addSnapshotListener(new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) {
            if(error!=null){
                Log.e("tag",error.getLocalizedMessage());
            }
            if(value!=null){
                for(DocumentSnapshot snapshot:value.getDocuments()){
                    Map<String,Object> userdata=snapshot.getData();
                    nickforcheck=(String) userdata.get("nick");
                    nicklist.add(nickforcheck);

                   String nick=nickText.getText().toString();
                  userid=mAuth.getCurrentUser().getUid();

                   DocumentReference     documentReference=firestore.collection("Kullanıcılar ve Skorlar").document(userid);
            Map<String,Object> userdata=new HashMap<>();

  System.out.println(nicklist);
    if(nicklist.contains(nick)) {
        Toast.makeText(this, "Bu Kullanıcı İsmi Zaten Mevcut", Toast.LENGTH_SHORT).show();
    }else{
        userdata.put("nick",nick);
        userdata.put("email",email);
        userdata.put("skor",0);
        documentReference.set(userdata).addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void unused) {
                Log.d("Tag","Veri alındı"+userid);

                 //once user data added in firestore ,finish your activity .
                 Intent intent=new Intent(NickName.this,Secimekrani.class);
                startActivity(intent);
                finish();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.d("Tag","işlem başarısız"+e.toString());
            }
        });

    }

                }
            }
        }
    });

}
}


text:
Q: How to get the value of an autoincreament field from SQLiteDatabase in Android? I have a table in SQLiteDatabase with only one column which is autoincreament...
CREATE TABLE [LEADID] (
[lead_id] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT
 )

I want the value of autoincrement to start from 10000.
How do i get the value of this column???
How do i put an insert and a select statement to get the autoincreamented value??
i basically dont know how to invoke this table to generate this autoincrement value...
how do i do that??
Please help!!! thanks in advance!!

A: You can set new auto-increment starting value for table mytable using this:
UPDATE sqlite_sequence SET seq = 10000 WHERE name = 'mytable'

If your table already has primary key present with value that conflicts (like 10000), next insert will automatically change auto-increment value to max_value+1.


text:
Q: How to use placeholders in std::bind I give you a simple snippet of code:
#include <functional>
#include <iostream>

using namespace std;

void module2(int x, int y)
{
    cout << "\n "  << __PRETTY_FUNCTION__ << ":\t x = " << x  << "\t y = " << y;
}

void module3(int x, int y, int z)
{
    cout << "\n "  << __PRETTY_FUNCTION__ << ":\t x = " << x  << "\t y = " << y << "\t z = " << z;
}

int main()
{
    using namespace std::placeholders;

    int a = 39;
    int b = 7;
    int c = 3;

    auto func_m2 = bind(&module2, _1, _2);
    func_m2(a, b);                                   //  OK

    auto func_m2_PH = bind(&module2, _2, _1);
    func_m2_PH(b, a);                                   //  OK

    //---------------------------------------------------------

    auto func_m3 = bind(&module3, a, b, c);
    func_m3();                                          //  OK

    cout << "\n With PlaceHolders:";

    auto func_m3_PH_0 = bind(&module3, _1, _2, _3);
    func_m3_PH_0(a, b, c);                              //  OK

    auto func_m3_PH_1 = bind(&module3, _2, _1, _3);
    func_m3_PH_1(b, a, c);                              //  OK

    auto func_m3_PH_2 = bind(&module3, _3, _1, _2);
    func_m3_PH_2(c, a, b);                              //  KO !!!

    auto func_m3_PH_3 = bind(&module3, _3, _2, _1);
    func_m3_PH_3(c, b, a);                              //  OK

    auto func_m3_PH_4 = bind(&module3, _1, _3, _2);
    func_m3_PH_4(a, c, b);                              //  OK

    auto func_m3_PH_5 = bind(&module3, _2, _3, _1);
    func_m3_PH_5(b, c, a);                              //  KO !!!

    return 0;
}

link to coliru
When the first argument is a function that takes 2 arguments everything is fine: the code works as I expect.
However when the first std::bind's parameter is a function with 3 (or more) arguments the code stops working as I expect (these cases are marked with 'KO !!!' )
But, what do I expect from std::bind and its placeholders?
In this particular case I expect the output:
void module3(int, int, int):     x = 39  y = 7   z = 3
every time that I invoke the function object generated from
bind(&module3, etc...)

but, more in general:
I expect that the parameter that replaces the placeholder named '_K' will be the K-th parameter passed to the underlying function (i.e. the first parameter of the std::bind).
What is wrong? My understanding of the std::bind or there is a bug in this function template?
Thanks for your time.

A: You have it backwards. The _K placeholder defines the mapping from the Kth argument passed to the generated functor (the result of bind) to the position of the placeholder in the parameters of the bound function. So putting _3 in the first argument position of bind means that the first argument given to the bound function will be the third parameter given to the generated function.
The other cases worked because your reversed logic just so happened to be the same as the correct version.


text:
Q: Ctypes: fast way to convert a return pointer to an array or Python list I am using ctypes to pass an array pointer to a dll and return a pointer to an array of doubles that was created using malloc in the dll. On return to Python, I need a fast way to convert the pointer to an array or Python list.
I can use this list comp, but it's slow because there are 320,000 data points:
list_of_results = [ret_ptr[i] for i in range(320000)]

Ideally I would create the array in Python and pass it to the dll, but I have to create it using malloc in the dll because this is a dynamic array where I don't know beforehand how many data elements there will be (although the return pointer also returns the number of data elements, so I know how many there are on return to Python) -- I use realloc to extend the array size dynamically in the dll; I can use realloc with a Python array, but a call to free() at the end is not guaranteed to work.
Here is the relevant Python code:

CallTest = hDLL.Main_Entry_fn
CallTest.argtypes = [ctypes.POINTER(ctypes.c_double), ctypes.c_int64]
CallTest.restype = ctypes.POINTER(ctypes.c_double)
ret_ptr = CallTest(DataArray, number_of_data_points)
list_of_results = [ret_ptr[i] for i in range(320000)]

So my question is: what is the fastest way to convert a pointer returned from a dll to a Python list or array?  The method shown above is too slow.

A: Slicing a ctypes array or pointer will automatically produce a list:
list_of_results = ret_ptr[:320000]

Depending on what you mean by "convert the pointer to an array" and what output types you can work with, you may be able to do better. For example, you can make a NumPy array backed by the buffer directly, with no data copying:
buffer_as_ctypes_array = ctypes.cast(ret_ptr, ctypes.POINTER(ctypes.c_double*320000))[0]
buffer_as_numpy_array = numpy.frombuffer(buffer_as_ctypes_array, numpy.float64)

This will of course break horribly if you deallocate the buffer while something still needs it.


text:
Q: 404 Error message - can't find SignalR/Hubs I know this question has been posted elsewhere here, but can't find a working solution.
I have 2 applications: 1 is an older version of the other and runs a SignalR chat app just fine from VS2015 (using IIS Express), the other app is basically the same except for changes elsewhere (its a shopping cart), but the chat pages, scripts, and references are identical (including the path). Web.config, global.cs, startup are all identical and both run MVC5.
The older app uses a standard HTML page and references the SignalR/Hubs just fine (no 404 error) with the following:
Here's the agent.html page:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>LiveChat</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="../Scripts/JqueryUI/jquery-ui.css" rel="stylesheet" type="text/css" />
    <link href="assets/chat.css" rel="stylesheet" />

Chat Agent Panel

Show Real Time Visits

Agent to Agent Chat

Configure Chat

Logged in as:

Not logged in

Chat Sessions

Log In to Start Accepting Chat Requests

                <fieldset>
                    <legend>Enter your agent name and password</legend>

                        Agent Name
                        <input id="login-name" type="text" class="form-control" placeholder="agent name">

                        Agent Password
                        <input id="login-pass" class="form-control" type="password">

                    <button id="login-btn" type="submit" class="button-1">Start accepting chat ></button>
                </fieldset>

Real time visits

                                Visited on
                                Page
                                Referrer
                                City
                                Country
                                In Chat
                                Invite

                    <input id="post-msg" type="text" style="width: 100%;" placeholder="Enter your text here. Enter /list for a list of available commands" />

                    <button id="post-btn" class="button-1" style="margin-top: 6px;">Send</button>

This works fine in the old app, but the auto-generated signalr/hubs javascript is not created.
The startup.cs:
using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(WEBCHAT.Startup))]

namespace WEBCHAT
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}

ChatHub.cs (once again, it works find in the old, not the new)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using System.Threading.Tasks;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Net.Mail;
using System.Collections.Concurrent;
using System.Diagnostics;

namespace WEBCHAT
{
    public class ChatHub : Hub
    {
        private const string CONFIG_FILE = "webchat.dat";

        private static ConcurrentDictionary<string, Agent> Agents;
        private static ConcurrentDictionary<string, string> ChatSessions;

        public void AgentConnect(string name, string pass)
        {
            if (Agents == null)
                Agents = new ConcurrentDictionary<string, Agent>();

            if (ChatSessions == null)
                ChatSessions = new ConcurrentDictionary<string, string>();

            string hashPass = ToHash(pass);

            var config = GetConfig();
            if (config == null || config.Length < 2)
            {
                Clients.Caller.loginResult(false, "config", "");
            }
            else if ((config[0] == hashPass) || (config[1] == hashPass))
            {
                var agent = new Agent()
                {
                    Id = Context.ConnectionId,
                    Name = name,
                    IsOnline = true
                };

                // if the agent is already signed-in
                if (Agents.Any(x => x.Key == name))
                {
                    agent = Agents[name];

                    Clients.Caller.loginResult(true, agent.Id, agent.Name);

                    Clients.All.onlineStatus(Agents.Count(x => x.Value.IsOnline) > 0);
                }
                else if (Agents.TryAdd(name, agent))
                {

                    Clients.Caller.loginResult(true, agent.Id, agent.Name);

                    Clients.All.onlineStatus(Agents.Count(x => x.Value.IsOnline) > 0);
                }
                else
                {
                    Clients.Caller.loginResult(false, "error", "");
                }
            }
            else
                Clients.Caller.loginResult(false, "pass", "");
        }

        public void ChangeStatus(bool online)
        {
            var agent = Agents.SingleOrDefault(x => x.Value.Id == Context.ConnectionId).Value;
            if (agent != null)
            {
                agent.IsOnline = online;
                Clients.All.onlineStatus(Agents.Count(x => x.Value.IsOnline) > 0);
            }
        }

        public void EngageVisitor(string connectionId)
        {
            var agent = Agents.SingleOrDefault(x => x.Value.Id == Context.ConnectionId).Value;
            if (agent != null)
            {
                ChatSessions.TryAdd(connectionId, agent.Id);
                Clients.Caller.newChat(connectionId);
                Clients.Client(connectionId).setChat(connectionId, agent.Name, false);
                Clients.Caller.addMessage(connectionId, "system", "You invited this visitor to chat...");
                Clients.Client(connectionId).addMessage(agent.Name, "Hey there. I'm " + agent.Name + " let me know if you have any questions.");
            }
        }

        public void LogVisit(string page, string referrer, string city, string region, string country, string existingChatId)
        {
            if (Agents == null)
                Agents = new ConcurrentDictionary<string, Agent>();

            Clients.Caller.onlineStatus(Agents.Count(x => x.Value.IsOnline) > 0);

            var cityDisplayName = GetCityDisplayName(city, region);
            var countryDisplayName = country ?? string.Empty;

            if (!string.IsNullOrEmpty(existingChatId) &&
                ChatSessions.ContainsKey(existingChatId))
            {
                var agentId = ChatSessions[existingChatId];
                Clients.Client(agentId).visitorSwitchPage(existingChatId, Context.ConnectionId, page);

                var agent = Agents.SingleOrDefault(x => x.Value.Id == agentId).Value;

                if (agent != null)
                    Clients.Caller.setChat(Context.ConnectionId, agent.Name, true);

                string buffer = "";
                ChatSessions.TryRemove(existingChatId, out buffer);

                ChatSessions.TryAdd(Context.ConnectionId, agentId);
            }

            foreach (var agent in Agents)
            {
                var chatWith = (from c in ChatSessions
                                join a in Agents on c.Value equals a.Value.Id
                                where c.Key == Context.ConnectionId
                                select a.Value.Name).SingleOrDefault();

                Clients.Client(agent.Value.Id).newVisit(page, referrer, cityDisplayName, countryDisplayName, chatWith, Context.ConnectionId);
            }
        }

        public void RequestChat(string message)
        {
            // We assign the chat to the less buzy agent
            var workload = from a in Agents
                           where a.Value.IsOnline
                           select new
                           {
                               Id = a.Value.Id,
                               Name = a.Value.Name,
                               Count = ChatSessions.Count(x => x.Value == a.Value.Id)
                           };

            if (workload == null)
            {
                Clients.Caller.addMessage("", "No agent are currently available.");
                return;
            }

            var lessBuzy = workload.OrderBy(x => x.Count).FirstOrDefault();

            if (lessBuzy == null)
            {
                Clients.Caller.addMessage("", "No agent are currently available.");
                return;
            }

            ChatSessions.TryAdd(Context.ConnectionId, lessBuzy.Id);

            Clients.Client(lessBuzy.Id).newChat(Context.ConnectionId);

            Clients.Caller.setChat(Context.ConnectionId, lessBuzy.Name, false);

            Clients.Client(lessBuzy.Id).addMessage(Context.ConnectionId, "visitor", message);
            Clients.Caller.addMessage("me", message);
        }

        public void Transfer(string connectionId, string agentName, string messages)
        {
            if (!Agents.ContainsKey(agentName))
            {
                Clients.Caller.addMessage(Context.ConnectionId, "system", "This agent does not exists: " + agentName);
                return;
            }

            var agent = Agents[agentName];
            if (!agent.IsOnline)
            {
                Clients.Caller.addMessage(Context.ConnectionId, "system", agentName + " is not online at the moment.");
                return;
            }

            if (!ChatSessions.ContainsKey(connectionId))
            {
                Clients.Caller.addMessage(Context.ConnectionId, "system", "This chat session does not exists anymore.");
                return;
            }

            string currentAgentId = "";
            if (ChatSessions.TryRemove(connectionId, out currentAgentId) &&
                ChatSessions.TryAdd(connectionId, agent.Id))
            {
                Clients.Client(agent.Id).newChat(connectionId);
                Clients.Client(agent.Id).addMessage(connectionId, "system", "New chat transfered to you.");
                Clients.Client(agent.Id).addMessage(connectionId, ">>", "Starting previous conversation");
                Clients.Client(agent.Id).addMessage("", messages);
                Clients.Client(agent.Id).addMessage(connectionId, "<<", "End of previous conversation");

                Clients.Client(connectionId).addMessage("", "You have been transfered to " + agent.Name);
                Clients.Client(connectionId).setChat(connectionId, agent.Name, true);

                Clients.Caller.addMessage(connectionId, "system", "Chat transfered to " + agentName);
            }
        }

        public void Send(string data)
        {
            Clients.Caller.addMessage("me", data);

            if (ChatSessions.ContainsKey(Context.ConnectionId))
            {
                var opId = ChatSessions[Context.ConnectionId];
                Clients.Client(opId).addMessage(Context.ConnectionId, "visitor", data);
            }
            else
            {
                Debug.WriteLine("Chat Session not found.");

                var workload = from a in Agents
                               where a.Value.IsOnline
                               select new
                               {
                                   Id = a.Value.Id,
                                   Name = a.Value.Name,
                                   Count = ChatSessions.Count(x => x.Value == a.Value.Id)
                               };

                if (workload == null)
                {
                    Clients.Caller.addMessage("", "No agent are currently available.");
                    return;
                }

                var lessBuzy = workload.OrderBy(x => x.Count).FirstOrDefault();

                if (lessBuzy == null)
                {
                    Clients.Caller.addMessage("", "No agent are currently available.");
                    return;
                }

                ChatSessions.TryAdd(Context.ConnectionId, lessBuzy.Id);

                Clients.Client(lessBuzy.Id).newChat(Context.ConnectionId);

                Clients.Caller.setChat(Context.ConnectionId, lessBuzy.Name, false);

                Clients.Client(lessBuzy.Id).addMessage(Context.ConnectionId, "system", "This visitor appear to have lost their chat session.");
                Clients.Client(lessBuzy.Id).addMessage(Context.ConnectionId, "visitor", data);
            }
        }

        public void OpSend(string id, string data)
        {
            var agent = Agents.SingleOrDefault(x => x.Value.Id == Context.ConnectionId).Value;
            if (agent == null)
            {
                Clients.Caller.addMessage(id, "system", "We were unable to send your message, please reload the page.");
                return;
            }

            if (id == "internal")
            {
                foreach (var a in Agents.Where(x => x.Value.IsOnline))
                    Clients.Client(a.Value.Id).addMessage(id, agent.Name, data);

            }
            else if (ChatSessions.ContainsKey(id))
            {
                Clients.Caller.addMessage(id, "you", data);
                Clients.Client(id).addMessage(agent.Name, data);
            }
        }

        public void CloseChat(string id)
        {
            if (ChatSessions.ContainsKey(id))
            {
                Clients.Client(id).addMessage("", "The agent close the chat session.");

                string buffer = "";
                ChatSessions.TryRemove(id, out buffer);
            }
        }

        public void LeaveChat(string id)
        {
            // was it an agent
            var agent = Agents.SingleOrDefault(x => x.Value.Id == id).Value;
            if (agent != null)
            {
                Agent tmp = null;
                if (Agents.TryRemove(agent.Name, out tmp))
                {

                    var sessions = ChatSessions.Where(x => x.Value == agent.Id);
                    if (sessions != null)
                    {
                        foreach (var session in sessions)
                            Clients.Client(session.Key).addMessage("", "The agent was disconnected from chat.");
                    }

                    Clients.All.updateStatus(Agents.Count(x => x.Value.IsOnline) > 0);
                }
            }

            // was it a visitor
            if (ChatSessions.ContainsKey(id))
            {
                var agentId = ChatSessions[id];
                Clients.Client(agentId).addMessage(id, "system", "The visitor close the connection.");
            }
        }

        public override Task OnDisconnected(bool stopCalled)
        {
            return Clients.All.leave(Context.ConnectionId);
        }

        public void SendEmail(string from, string message)
        {
            if (ValidateEmail(from) == true)
            {
                var msg = new MailMessage();
                msg.To.Add(new MailAddress(from));
                msg.Subject = "WEBCHAT - Offline Contact";
                msg.Body = "You received an offline contact from your WEBCHAT chat widget.\r\n\r\n" + Nop.Core.Html.HtmlHelper.FormatText(message, true, false, false, false, false, false);

                try
                {
                    string emResult = eMail.SendEmail(msg.Subject, msg.Body, from, "xxx@xxx.com", "mail.xxx.com", "xxx@xxx.com", "password", from, "My Chat Agent", false, null, 25, from, MailPriority.High, DeliveryNotificationOptions.None);
                }
                catch
                {

                }

            }
        }

        #region Install and config methods
        public void getInstallState()
        {
            var config = GetConfig();

            if (config != null && config.Length >= 2)
                Clients.Caller.installState(true, config[0]);
            else
                Clients.Caller.installState(false, "chattemptoken");
        }

        public void AdminRequest(string pass)
        {
            var config = GetConfig();

            if (config != null && config.Length >= 2)
            {
                if (config[0] == ToHash(pass))
                    Clients.Caller.adminResult(true, config[0]);
                else
                    Clients.Caller.adminResult(false, "");
            }
            else
                Clients.Caller.adminResult(false, "");
        }

        public void SetConfig(string token, string adminPass, string agentPass)
        {
            bool shouldSave = false;
            var config = GetConfig();

            if (config != null && config.Length >= 2)
            {
                if (config[0] == token)
                    shouldSave = true;
            }
            if (token == "chattemptoken")
                shouldSave = true;

            if (shouldSave)
            {
                string configPath = HttpContext.Current.Server.MapPath("~/App_Data/" + CONFIG_FILE);

                File.WriteAllText(
                    configPath,
                    ToHash(adminPass) + "\n" + ToHash(agentPass));

                Clients.Caller.setConfigResult(true, "Config file updated.");
            }
            else
                Clients.Caller.setConfigResult(false, "Unable to save the config file.");
        }

        private string GetCityDisplayName(string city, string region)
        {
            var displayCity = string.Empty;
            if (!string.IsNullOrEmpty(city))
            {
                displayCity = city;
                if (!string.IsNullOrEmpty(region))
                {
                    displayCity += ", " + region;
                }
            }
            return displayCity;
        }

        private string[] GetConfig()
        {
            string configPath = HttpContext.Current.Server.MapPath("~/App_Data/" + CONFIG_FILE);
            if (File.Exists(configPath))
            {
                return File.ReadAllLines(configPath);
            }
            return null;
        }

        public string ToHash(string password)
        {
            if (string.IsNullOrEmpty(password))
                return "";

            var provider = new SHA1CryptoServiceProvider();
            var encoding = new UnicodeEncoding();
            return Convert.ToBase64String(provider.ComputeHash(encoding.GetBytes(password)));
        }
        #endregion

        public bool ValidateEmail(string strCheck)
        {
            try
            {
                System.Net.Mail.MailAddress vEmailAddress = new System.Net.Mail.MailAddress(strCheck);
            }
            catch (Exception ex)
            {
                //_logger.Error(string.Format("Error validating e-mail. {0}", ex.Message), ex);
                return false;
            }
            return true;
        }
    }

    public class eMail
    {
        public static string SendEmail(string emailSubject, string emailBody, string senderAddress, string recipientAddress, string emailServer, string accountName, string accountPassword, string senderName = "", string recipientName = "", bool isHTML = true, List<string> attachmentPaths = null, int portNumber = 25, string replyToAddress = "", System.Net.Mail.MailPriority priority = MailPriority.Normal, DeliveryNotificationOptions deliveryNotification = DeliveryNotificationOptions.None)
        {
            //this will return a string of "success", if successful and an error message if not
            string retval = string.Empty;
            if (senderName.Length == 0)
            {
                senderName = senderAddress;
            }
            if (recipientName.Length == 0)
            {
                recipientName = recipientAddress;
            }
            MailMessage msg = new MailMessage(new MailAddress(senderAddress, senderName), new MailAddress(recipientAddress, recipientName));
            SmtpClient mailClient = null;
            mailClient = new SmtpClient(emailServer, portNumber);

            msg.Subject = emailSubject;
            msg.IsBodyHtml = isHTML;
            msg.Body = emailBody;

            if (attachmentPaths != null)
            {
                foreach (var attPath in attachmentPaths)
                {
                    if (File.Exists(attPath))
                    {
                        msg.Attachments.Add(new Attachment(attPath));
                    }
                }
            }

            if (accountName.Length > 0 && accountPassword.Length > 0)
            {
                System.Net.NetworkCredential userSMTPAccount = new System.Net.NetworkCredential(accountName, accountPassword);
                mailClient.UseDefaultCredentials = false;
                mailClient.Credentials = userSMTPAccount;
            }
            else
            {
                mailClient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
            }

            msg.DeliveryNotificationOptions = deliveryNotification;
            try
            {
                mailClient.Send(msg);
                retval = "success";
            }
            catch (SmtpException ex)
            {
                retval = ex.Message;
            }
            catch (Exception ex2)
            {
                retval = ex2.Message; //for general errors
            }
            finally
            {
                msg.Dispose();
            }

            return retval;
        }

    }

}

There's more, all of the code works fine on the old version, but not on the new. All the required DLLs are in the BIN folder. The package.config is identical (except an older version of OWIN - which may be suspect).
I just don't know where else to look for a difference that would explain why the old version of the Application works and the new one does not (everything loads in the new one, scripts, css, pages, etc. except the dreaded SignalR/Hubs). Is there a setting somewhere that I missed?

A: OMG! I knew the answer had to be dumb simple! It is!
First, I upgraded OWIN security to the latest version (not sure if this was the real problem).
Then, I saw a new key in the Web.config file (or I missed it last time) called:
<appSettings>
   <add key="owin:AutomaticAppStartup" value="true" />
    ...
</appSettings>

I changed the value from false to true and now it works. After 3 days of code tweaking and trial and error by looking at other forum posts, I'm glad it was this simple. Hope this helps others.
What bugs me, however is that there is no such setting in the web.config in the old application (go figure) - it worked without it.


text:
Q: Mapping through multiple arrays of objects and comparing ids So I have a bit of a dilemma. I am creating a forum and I am calling 3 different API's. Suppose I have multiple JSONs:
let forumPost= [{
"userId": 1,
"postId": 1,
"postTitle": "I am the post title",
"postBody": "I am the post body"
}]

let forumUser= [{
"userId": 1,
"name": "Someone Someone",
"username": "Som",
}]

let forumComment = [{
"postId": 7,
"userId" : 10,
"body": "I don't like your post",
}]

I would now like to create something like this:
Post title
  Post body
By user
-------------
CommentUser: CommentBody
CommentUser: CommentBody

In order to do this I am currently sort of doing nest mapping 3 times 3 different arrays of objects and comparing id's so:
forumPost.map(...
 forumUser.map(...
   forumComment.filter(...
       (post.userId === user.userId){
        <div>...</div>
        }

I was wondering if there is a more efficient way of mapping and comparing multiple nested objects in vanilla ReactJS?


text:
Q: How to get selected columns in slickgrid I am using mleibman/SlickGrid and have checkbox (isChecked) column,
var columns = [
            { id: "tagID", name: "#", field: "tagID", behavior: "select", cssClass: "cell-selection", width: 40, cannotTriggerInsert: true, resizable: false, selectable: false, excludeFromColumnPicker: true },
            { id: "isChecked", name: "isChecked", field: "isChecked", width: 80, minWidth: 20, maxWidth: 80, cssClass: "slick-cell-check", formatter: Slick.Formatters.Checkbox, editor: Slick.Editors.Checkbox, sortable: true },
            { id: "tagName", name: "tagName", field: "tagName", width: 90, minWidth: 120, cssClass: "cell-title", sortable: true },
            { id: "description", name: "description", field: "description", width: 120, minWidth: 120, cssClass: "cell-title", sortable: true }
        ];

How to get all selected/checked rows.
My Approach:
function GetCheckedRows() {
    var checkedRows = [];
    for (var i = 0; i < grid.getDataLength(); i++) {
       if (grid.getDataItem(i).isChecked)
            checkedRows.push(grid.getDataItem(i));
    }
    console.log(checkedRows);
 }

Calling GetCheckedRows never returns first checked row, second checked row comes and deselecting doesn't removes from  checkedRows.

A: For a start use 6pac SlickGrid, the MLeibman repo is dead now.
Are you missing a closing ')' in the line
if (grid.getDataItem(i).isChecked

or is this just a typo in what you've posted?


text:
Q: modify stylesheet of a particular page inside wp-admin inside this path, are the listing of my wordpress pages.
/wp-admin/edit.php?post_type=page&orderby=title&order=asc

i want to remove the default <table> design of the page and create my own style.
how do i go and modify that particular page.
Does this function add_action() still applicable? only to a particular page?
or should i modify the edit.php directly?

A: Do not modify the edit.php file directly as modifying WordPress core files are not recommended  and may generate new issues, will get overwritten when WordPress is updated.
Instead you can use properties and functions of WP_List_Table class to change it, along with adding css to backend for design changes.


text:
Q: Run different code clicking a button while remaining on same page? I have in a div id="1" following code:

  <object width="640" height="392" classid="clsid:**************">
    <param name="flashvars" value="cid=******&autoplay=true" />
    <param name="allowfullscreen" value="true" />
    <param name="allowscriptaccess" value="always" />
    <param name="src" value="http://www.ustream.tv/flash/viewer.swf" />
    <embed flashvars="cid=******&autoplay=true" width="640" height="392" allowfullscreen="true" allowscriptaccess="always" src="http://www.ustream.tv/flash/viewer.swf" type="application/x-shockwave-flash"></embed>
  </object>

I want remaining on same page click a button loading in same div a new different code :

A: Using pure javascript, add the following code to your buttons onclick event.
document.getElementById("1").innerHTML = "your code";


text:
Q: submitting forms in vuejs, should I use the form tag? I'm so confused how I should submit and handle edit forms in vuejs.
How I'm doing it now is I have a component called TreeForm.vue:
<template>

    <v-text-field v-model="cloned_tree.root" />
    <v-text-field v-model="cloned_tree.root" />
    <v-file-input type="number" v-model="cloned_tree.fruits" />
    <v-btn @click="$emit('save', {idx: tree_idx, tree: cloned_tree})">Save</v-btn>

</template>

And in the parent component I do:
<template>

    ...
    <TreeForm tree_idx="0" @save="submitTreeForm" />
    ...

</template>

And in my vuex I do:
import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';

const api = axios.create({
  baseURL: 'https://api.mydomain.com/api',
  timeout: 10000,
  withCredentials: true,
});
Vue.use(Vuex);
export default new Vuex.Store({
  strict: process.env.NODE_ENV !== 'production',
  state: {
    trees: [
      {
        root: 'hello',
        imageFile: require('some/picture'),
        fruits: 5,
      },
    ],
  },
  mutations: {
    updateTree(state, payload) {
      state.trees[payload.idx] = payload.tree;
    },
  },
  actions: {
    submitVideoForm({commit}, payload) {
      api
        .post('/trees/update/', payload)
        .then(response => {
          if (response.data.success == 1) {
            commit('updateTree', payload);
          } else {
            console.log(response.data.success);
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
  },
});

But I feel like This is not the correct way to do it specially because I'm not using <v-form> or <form> tags. I also haven't incorporated validation yet, I'm thinking of using vuelidate. So please give me the best practice for submitting and handling edit form while validation is done by vuelidate.

A: Basically, the form tag is not mandatory. Unless using some kind of CSS framework, the UI will look the same with or without the form tag. But, it still has some pros:
Ben Nadel put it best in his blog post:

... it seems that using a FORM tag does have some benefits, depending
  on your particular situation:

*

*You need it if you want to execute a traditional (ie. non-AJAX) form
  post.

*You need it you want to capture the "submit" event
  programmatically.

*You need it in order for mobile Safari to show the
  "Go" button on the keyboard.

*You need it if you want to
  programmatically "reset" a form (ie. call reset()).

*It makes generic
  form serialization easier (since it groups input fields).

*You need it if you want to post files without the modern file API.

*You need it if you have to segregate fields with the same name.

Vue.js gets you covered in almost all these situations. But if it doesn't - use form.


text:
Q: Доступ к элементам ListBox Добавлял элементы в ListBox так -
listBox1.Items.Add(стринг переменная);
listBox1.Items.Add(стринг переменная2);
listBox1.Items.Add(стринг переменная3);

Как мне теперь получить доступ к элементам которые я добавил?

A: Для доступа к элементам массива используется обычный способ с индексацией например
var value = listBox1.Items[index];

можно так же использовать foreach
foreach(var item in listBox1.Items)
{
   // item - делаем то что нам надо
}

или for
for (var i=0;i<listBox1.Items.Length;i++)
{
    // listBox1.Items[i] - делаем то что нам надо
}

или Linq
var items = listBox1.Items.Where(a=>a.Contains("подстрока"));


text:
Q: Multiple BindIp in MongoDB 3.4.1 on Debian Jessie I just upgraded from MongoDB 3.2 to 3.4.1.
/etc/mongod.conf had a multiple BindIP:
bindIp: [127.0.0.1,192.168.20.1]

This is not working anymore.
I get this error :
Scalar option 'net.bindIp' must be a single value

According to the documentation, It must be correct :
https://docs.mongodb.com/manual/reference/configuration-options/#net.bindIP
Any idea ?

A: Remove []. so solution is: bindIp: 127.0.0.1,192.168.20.1 and remember, no space characters anywhere in that string.


text:
Q: Are GridFS Java objects thread safe? I know that Java com.mongodb.Mongo objects are thread safe, but if I use the database returned from it to create a GridFS object, is that GridFS object also thread safe?
Thanks.

A: Yes, instances of GridFS are also thread safe.


text:
Q: Why open and closed boxes are measurable Let $B := \prod_{i=1}^n (a_i,b_i) := \{(x_1,\cdots,x_n) \in \mathbb R^n \mid \forall i: x_i \in (a_i,b_i) \}$. Can someone help me to show that $B$ is a measurable set, i.e. that if $A \subseteq \mathbb R^n$ then $m^*(A) \geq m^*(A \cap B) + m^*(A \cap B^c)$ where
$$
m^*(E) = \inf \left \{ \sum_{j=0}^\infty vol(B_j) : E \subseteq \bigcup_{i=0}^\infty B_i \text{ where } (B_i)_{i=0}^\infty \text{ at most countable } \right \}
$$ and the $B_i$ have to be open boxes. Further is $vol(B) := \prod_{i=1}^n (b_i-a_i)$ for each open box $B$.


text:
Q: The difference between using fstream constructor and open function I have a simple question about the constructor of fstream and the .open function.
Are there any differences between the following two expression?
1
fstream("file.txt",ios::app);

2
fstream fin;
fin.open("file.txt",ios::app);

For (1), I don't need to use .open function again right? Any functional differences between the two expression?
My second question is that if I left the openmode empty, what will be the default open mode?

A: No, there are no differences there.

A:
For (1), I don't need to use .open function again right?

That is correct.

Any functional differences between the two expression?

Not that I can think of.

My second question is that if I left the openmode empty, what will be the default open mode?

It is ios_base::in|ios_base::out. See http://en.cppreference.com/w/cpp/io/basic_fstream/open for further details.

A: There are no differences in terms of the state of the objects following your two snippets.
Why are there two versions?

*

*The ctor exists in order to create fstream objects that are immediately  associated with a stream.

*The open exists because these types of objects cannot be copied. Hence you cannot assign an fstream object to a different stream by writing:
fstream foo('bblskd');
// ...
foo = fstream('skdjf');

(Note that this interface was devised before move semantics).

You can find the default open mode here.

A: This is a really old question, but none of the answers are right in my opinion.
Both versions are the same. But the reason for having a separate open is for when you want to create your own class that inherits from basic_fstream. And you want to do something with the input to the constructor before and/or after.
class MoleStream : public std::basic_fstream<char> {
public:
    MoleStream () : std::basic_fstream<char> ("defaultmole") { }

    MoleStream ( const char *fn ) {
        std::string s = fn; s+=".mole";
        std::basic_fstream<char>::open (s);
        if ( !is_open() )
            std::basic_fstream<char>::open (fn);
    }
};

The second MoleStream constructor does stuff before and after the open. This might not be good practice in c++, but it can be useful.


text:
Q: How do I port php's openssl_sign to C#? I need to translate the following code to C# from php. What libraries / namespaces do I need to use?
function sign($method, $uuid, $data) {
    $merchant_private_key = openssl_get_privatekey(file_get_contents('merchant_private_key.pem'));
    $plaintext = $method . $uuid . serialize_data($data);
    **openssl_sign($plaintext, $signature, $merchant_private_key);**
    return base64_encode($signature);
}

The api can be found over at http://php.net/manual/en/function.openssl-sign.php. Where do I start? I have no idea what the open_ssl sign in php does behind the covers.
Anyone able to help out that knows both php and C# or could someone at least explain what openssl_sign does in the background so that I can port it.
EDIT: 2010-08-18 I can't find a way to use openssl, it keeps saying it can't load managedopenssl.dll. Think it is because of my machine being x64.

A: The difficulty here consist in reading and decoding the private key. You could use the following openssl helper class. Once you have referenced it you may try this:
public static string Sign(string method, string uuid, string data)
{
    string merchantPrivateKey = File.ReadAllText("merchant_private_key.pem");
    byte[] der = opensslkey.DecodePkcs8PrivateKey(merchantPrivateKey);
    using (RSACryptoServiceProvider rsa = opensslkey.DecodePrivateKeyInfo(der))
    using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
    {
        // This will contain the data to sign
        byte[] dataToSign = Encoding.Default.GetBytes(method + uuid + data);
        byte[] signature = rsa.SignData(dataToSign, md5);
        return Convert.ToBase64String(signature);
    }
}

In this example I have used MD5 but you could use anything that is appropriate to your scenario. I think openssl_sign uses SHA1 by default.

A: Thank you for the suggestions.
I have found a solution for my problems. There is a library called ChilKat that we will be using. The answer was found here. Unfortunately this does not work on my x64 machine. Fortunately our servers are all x86 still so we have some more time to look into a workaround.


text:
Q: Actuary P/1 Exam Question
I was taking a practice exam and I don't understand a step in one of the solutions to the problem. I understand every part except why $f(y^{0.5})=8(y^{0.5})^{-3}$
If someone could help explain that to me it would be very helpful.
Edit: Just to be clear I am only referring to the second solution provided that starts at "Alternatively"

A: There is a typo that may be the cause of the confusion. The density function $f(t)$ of $T$, for $t\gt 2$, is $\frac{8}{t^3}$. This is obtained by differentiating the cdf, which is $1-\frac{4}{t^2}$. After that, it is direct substitution of $y^{0.5}$ for $t$.


text:
Q: How to use a Swift class from Source folder in Swift2 playground This problem has occurred in Xcode 7.0.1. How do I use a public class from the Source folder in my Swift playground?
import Foundation
public class User {
    var name: String = ""
    var age: Int = 0
    init (name: String, age: Int) {
        self.name = name
        self.age = age
    }
}

In the main playground (below), I get error 'User' cannot be constructed because it has no accessible initializers.
import Cocoa
let user1 = User(name: "User", age: 99)

Evidence of my folder structure is in this screenshot:

A: The error tells you that the init is not accessible. Make it public, too.

A: Try this
public class User {
    var name: String?
    var age: Int?
    init (name: String, age: Int)
     {
        self.name = name
        self.age = age
    }
}


text:
Q: Is it possible for a new Recordset be created using a variable from an existing Recordset? I have a Db for individuals to test on courses they have taken.  This Db takes input from an introduction form, selects data from a query, and passes it to the test form.  This works great (with many thanks to @xpofer) in that it returns questions randomly, but the answers are always in the same order.  This is because the tables and queries the Recordset is based on contains the following columns:
TABLE
ID
CDC
Vol
Question No (Randomized in query)
Section
Question
Ans A
Ans B
Ans C
Ans D
Correct Answer
What I am trying to do is not only present the questions randomly, but have the answers presented randomly also.  To do so, I have separated this into two separate tables.
tblRnd_Ques
ID (PK)
CDC
Vol
Question No
Section
Question
tblRnd_Ans
ID
Q_ID (FK)
Answer
Correct (Y/N)
Here are the queries I am trying to use.
qryRnd_Ques
ID
CDC
Vol
Question No.
Section
Question
Rnd_ID (Randomized ID, ascending)
qryRnd_Ans
Rnd_ID (Randomized ID, Ascending)
Q_ID
Answer
Correct (Y/N)
Now for the problem.  Is it possible to create a Recordset using a variable from a previous Recordset?  Here is the code I currently have:
Private Sub GetAnswers()

Dim rsAns As Recordset
Dim strAns As String
Dim strSQL As String
Dim intQues As Long
Dim isCorr As Boolean

intQues = !ID

        strSQL = "Select [ID], [Answer], [Correct] FROM [qryRnd_Ans] WHERE [Q_ID] = " & intQues

        Set rsAns = CurrentDb.OpenRecordset(strSQL, dbOpenDynaset)

        strAns = !Answer
        isCorr = !Correct

        MsgBox "Answer:  " & strAns _
        & Chr(13) & Chr(10) & "Correct:  " & isCorr

        rsAns.Close

End Sub

I have tried creating this second Recordset (rsAns) directly in the LoadNextQuestion sub where I now call GetAnswers.  I kept getting

Run-time error 3464: Data type mismatch in criteria expression

with this code:
    strSQL = "Select [ID], [Answer], [Correct] FROM [qryRnd_Ans] WHERE [Q_ID] = '" & intQues & "'"

    Set rsAns = CurrentDb.OpenRecordset(strSQL, dbOpenDynaset)

I figured I may need to place this code in a subroutine, hence the call to GetAnswers.  With this code, I get a Compile error:  Invalid or unqualified reference at the strAns = !Answer line.  I have searched many sites, including Microsoft, CNet, bytes.com, as well as Stackoverflow, and it appears as if the syntax is correct, so I am at a loss as to the problem.  Any assistance is appreciated.
UPDATE
After much sole- AND Internet searching, I found a solution.  I changed the variable values from strAns = !Answer to strAns = rsAns![Answer], and it all fell into place.  Many thanks to DanielG and the other sites I searched.

A: Since it is an int, have you tried taking your single quotes out:
strSQL = "Select [ID], [Answer], [Correct] FROM [qryRnd_Ans] WHERE [Q_ID] = " & intQues

To get all of the answers in the recordset, you can now iterate the recordset:
If Not (rsANS.EOF And rsANS.BOF) Then
    Do Until rsANS.EOF = True
          ' Get the next answer and do something with it
          ' Me!MyTextBox = rsANS!MyNextAnswer
    rsANS.MoveNext
    Loop
End If


text:
Q: Optional Date Parameters I'm using Pentaho Report Designer 3.9.4 and a db2 database.  I have 4 variables that I need to pass in to my Pentaho report through a stored procedure call, 3 of which are driven by the user.
CALL SCHEMA.STORED_PROCEDURE ('DATA', ${START_DATE}, ${END_DATE}, ${PARM_YEAR})

The rows of data are provided by the first variable 'DATA' which will be hard coded.  I have a drop down box parameter PARM_YEAR that allows the user to choose and drill down to a specific year.  I also have date picker parameters START_DATE and END_DATE that receives the start and end date values from the user retrieving the desired results from that specified date range.  The PARM_YEAR and date range parameters (START/END_DATE) need to be optional.  If the user selects a year with the drop down parameter PARM_YEAR then the report will produce the results and vice versa for the date picker parameters.  In order to retrieve the results for the date range selected the PARM_YEAR parameter must equal zero.
CALL SCHEMA.STORED_PROCEDURE ('DATA', ${START_DATE}, ${END_DATE}, 0)

Any help would be appreciated.

A: I found an answer.  Make the PARAM_YEAR parameter optional (not mandatory). Then add a new hidden parameter to the report and give it a post-processing formula of "=IFNA([PARAM_YEAR]; 0)" to provide a value when your year is not set. Or list the zero option as one of the selections in your PARAM_YEAR if it is a drop-down parameter.


text:
Q: what is the best way to visualize a table on graph in r I have the following table(data frame):
             week24  week25 week26
 under 0.5m    1824   1878   1955
 0.5 to 1m     170    205    211
 1to3          117    109    124
 3to6           19     19     25
 6to10           9      8      8
 10to15          4      3      5
 15to30          9     13      9
 above 30m      19     32     28

i am looking for the best way to visualize it on a graph then i can i have row names under 0.5m:above 30m  in X axis .
i have already tried barplot() but the results are not that good

how can i make it more informative?

A: It's not clear to me what exactly are you trying to obtain. Maybe just by adding the legend your graph will be way more descriptive. I've a simple data frame to show what I mean:
df <- data.frame(Z=c(1,2,3),Y=c(2,3,1))
row.names(df) <- c("Cat1","Cat2","Cat3")

barplot(as.matrix(df),
        legend.text = row.names(df),
        args.legend = list(x = "right"),
        col = c("blue","green","red"))

If you want check better colours, check this website: http://www.stat.columbia.edu/~tzheng/files/Rcolor.pdf


text:
Q: CNN having high overfitting despite having dropout layers? For some background, my dataset is roughly 75000+ images, 200x200 greyscale, with 26 classes (the letters of the alphabet). My model is:
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(200, 200, 1)))
model.add(MaxPooling2D((2, 2)))
model.add(Dropout(0.2))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Dropout(0.2))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Dropout(0.2))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(26, activation='softmax'))

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=[tf.keras.metrics.CategoricalAccuracy()])

model.fit(X_train, y_train, epochs=1, batch_size=64, verbose=1, validation_data=(X_test, y_test))

The output of the model.fit is:
Train on 54600 samples, validate on 23400 samples
Epoch 1/1
54600/54600 [==============================] - 54s 984us/step - loss: nan - categorical_accuracy: 0.9964 - val_loss: nan - val_categorical_accuracy: 0.9996

99.9+ valadiation accuracy. When I run a test, it gets all the predictions incorrect. So, I assume it is overfitting. Why is this happening, despite adding the dropout layers? What other options do I have to fix this? Thank you!

A: The only way you would get all the predictions on a held-out test set incorrect while simultaneously getting almost 100% on validation accuracy is if you have a data leak. i.e. Your training data must contain the same images as your validation data (or they are VERY similar to the point of being identical).
Or the data in your test set is very different than your training and validation datasets.
To fix this ensure that across all your datasets no single image exists in more than one of the datasets. Also ensure that the images are generally similar. i.e. if training using cell phone photos, do not then test with images taken using a DSLR or images that have watermarks pulled from Google.
It is also odd that your loss is nan. It may be due to using categorical accuracy. To fix this just put the metric to be 'accuracy'. This will dynamically determine the best accuracy to use. One of [binary, categorical or sparse_categorical].
Hope this helps.

A: It's totally not overfiting, look at your loss it's equal to nan. That means your gradients have exploded during the training. To see what's really happening i recommend you look at the loss after every mini-batch and see at what point the loss becomes nan.


text:
Q: The Invincible error with Windows Store PC Configuration
Asus X53U (Windows 10 and Windows 8.1 dual boot),
problem is seen on- Windows 8.1,
frequency of problem- Everytime the Store is opened
Long Story, short
Life was running smooth, until one fine morning I found out that I was unable to download any apps from the windows store. I tried all sorts of remedies I could find online (running sfc, dism /restorehealth, dism /componentcleanup, ran the Windows update troubleshooter, wsreset in cmd) but that didn't help. For an insight jump to the screenshots section of this question.
The Details
'Invincible' would be a word too shallow to describe the problem. After I've tried the aforementioned remedies, and needless to say, every one of them failed, I even did a 'Clean Install' of windows, but still that didn't help. Every time I go to download an app from the windows store, I get a new error. The app search runs fine. The screenshots of the apps also load fine, but despite being on a 4G connection, Store reports me that my Internet connection is 'Too Slow'. Sometimes I get error 0xc03f300d, while sometimes 0x8000405 (refer screenshots for more). And when I go to the 'Your Account' section of the Store, I'm greeted with the problem 'Connection Time Out' everytime. At last I decided to sideload Windows Store apps, so to get a developer License, I opened powershell and opened the Dev-Licensing prompt. The prompt asked me to sign in with my Microsoft account, but after I successfully do so I again get the error 0xc03f300d.
After this I suspect that there may be some problem with the Accounts & sync. My local account is connected to my Microsoft account. A day before all this happened I noticed that windows asked me (about 2-3 times) to sign in with my password as there was some problem. If this is the case please suggest a possible remedy. (That being said, OneDrive loads fine, and other account Sync functionalities work fine, The only problem is with the Store)
I think if things go on this way, my family may feel the need to contact a Lunatic asylum. If possible please help me. All I want is a 'Stable' life and I guess Windows is planning not to give me one.
Screenshots

Network Error msg in Store (Notice that I'm already connected to my Home-Network)

Now this is strange. Two different errors are shown at a time while downloading the same app.

Edit
Downloaded all recent updates and updated my PC with the most recent updates, still problem persists.

A: As things stand, the store now works again for me...
Nothing changed on my behalf, so I guess Microsoft fixed something on their side (sync servers?)
Just try again now


text:
Q: Where is the Android emulator in Visual Studio 2015? I have just double checked, run install to modify VS, and it showed the emulator as installed. To feel sure, I uninstalled it, and re-installed it, and the installer gave no indication of any problems. If I run the installer now, all the Android boxes, SDK etc. and emulator, are checked, that is, they are supposed to be installed.
Yet there is no Android emulator in the drop-down for browsers in the toolbar in VS. What is up with this?

A: http://blogs.msdn.com/b/visualstudioalm/archive/2015/07/20/you-can-now-acquire-the-visual-studio-emulator-for-android-on-its-own.aspx
Try looking at the link, i provided. i believe it will be of some help to you.

A: The emulator won't be available in Visual Studio if you don't meet the system requirements listed here https://msdn.microsoft.com/en-us/library/mt228280.aspx


text:
Q: DNS Redirection - no such thing, or is there? Some domain registry like europeregistry.com allows users to buy and register a domain and set up a "redirection" to an existing website.
Is this redirection a function of DNS or has the registry setup a behind-the-scenes webserver that does a HTTP redirection to the specified website?

A: How about this for a complete answer:
DNS has the concept of a CNAME record, where an entry can point to a different entry, as per adaptr's answer.  So, a DNS lookup of "redirect.example.com" will return a CNAME that says "example.hostingservice.com", which will subsequently be looked up to some A record with an IP address (with perhaps more levels, if the target of a CNAME is also a CNAME, etc.)  This is a standard part of DNS.
Some DNS providers, but not all, will let you create a non-standard "HTTP redirect" record.  For example: http://help.dnsmadeeasy.com/record-entry/http-redirection/
This non-standard record appears to be what the OP refers to, and is geared towards hosted web sites, where it may not be possible to set up custom domains to your liking.  What happens is that the "HTTP Redirection" record let's you map the website http://redirect.example.com to something like http://example.hostingservice.com.  The DNS for "redirect.example.com" actually resolves to a server run by that DNS provider.  That server runs a specialized web server, that will issue an HTTP redirect so that the browser goes from http://redirect.example.com to http://example.hostingservice.com.
A couple things get mixed up in this: there's a DNS query that resolves to a machine controlled by the DNS provider.  There is an HTTP response from that machine's web server which sends people off to a different web server.  This is not purely DNS, and, in fact, only works for web services because of the HTTP redirect.  You can't use this for, say, mail.  This is entirely for people who don't want to (or can't) set up their own web server to issue the HTTP redirect themselves.  My example would be, say, an expensive SSL certificate for a custom domain on Heroku.  Instead of paying for that, the DNS provider can give us a "HTTP redirect" record for an easy-to-remember hostname.  Hitting that easy-to-remember hostname in a web browser will send us to the hard-to-remember Heroku server running SSL.

A: It's a behind-the-scenes thing that they do. They will register the domain, point it to their own webservers, and have very simple script that checks the incoming domain, looks it up in its database to see which site it should redirect to, and gives you a 301/302 redirect.
So it's actually three different things all working together.

A: When talking about pure DNS, they are referring to a CNAME record; a CNAME points to another label, which has to be resolved anew (hence "redirection") by the client.
Example:
yoursite.example.com. IN CNAME www.example.org.
www.example.org. IN A 10.10.10.10
There are both pros and cons to using CNAMEs; primarily, it forces a second lookup.


text:
Q: override Master Page CSS div width in Child Page I've set a specific width to the body div in my Master Page and I want to change that in a Child Page that belongs to the Master Page. Is this possible? I've been searching and I think what I need is javascript.
I haven't used javascript before though, but here's what I've tried:
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">

    <script type="text/javascript">
      {
            document.getElementById("pagediv").style.width = "200px";
        }
    </script>

</asp:Content>

A: You don't have to use JavaScript. You can also use CSS and have this in your content placeholder.
<style>
    #pagediv { width: 200px !important; }
</style>

A: Create a property in your masterpage called BodyWidth
Then in your output use that for the div width
<div style="width:<%= BodyWidth %>">

Then in any child page you can override this width using something like the following in Page_Load.
((MyMaster)Page.MasterPage).BodyWidth = "300px";

Avoids using javascript then for overriding the value.
Alternatively you could use the same code but to set a style class, which would be a better way - but this depends how different your widths are on each page.


text:
Q: Python Stop Generator Gracefully I have a generator in python that returns rows from a postgres table. After those rows are processed I want to delete those rows, but not until they are successfully processed by the process being yielded to.
def scan():
  rows = # ... get rows from pg

  yield rows

  delete(rows)

In my process that uses the generator, I want to stop the scan prematurely if a condition is met (i.e. a process has run too long)
timeout = 60
start = time.time()

for rows in scan():
  do_something_with_rows(rows)

  if time.time() - start > timeout:
    # Break out of generator gracefully

If I return or break here, the generator will never delete the rows. If I throw a StopIteration here, it just behaves as an exception being thrown.
Is it possible to break out of a generator gracefully, so that the generator will complete it's final post-yield process?
Edit:
Figured it out. You can catch a GeneratorException.
See: https://www.peterbe.com/plog/generatorexit

A: You can catch a GeneratorExit exception from a break in the yielded-to process and perform any post-yield actions.
Details:
https://www.peterbe.com/plog/generatorexit


text:
Q: How to map HTML markup with plain text equivalent I have some HTML markup that I am displaying with TinyMCE. As an example, the following markup:

This is a market.

renders as "This is a market."
I need to highlight certain specific words whose position etc. is given to me based on the plain text version of the markup. Since the highlighting has to be done in HTML (TinyMCE), I need to find a way to map the plain text back to the HTML markup.
In the above sample, the first "T" in the sentence would be at position 3 in HTML markup and at position 0 in plain text.
My question(s):
1. How do I go about doing this?
I already tried a brute-force approach, i.e., running through the HTML text and wherever the tag ends, start mapping the html markup position to the plain text. The presence of newlines etc. does seem to trip it up.
Any help is welcome.


text:
Q: Call a js with GET parameters I need someone to enlighten me.
I've seen this:
<script src="http://host.com/file.js?no_forms=1"></script>

What does that means? A GET parameter passed to a javascript file?
Into which conditions this can be done?
What kind of approach is this?
Any help would be appreciated.

A: ?no_forms=1 is just a query string parameters. i will just tell the common usage of such things.

*

*Used for to avoid caching (get new updated version of JS)

*Some sort of redirection

*Even some application usage ideas.

A: Sometimes the parameter is used simply to prevent client side caching.
It could also be that requesting file.js is actually rewritten as a dynamic call (say script.php?file=file.js&no_forms=1) that is fetching the correct file and using the extra parameter somehow.

A: You can use this
<script src="http://host.com/file.js" no_forms="1"></script>

And
function $_GET(q,s) {
    s = s || window.location.search;
    var re = new RegExp('&'+q+'=([^&]*)','i');
    return (s=s.replace(/^\?/,'&').match(re)) ? s=s[1] : s='';
}

And get result
var noForms = $_GET('no_forms');