text:
Q: Count users and groups totals in one query I am super new to access and having difficulty with a query. My table (tblpacks) is the following:
 id user_id group_id quota_id
 1    1        1       1
 2    1        2       1
 3    2        1       1
 4    3        1       1

Ideally, what I now is to get hte number of unique users and groups for quota_id=1
The result will be:
       total_users = 3
       total_groups = 2

A: If you only wanted to count one field, there would by a simple solution, but since you want to count 2 separate fields, you in fact need at least 2 separate queries.
My answer is to use a UNION query as the source for counting. This UNION query returns the distinct user_id values (with Null as group_id) and the distinct group_id values (with Null as user_id). I omitted the DISTINCT keyword, because UNION (without ALL) does a DISTINCT query automatically. As the datatypes where not recognized correctly when using a constant Null field in the first SELECT statement of the UNION query, I added a third SELECT statement as the first one, which selects both fields from the table but returns no records:
SELECT Count(user_id) AS total_users, Count(group_id) AS total_groups
FROM (
  SELECT user_id, group_id FROM tblpacks WHERE Yes=No
  UNION
  SELECT user_id, Null FROM tblpacks WHERE quota_id=1
  UNION
  SELECT Null, group_id FROM tblpacks WHERE quota_id=1
) AS qsub;


text:
Q: Regex - Match string between quotes (") but do not match (\") before the string I need to match a string that is in quotations, but make sure the first quotation is not escaped.
For example: First \"string\" is "Hello \"World\"!"

Should match only Hello \"World\"!
I am trying to modify (")(?:(?=(\\?))\2.)*?"
I tried adding [^\\"] to ("), and that kinda works, but it matches either only (") or every other letter that isn't (\") and I can't figure out a way to modify ([\\"]") to only match (") if it is not (\")
This is what I have so far ([^\\"]")(?:(?=(\\?))\2.)*?"
I've been trying to figure it out using these two pages, but still cannot get it.

Can Regex be used for this particular string manipulation?

RegEx: Grabbing values between quotation marks

Thanks

A: You can use negative look behind like this:
(?<!\\)"(.*?)(?<!\\)"

Check see it in action here on regex101
The first match group contains:
Hello \"World\"!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Magento - Paypal Express 404 Error I have added paypal pro (uk) express to my Magento shopping cart.  The paypal button now appears below the checkout button in the shopping cart.
The problem is when I click the paypal button I get a 404 error.
Any ideas?

A: I reckon you added a payment method for the checkout process or a custom paypal checkout.
Activate the debug mode and the error logging in system->configuration->developer. Having a more verbose error message will point you to a more clear error.
404 is page not found error, so wherever the paypal module is pointing the page is missiong. This could happen as a result of malconfiguration or API change or other issues.

A: Fixed it by following post 5 here:
http://www.magentocommerce.com/bug-tracking/issue?issue=8528
I needed to delete the paypal files in the default folder.


text:
Q: ArchLinux + nginx + Passenger Rails app always pointing to localhost This is my first time using Arch based Linux environment (Manjaro Linux), and also Nginx.
I installed Nginx, opened http://localhost and it showed the standard Welcome to Nginx page.
Then I created 2 folders:

*

*/etc/nginx/sites-available

*etc/nginx/sites-enabled

In sites-available, I created a conf file named iima, with following data:
server {
  listen 80;
  server_name iima.merged.localhost;
  passenger_enabled on;
  location / {
    root /home/path/redacted/public;
  }
}

and then created a symbolic link:
sudo ln -s /etc/nginx/sites-available/iima /etc/nginx/sites-enabled/iima

Then in the /opt/nginx/conf/nginx.conf, I added:
include       /etc/nginx/sites-enabled/*;

In the /etc/hosts, I added the following line at the end of the file:
127.0.0.1       iima.merged.localhost   iima.merged.localhost

# I also tried below line while removing above line
127.0.0.1       iima.merged.localhost

Restarted the nginx server using sudo systemctl restart nginx (also tried with reload), but typing iima.merged.localhost always points to localhost page.
Am I missing anything? There are no error(s).log created in /var/log/nginx.
EDIT:
Content of /opt/nginx/conf/nginx.conf
#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
    passenger_root /home/harsh/.rbenv/versions/1.8.7-p375/lib/ruby/gems/1.8/gems/passenger-4.0.45;
    passenger_ruby /home/harsh/.rbenv/versions/1.8.7-p375/bin/ruby;

    include       mime.types;
    include       /etc/nginx/sites-enabled/*;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;
        # server_name_in_redirect off;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }

    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}


text:
Q: Creating node object from var-args arguments I have the following Node class
class Node<T> {
    var data: T
    var next: Node<T>?

    init(_ items: Any...) {
       // self.data = items[0] as! T
    }
}

and my goal is to initialize the node with the constructor above like this :
var sampleNode =  Node<Any>(Node<Int>(2, 15), 4, Node<Any>(5, Node<Int>(7, 9)))
How can I achieve this with varargs?

A: The key problem here is "how do I combine the items in items into a big list?". We can simplify the problem into a smaller one: "How do I combine 2 Anys, which can be either T or Node<T>, into a single list, represented by a Node<T>?". (This is what combine2Anys does below) You can easily see that there are 4 cases to this problem:

*

*the first item is a Node<T>, the second item is a T,

*both items are Node<T>

*the first time is T, the second item is a Node<T>

*both items are T
You just need to handle each case in turn. And then, use this method on the first two items of items, then on the result of that and the third item, then on the result of that and the fourth item, and so on.
class Node<T> {
    var data: T
    var next: Node<T>?

    init(_ items: Any...) {
        func combine2Anys(_ x: Any, _ y: Any) -> Node<T> {
            switch (x, y) {
            case (let node as Node<T>, let t as T):
                node.end.next = Node(data: t, next: nil)
                return node
            case (let node1 as Node<T>, let node2 as Node<T>):
                node1.end.next = node2
                return node1
            case (let t as T, let node as Node<T>):
                return Node(data: t, next: node)
            case (let t1 as T, let t2 as T):
                return Node(data: t1, next: Node(data: t2, next: nil))
            default:
                // something other than Node<T> and T are in the passed in array
                fatalError()
            }
        }

        if items.count == 0 {
            fatalError() // it's undefined what we should do when items is empty
        } else if items.count == 1 {
            data = items.first as! T
            next = nil
        } else {
            var combined = combine2Anys(items[0], items[1])
            for i in 2..<items.count {
                combined = combine2Anys(combined, items[i])
            }
            data = combined.data
            next = combined.next
        }
    }

    // find the last node of the list
    var end: Node<T> {
        var node = self
        while node.next != nil {
            node = node.next!
        }
        return node
    }

    init(data: T, next: Node<T>?) {
        self.data = data
        self.next = next
    }
}

Usage:
let list = Node<Int>(1, Node<Int>(2, 15), 4, Node<Int>(5, Node<Int>(7, 9)))

Note all you should be using the same generic type all the time.
But really though, this is really ugly, mainly because of the casts and stuff. You lose all compile-time type safety. I assume this is one of those "weird requirements of homework". If I were to do this in the real world, I would change the usage to:
let list = Node(Node(1), Node(Node(2), Node(15)), Node(4), Node(Node(5), Node(Node(7), Node(9))))

And I would have these two initialises instead:
init(_ items: Node<T>...) {
    if items.count == 1 {
        data = items.first as! T
        next = nil
    } else {
        items[0].end.next = items[1]
        for i in 2..<items.count {
            items[i - 1].end.next = items[i]
        }
        data = items[0].data
        next = items[0].next
    }
}

init(_ item: T, next: Node<T>? = nil) {
    self.data = item
    self.next = next
}


text:
Q: Can I use IsNull or na in if() to check missing value? This one is not duplicate I have new question. I tried to write this
package org.apache.spark.h2o.utils

import water.fvec.{NewChunk, Frame, Chunk}
import water._

class Miss extends MRTask {
  override def map(c: Chunk, nc: NewChunk): Unit = {
    for (row <- 0 until c.len()) {
      if(c.atd(row) == 0){
       nc.addNum(0)
      }
      else
       nc.addNum(1)
    }
  }
}

Can I use na or IsNull in if (...) to check whether or not that row is null?
Code result
          A    B    C    D            E    NaN
    min                                     0
   mean                                     0
 stddev                                     0
    max                                     1
missing                                     0
      0  5.1  3.5  1.4  0.2  Iris-setosa    1
      1  4.9    3  1.4  0.2  Iris-setosa    1
      2  4.7  3.2  1.3  0.2  Iris-setosa    1
      3  4.6  3.1  1.5  0.2  Iris-setosa    1
      4    5  3.6  1.4  0.2  Iris-setosa    1
      5  5.4  3.9  1.7  0.4  Iris-setosa    1
      6  4.6  3.4  1.4  0.3  Iris-setosa    1
      7    5  3.4  1.5  0.2  Iris-setosa    1
      8  4.4  2.9  1.4  0.2  Iris-setosa    1
      9  4.9  3.1  1.5  0.1  Iris-setos...

A: Something like that:
c.atd(row) match {
  case nan: Double if nan.isNaN => nc.addNum(0)
  case 0 => nc.addNum(0)
  case _ => nc.addNum(1)
}


text:
Q: Is there a way to back to the lastest branch? I always switch each between two branches, as develop and mywork, is there a better way to switch more quick except checkout develop and checkout mywork? As cd - in shell.

A: Yeah, it works just like cd does in bash: git checkout -


text:
Q: Activating mouse event in visual object in WPF I am creating my own control from derived from drawingvisual class and drawn a rectangle. I want to enable mouse events for this object. how can I achieve this?
I thing implementing IInputElement interface might be the solution. Could you guys suggest me how to implement this interface.
Thanks in advance

A: The DrawingVisual class doesn't offer any mouse events, and according to MSDN the IInputElement interface is "not intended to be implemented in application or framework-building scenarios."
Maybe you would be better deriving from UserControl and using DrawingVisual to provide visual content for it?


text:
Q: Adjectival clauses with time subordinating conjunctions (before) I know that we can use "before" (which is a time subordinating conjunction) for an adjectival clause.
For example:

All the years before Jesus' birth receive the label B.C.

I would like somebody to confirm that when using an adjectival clause with "before",  we cannot describe things other than time.
This would not make sense, for example:

The countries before Jesus' birth did not have Christianity.


text:
Q: Qual a melhor maneira de desfazer um merge com elementos em staged e modfy com conflitos? Fiz um merge desnecessário com uma branch, agora tenho vários elementos em staged e não mesclados pelo fato de exitirem conflitos. Qual a melhor maneira de reverter este merge e deixar a branch no ultimo commit antes desta ação indesejada?

A: Assumindo que o merge não gerou nenhum commit (já que há conflitos). Na raiz do seu repositório, digite
git reset .

Isso irá remover todas as mudanças que estão staged, colocando-as de volta na lista de modified.
Em seguida, reverta todas as modificações:
git reset HEAD --hard

Isso irá reverter todas as modificações nos arquivos modificados. Note que se você tinha alguma outra modificação, ela também será perdida.
Se o merge adicionou arquivos novos no repositório, então você pode "limpá-los" através do git clean. Novamente da raiz do repositório:
git clean -xdf

Como sempre, cuidado quando usar o git clean já que ele pode apagar arquivos que você gostaria de ter. Você pode usar a opção n em fez de f para listar os arquivos que serão apagados.

A: Um merge pode ser cancelado com
git merge --abort

De acordo com o Pro GIT Book https://git-scm.com/book/pt-pt/v2/Ferramentas-do-Git-Advanced-Merging


text:
Q: Error : Login Profile for User XXXXXX cannot be modified while login profile is being created. (EntityTemporarilyUnmodifiable) I have created an IAM User with login profile (Password) using Python SDK (Boto3). The user creation was success.
When trying to delete the Login Profile of the IAM User, I'm getting the below error :

An error occurred (EntityTemporarilyUnmodifiable) when calling the
DeleteLoginProfile operation: Login Profile for User XXXXXX cannot be
modified while login profile is being created.

After i wait for few minutes and then run the code again, the code works.
This issue started from few days ago and now it has became a frequent error.
Any problems with IAM ?


text:
Q: Google Client Authorize doesn't work on Mobile IOS IPhone(41.0.2272.58) We use gapi.js for Google authorising.
It works correct on majority of desktop browsers and on mobile Safari.
But it doesn't on  Mobile Chrome IOS(41.0.2272.58).
In the begging we load gapi.js script
require(['https://apis.google.com/js/client.js?onload=gapiIsLoaded'];

Then we try authorize using:
gapi.auth.authorize(params, handler);

Params are
var params = {
                client_id: MY_CLIENT_ID,
                scope: MY_SCOPES,
                immediate: false // to open popup
            };

Browsers shows popup and I can autorize and continue work.
IOS Safari works correct too.
But Chrome IOS never calls handler callback.

A: This issue extends to Chrome for Android 5.0. In my case, downgrading to 39.0.2171.59 resolves the problem. Hopefully this information puts you closer to finding the root cause.

A: Issue was resolve by adding redirect ur instead of window open https://github.com/google/google-api-javascript-client/issues/189


text:
Q: Solution for javascript window.close()? I have been searching online to peform window.close() using the javascript. I have a MVC application,when i click on logoff button the page should close.
I know that the window.close is not working now a days as there is some security reasons. Getting the message "Scripts may close only the windows that were opened by it".
Tried almost all the options to close the window but nothing works till now.
 method1
method2
method2

Any help is appreciated.
Thanks
Dev

A: I had this same scenario and researched a lot. I had to end up with using IE(Internet Explorer) or Edge browser. There are no other solutions for existing browsers
Only if you page is loaded from another page or web application or a homePage(which is also a web page), this is possible


text:
Q: If I define a class-method in Ruby Object class, how do I get the name of a child class calling this method? Example
def Object.const_missing(name)
  puts self.class
end
class A; end
A::B # => Class

How can I get A in Object#const_missing?

A: def Object.const_missing(name)
  puts self
end


text:
Q: xslt grouping by every attribute I have multiple types of xml messages I need to "compact" by grouping multiple nodes under the same parent (same parent meaning they share the same node name and every attribute declared is also equal). For example:
<TopLevel CodeTL="Something">
    <Ratings>
          <Rating CodeA="ABC" Start="1-1-2012" End="1-2-2012">
              <RatingByNumber Code="X" Rating="10" Number="1">
              <RatingByNumber Code="X" Rating="19" Number="2">
          </Rating>
    </Ratings>
</TopLevel>
    <TopLevel CodeTL="Something">
    <Ratings>
          <Rating CodeA="ABC" Start="1-2-2012" End="1-3-2012">
              <RatingByNumber Code="X" Rating="10" Number="1">
              <RatingByNumber Code="X" Rating="19" Number="2">
          </Rating>
    </Ratings>
</TopLevel>
<TopLevel CodeTL="Something">
    <Ratings>
          <Rating CodeA="XYZ" Start="1-2-2012" End="1-3-2012">
              <RatingByNumber Code="X" Rating="10" Number="1">
              <RatingByNumber Code="X" Rating="19" Number="2">
          </Rating>
    </Ratings>
</TopLevel>
<TopLevel CodeTL="Something">
    <Ratings>
          <Rating CodeA="XYZ" Start="1-2-2012" End="1-3-2012">
              <RatingByNumber Code="X" Rating="30" Number="3">
              <RatingByNumber Code="X" Rating="39" Number="4">
          </Rating>
    </Ratings>
</TopLevel>

Notice how they all share the same CodeTL attribute and the last 2 share the same CodeA,Start and End attributes so what I need is to produce the following output using a xslt
<TopLevel CodeTL="Something">
    <Ratings>
          <Rating CodeA="ABC" Start="1-1-2012" End="1-2-2012">
              <RatingByNumber Code="X" Rating="10" Number="1">
              <RatingByNumber Code="X" Rating="19" Number="2">
          </Rating>
          <Rating CodeA="ABC" Start="1-2-2012" End="1-3-2012">
              <RatingByNumber Code="X" Rating="10" Number="1">
              <RatingByNumber Code="X" Rating="19" Number="2">
          </Rating>
          <Rating CodeA="XYZ" Start="1-2-2012" End="1-3-2012">
              <RatingByNumber Code="X" Rating="10" Number="1">
              <RatingByNumber Code="X" Rating="19" Number="2">
              <RatingByNumber Code="X" Rating="30" Number="3">
              <RatingByNumber Code="X" Rating="39" Number="4">
          </Rating>
    </Ratings>
</TopLevel>

which is much cleaner and, depending on the application consuming it, it might save processing time and saves space.
The problem I'm having is that I have different types of xml messages with different node names and attributes (and number of attributes) but they all share the same structure I'm showing here.
It would be great a generic way to handle all of them but I would be grateful for a XSLT to transform the example I provided so I can create custom code for every xml message I need to send out.

A: This XSLT 1.0 stylesheet produces the desired result:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:key name="byCodeTL" match="TopLevel" use="@CodeTL"/>
    <xsl:key name="byAttrs" match="Rating"
             use="concat(../../@CodeTL, '|', @CodeA, '|', @Start, '|', @End)"/>
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="TopLevel[generate-id()=
                                  generate-id(key('byCodeTL', @CodeTL)[1])]">
        <xsl:copy>
            <xsl:apply-templates select="@*"/>
            <Ratings>
                <xsl:apply-templates
                        select="key('byCodeTL', @CodeTL)/Ratings/*"/>
            </Ratings>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="Rating[generate-id()=
                                generate-id(key('byAttrs',
            concat(../../@CodeTL, '|', @CodeA, '|', @Start, '|', @End))[1])]">
        <xsl:copy>
            <xsl:apply-templates select="@*|key('byAttrs',
                concat(../../@CodeTL, '|', @CodeA, '|', @Start, '|', @End))/*"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="TopLevel"/>
    <xsl:template match="Rating"/>
</xsl:stylesheet>

All TopLevel elements are grouped by their CodeTL attribute. All Rating elements are grouped by a combination of their attributes and the CodeTL attribute of their corresponding TopLevel.

A: This generic XSLT 2.0 transformation:
<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:xs="http://www.w3.org/2001/XMLSchema"
 xmlns:my="my:my" exclude-result-prefixes="xs my">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/*">
     <t>
       <xsl:sequence select="my:grouping(*)"/>
     </t>
 </xsl:template>

 <xsl:function name="my:grouping" as="node()*">
   <xsl:param name="pElems" as="element()*"/>

   <xsl:if test="$pElems">
       <xsl:for-each-group select="$pElems" group-by="my:signature(.)">
         <xsl:copy>
          <xsl:copy-of select="@*"/>

            <xsl:sequence select="my:grouping(current-group()/*)"/>
         </xsl:copy>
       </xsl:for-each-group>
   </xsl:if>
 </xsl:function>

 <xsl:function name="my:signature" as="xs:string">
  <xsl:param name="pElem" as="element()"/>

  <xsl:variable name="vsignAttribs" as="xs:string*">
      <xsl:for-each select="$pElem/@*">
       <xsl:sort select="name()"/>

       <xsl:value-of select="concat(name(), '=', .,'|')"/>
      </xsl:for-each>
  </xsl:variable>

  <xsl:sequence select=
  "concat(name($pElem), '|', string-join($vsignAttribs, ''))"/>
 </xsl:function>
</xsl:stylesheet>

when applied on the provided XML (wrapped into a single top element to become well-formed XML document):
<t>
    <TopLevel CodeTL="Something">
        <Ratings>
              <Rating CodeA="ABC" Start="1-1-2012" End="1-2-2012">
                  <RatingByNumber Code="X" Rating="10" Number="1"/>
                  <RatingByNumber Code="X" Rating="19" Number="2"/>
              </Rating>
        </Ratings>
    </TopLevel>
        <TopLevel CodeTL="Something">
        <Ratings>
              <Rating CodeA="ABC" Start="1-2-2012" End="1-3-2012">
                  <RatingByNumber Code="X" Rating="10" Number="1"/>
                  <RatingByNumber Code="X" Rating="19" Number="2"/>
              </Rating>
        </Ratings>
    </TopLevel>
    <TopLevel CodeTL="Something">
        <Ratings>
              <Rating CodeA="XYZ" Start="1-2-2012" End="1-3-2012">
                  <RatingByNumber Code="X" Rating="10" Number="1"/>
                  <RatingByNumber Code="X" Rating="19" Number="2"/>
              </Rating>
        </Ratings>
    </TopLevel>
    <TopLevel CodeTL="Something">
        <Ratings>
              <Rating CodeA="XYZ" Start="1-2-2012" End="1-3-2012">
                  <RatingByNumber Code="X" Rating="30" Number="3"/>
                  <RatingByNumber Code="X" Rating="39" Number="4"/>
              </Rating>
        </Ratings>
    </TopLevel>
</t>

produces the wanted, correct result:
<t>
   <TopLevel CodeTL="Something">
      <Ratings>
         <Rating CodeA="ABC" Start="1-1-2012" End="1-2-2012">
            <RatingByNumber Code="X" Rating="10" Number="1"/>
            <RatingByNumber Code="X" Rating="19" Number="2"/>
         </Rating>
         <Rating CodeA="ABC" Start="1-2-2012" End="1-3-2012">
            <RatingByNumber Code="X" Rating="10" Number="1"/>
            <RatingByNumber Code="X" Rating="19" Number="2"/>
         </Rating>
         <Rating CodeA="XYZ" Start="1-2-2012" End="1-3-2012">
            <RatingByNumber Code="X" Rating="10" Number="1"/>
            <RatingByNumber Code="X" Rating="19" Number="2"/>
            <RatingByNumber Code="X" Rating="30" Number="3"/>
            <RatingByNumber Code="X" Rating="39" Number="4"/>
         </Rating>
      </Ratings>
   </TopLevel>
</t>

Explanation:

*

*The performed grouping is implemented in the function my:grouping() and is recursive.

*The top element is single at its level and doesn't need any other grouping than just shallow copy of itself. Then inside the body of this shallow copy the grouping of the lower levels is performed by the function my:grouping().

*The function my:grouping() has a single argument which is all the children elements of a all elements in a group at the immediate upper level. It returns all groups at the current level.

*The sequence of elements passed as argument to the function, is grouped based on their signature -- the concatenation of the name of the element with all name-value pairs of its attributes and their corresponding values, and these are separated using appropriate delimiters. The signature of an element is produced by the function my:signature() .

II. Generic XSLT 1.0 solution:
<xsl:stylesheet version="1.0"
         xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
         xmlns:ext="http://exslt.org/common"
         xmlns:my="my:my" exclude-result-prefixes="my ext">
         <xsl:output omit-xml-declaration="yes" indent="yes"/>
         <xsl:strip-space elements="*"/>

         <xsl:variable name="vrtfPass1">
          <xsl:apply-templates select="/*"/>
         </xsl:variable>

         <xsl:variable name="vPass1" select="ext:node-set($vrtfPass1)"/>

         <xsl:template match="/">
          <xsl:apply-templates select="$vPass1/*" mode="pass2"/>
         </xsl:template>

         <xsl:template match="/*" mode="pass2">
             <xsl:copy>
               <xsl:call-template name="my:grouping">
                <xsl:with-param name="pElems" select="*"/>
               </xsl:call-template>
             </xsl:copy>
         </xsl:template>

         <xsl:template name="my:grouping">
           <xsl:param name="pElems" select="/.."/>

           <xsl:if test="$pElems">
             <xsl:for-each select="$pElems">
              <xsl:variable name="vPos" select="position()"/>

              <xsl:if test=
               "not(current()/@my:sign
                   = $pElems[not(position() >= $vPos)]/@my:sign
                   )">

                 <xsl:element name="{name()}">
                  <xsl:copy-of select="namespace::*[not(. = 'my:my')]"/>
                  <xsl:copy-of select="@*[not(name()='my:sign')]"/>
                   <xsl:call-template name="my:grouping">
                    <xsl:with-param name="pElems" select=
                    "$pElems[@my:sign = current()/@my:sign]/*"/>
                   </xsl:call-template>
                 </xsl:element>
               </xsl:if>

             </xsl:for-each>
           </xsl:if>
         </xsl:template>

     <xsl:template match="/*">
             <xsl:copy>
               <xsl:apply-templates/>
             </xsl:copy>
     </xsl:template>

     <xsl:template match="*/*">
      <xsl:variable name="vSignature">
       <xsl:call-template name="signature"/>
      </xsl:variable>
      <xsl:copy>
       <xsl:copy-of select="@*"/>
       <xsl:attribute name="my:sign">
        <xsl:value-of select="$vSignature"/>
       </xsl:attribute>

       <xsl:apply-templates/>
      </xsl:copy>
     </xsl:template>

     <xsl:template name="signature">
       <xsl:variable name="vsignAttribs">
         <xsl:for-each select="@*">
          <xsl:sort select="name()"/>

                <xsl:value-of select="concat(name(), '=', .,'|')"/>
             </xsl:for-each>
        </xsl:variable>

        <xsl:value-of select=
          "concat(name(), '|', $vsignAttribs)"/>
     </xsl:template>
</xsl:stylesheet>

When this transformation is applied on the same XML document (above), again the same correct result is produced:
<t>
   <TopLevel>
      <Ratings>
         <Rating CodeA="ABC" Start="1-1-2012" End="1-2-2012">
            <RatingByNumber Code="X" Rating="10" Number="1"/>
            <RatingByNumber Code="X" Rating="19" Number="2"/>
         </Rating>
         <Rating CodeA="ABC" Start="1-2-2012" End="1-3-2012">
            <RatingByNumber Code="X" Rating="10" Number="1"/>
            <RatingByNumber Code="X" Rating="19" Number="2"/>
         </Rating>
         <Rating CodeA="XYZ" Start="1-2-2012" End="1-3-2012">
            <RatingByNumber Code="X" Rating="10" Number="1"/>
            <RatingByNumber Code="X" Rating="19" Number="2"/>
            <RatingByNumber Code="X" Rating="30" Number="3"/>
            <RatingByNumber Code="X" Rating="39" Number="4"/>
         </Rating>
      </Ratings>
   </TopLevel>
</t>

Explanation:

*

*This is a two-pass transformation.

*In the first pass for every element a signature is calculated and it becomes the valye of a new attribute my:sign.

*The same recursive grouping algorithm is used as with the XSLT 2.0 solution.


text:
Q: BlackBerry Java SDK < 6.0.0 on Mac I have a brand new installation of Eclipse with BlackBerry Plugin for mac.
The Java SDK 6.0.0 is already installed, the only thing now is that I want to compile for minor version, like 4.5.0
I have tried :
Help -> Install New Sotftware... -> http://www.blackberry.com/go/eclipseUpdate/3.5/java
But it gives me an error.
"No repository found at http://www.blackberry.com/go/eclipseUpdate/3.5/java"
anyone had the same issue ?
It seems that it worked for some people.

A: I don't know if what you're trying is possible, I also couldn't get it to work. According to the RIM site, they don't support building apps on OS X for non-6.0 right now, and based on the workaround below, I think it might not be as simple as installing the packages from the Eclipse installer.
However, I found a great post on building BlackBerry apps on OS X, and since then I've been working on my MBP, and can't say I would turn back. Here's a summary of how I got it set up:

*

*Install Eclipse (I am using 3.5, but it may not matter) and VirtualBox.

*Create a new VM and install Windows (tested with XP SP3). This
would probably work using VMWare Fusion or Parallels too.

*On the VM, install Java 6 and the version of the BlackBerry JDE
that matches your target OS.

*In OS X, download
bb-ant-tools.jar and move it
to ~/.ant/lib.

*Get an OS X version of preverify, which is included in the Sun
J2ME SDK 3.0 for OS
X.
Install it and either copy
/Applications/Java_ME_SDK_3.0.app/Contents/Resources/bin/preverify to
somewhere in your PATH or just add that directory to your PATH.

*If you don't have one already, create the file ~/.MacOSX/environment.plist.

*Edit this file with /Developer/Applications/Utilities/Property\
List\ Editor.app/.

*Create a new variable called PATH and set it to the value of your
shell PATH, making sure that the directory containing preverify is
included. This allows Ant, via Eclipse, to see the preverify command
when Eclipse is launched from Eclipse.app and not from the command
line. See this
for more details.

*In OS X, create a directory for the BlackBerry components
(something like "bb-components").

*From the BlackBerry JDE installation in the VM, copy both "lib" and
"bin" directories to this directory.

*In Eclipse, create a new Java project.

*Choose "Use an execution environment JRE:" and select Java 1.3.

*Right click the project in the "Package Explorer" and select "Build
Path" and then "Configure Build Path."

*Add bb-components/lib/net_rim_api.jar as an "External JAR."

*Remove the "JRE System Library." This is so that only BlackBerry
supported classes will be offered via autocompletion etc.

*Copy the attached minimal
build.xml into the project.

*Edit the build.xml to suit your environment (specifically the
jde.home property) and anything else you want to customise.

*Right click and select "Run as" and then "Ant Build" (the first
one). You can also build using Ant on the command line, of course.

These were adapted from https://spin.atomicobject.com/2010/11/04/our-blackberry-development-environment
Good luck!

A: I develop all of my BB apps on Mac hardware but I'm running Windows through Parallels.  Not better than having native Mac tools, but it works!


text:
Q: validateDOMNesting warning with a -based component using Enzyme.mount I have a component with a
 as the base element and it renders fine. But when I try to test it using mount, I get a warning:

Warning: validateDOMNesting(...):
 cannot appear as a child of
.

Here's a reproduction:
import React, {Component} from 'react';
import {mount} from 'enzyme';

class Foo extends Component {
  render() {
    return (

        moo

    )
  }
}

it('should not fail', () => {
  const wrapper = mount(<Foo />);
  console.log(wrapper.html());

});

In the call to mount, I can wrap the component with

<Foo />

 to make the warning go away. But it feels like there should be another way to do it since this warning doesn't happen with shallow or in the application itself.
This is with:

*

*React 16.5.2

*Enzyme 3.7.0

A: here is the way to fix it
it('should not fail', () => {
  const wrapper = mount(<Foo />, {
    attachTo: document.createElement('tbody'),
  });
  console.log(wrapper.html());
});


text:
Q: Solve $\sin^{3}x+\cos^{3}x=1$
Solve for $x\\ \sin^{3}x+\cos^{3}x=1$

$\sin^{3}x+\cos^{3}x=1\\(\sin x+\cos x)(\sin^{2}x-\sin x\cdot\cos x+\cos^{2}x)=1\\(\sin x+\cos x)(1-\sin x\cdot\cos x)=1$
What should I do next?

A: Both of $\sin(x),\cos(x)$ must be nonnegative since, if one of them was negative, the equation $\sin^3(x)+\cos^3(x)=1$ would imply that the other one is more than $1$, contradiction.

Thus, we have $0\le \sin(x) \le 1$ and $0\le \cos(x)\le 1$.

If both of $\sin(x),\cos(x)$ are less than $1$, then, since they are both nonnegative, we would have
$$
\begin{cases}
0\le \sin^3(x) < \sin^2(x)\\[4pt]
0\le \cos^3(x) < \cos^2(x)\\
\end{cases}
$$
but that would imply
$$\sin^3(x)+\cos^3(x) < \sin^2(x)+\cos^2(x)=1$$
contradiction.

It follows that one of $\sin(x),\cos(x)$ must be equal to $1$, and the other must be equal to zero.

From that information, I'm sure you can finish the solution.

A: Hint:
Let $\sin x+\cos x=t\implies t^2=?$
$$1=\dfrac{t\{2-(t^2-1)\}}2\iff t^3-3t+2=0$$
Clearly, $t=1$ a solution

A: Let use by $t= \tan (x/2)$

*

*$\sin x=\frac{2t}{1+t^2}$

*$\cos x=\frac{1-t^2}{1+t^2}$
to obtain
$$2t^6-8t^3+6t^2=0$$
$$\iff t^2(t^4-4t+3)=t^2(t-1)^2(t^2+2t+3)=0$$
and since $t^2+2t+3>0$ the solutions are

*

*$t=0 \implies \frac x 2=k\pi\implies x=2k\pi$

*$t=1 \implies \frac x 2=\frac{\pi}4+k\pi \implies x=\frac{\pi}2+2k\pi $

A: As an alternative by
$$\sin^3 x+ \cos ^3 x=1 \iff \sin x\cdot \sin^2+\cos x\cdot \cos^2 x=1$$
since $\sin^2 x+ \cos ^2 x=1$, the given equality is a weighted mean of $\sin x$ and $\cos x$ which holds if and only if

*

*$\sin x=1,\,\cos x=0$
or

*

*$\cos x=1,\,\sin x=0$

A: Hint $$\sin^3(x)+\cos^3(x)=\sin^2(x)+\cos^2(x).$$


text:
Q: TCPDUMP: are these args consistent or meaningless together? I'm using tcpdump on routing software, and trying to check whether the presence of ip/ip6 protocol with an ip6/ip host (i.e., the other IP family), or else specifying a mix of IPv4 and IPv6 IPs as hosts, is redundant, meaningless, or a user data sanitisation error. Or else, whether it can make reasonable sense as tcpdump capture parameters.
Is it consistent -- or capable of making sense - to specify tcpdump with proto='ip' but hosts
that include IPv6 IPs (or proto='ip6' but hosts that include IPv4)?
Can that ever make sense or return valid results? If so, when?
Thanks for any quick input, it'll help!

A: Something like this?
# tcpdump -i eth0 '(ip or ip6) and host www.google.com'

The above example is slightly more elaborate than it needs to be, to illustrate a point. The following will work fine too. www.google.com is a dual-stack host that includes A and AAAA records -- tcpdump automatically does 'or' logic that combines results when resolving a DNS host.
# tcpdump -i eth0 'host www.google.com'

This is effectively the same as:
# tcpdump -i eth0 '(host 74.125.237.20 or host 2404:6800:4006:800::1011)'

A: An IPv4 packet always has IPv4 source and destination addresses, and an IPv6 packet always has IPv6 source and destination addresses.
I don't really understand what you are trying to do, and I guess that means: "No, it doesn't make sense"


text:
Q: How to keep the process in a simple animation with some time duration? I want to change the imageview (x,y) values by using the setX(),setY(). It is directly going like an visible/gone. I just wants to keep this in a small animation so that it will go slowly to the given cordinates.
Is there any basic animation for performing this.

A: You should use ObjectAnimator and AnimatorSet to achieve this.
Use Following code:
ObjectAnimator oaX = ObjectAnimator.ofFloat(view, "translationX", 0, xValue);
oaX.setDuration(1000);
ObjectAnimator oaY = ObjectAnimator.ofFloat(view, "translationY", 0, yValue);
oaY.setDuration(1000);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(oaX, oaY);
animatorSet.start();

pass your coordinate values to xValue and yValue, these are relative to your image's actual coordinates.

A: The easiest way to move your imageview is here:
 imageview.animate().translationX(imageview.getWidth()).setDuration(1000).setInterpolator(new AccelerateDecelerateInterpolator());


text:
Q: Dagger and Login Credentials Im looking in a way to create a Dagger2 component to store UserCredentials after password validation
i have 3 activities -> Login, Home, About
i want to create a LoggedUser component after password validation at Login and than @Inject this UserLogged at Home and About, im trying to avoid multiple database access (my case ask for it) and than when user click close Home or About activity, it return to Login and destroy the UserLogged and than restart the process, but im a little bit lost how to create a Custom Component for @ActivityScope to be created at Login but destroyed at Login too
Curreclty im using Kotlin + MVP and Injecting Field at presenter in this way:
init {
        println("Presenter Init: " + javaClass.simpleName)
        MyApplicationCloudant.getAppComponent().inject(this)
}

the component is build in this way:
component = DaggerAndroidComponent.builder()
                .androidModule(AndroidModule(this))
                .build()

my AndroidModule:
@Module class AndroidModule(private val application: PontotelApplicationCloudant) {

    /**
     * Allow the application context to be injected but require that it be annotated with
     * [@Annotation][ForApplication] to explicitly differentiate it from an activity context.
     */
    @Provides @Singleton
//    @ForApplication
    fun provideApplicationContext(): Application {
        return application
    }

    @Provides @Singleton
    fun provideLocationManager(): LocationManager {
        return application.getSystemService(LOCATION_SERVICE) as LocationManager
    }

....

}

my AndroidComponent
@Singleton
@Component(modules = arrayOf(AndroidModule::class))
interface AndroidComponent {

    fun inject(application: MyApplicationCloudant)
    fun inject(loginPresenter: loginPresenter)
    fun inject(homePresenter: HomePresenter)
    fun inject(aboutPresenter: aboutPresenter)
}


text:
Q: Descomprimir un archivo .zip en PHP? Quisiera descomprimir un archivo que en que esta en un servidor usando php, alguien que sepa como hacerlo ?

A: Es bastante sencillo, lo puedes hacer de esta forma:
$zip = new ZipArchive;
// Asumiendo que este script está en el mismo directorio del zip, de lo contrario
// puedes darle la ruta absoluta del archivo
$res = $zip->open('nombre_archivo.zip');
if ($res === TRUE) {
  $zip->extractTo('/ruta/donde/guardar/archivos/');
  $zip->close();
  // Archivo descomprimido correctamente
} else {
   // Error descomprimiendo el archivo...
}

Puedes encontrar documentación más concreta y de manera oficial aquí


text:
Q: apt-get install phpmyadmin on debian doesn't install /etc/phpmyadmin/apache.conf I'm trying to install phpmyadmin on my webserver, using this guide:
http://www.howtoforge.com/ubuntu_debian_lamp_server
I did that once, and it worked like a dream, but I hated the looks of phpmyadmin (maybe the oldest layout ever) and decided to delete it, and didn't know that deleting is done with apt-get remove phpmyadmin and did in phpmyadmin directory rm * and thought that it's done. However, as I can't find the debian build of phpmyadmin anywhere, I want to install it again, but when I add Include /etc/phpmyadmin/apache.conf to /etc/apache2/apache2.conf, and restart apache, it give's me this error:
apache2: Syntax error on line 73 of /etc/apache2/apache2.conf: Could not open configuration file /etc/phpmyadmin/apache.conf: No such file or directory
Action 'configtest' failed.
The Apache error log may have more information.
 failed!

No matter how I try, I always get this error, and phpmyadmin isn't there.

A: First of all, just be defining "include /etc/..." in /etc/apache2/apache2.conf does not make the file magically appear in said destination.
But now, let's fix things.
You can reinstall phpmyadmin by executing "aptitude reinstall phpmyadmin" in the shell.
Debian's version of phpmyadmin can be downloaded from here: http://packages.debian.org/squeeze/all/phpmyadmin/download
You can search for Debian packages in here: http://www.debian.org/distrib/packages

A: Removing configuration files is considered to be a configuration change, and Debian packages are required to preserve configuration changes. So reinstalling a removed package will not cause removed configuration files to be restored. You need to purge the package rather than just remove. This will tell the packaging system that you no longer want even the configuration files for the package. Once that is done you can install the package again and the configuration files will be reinstalled as well.


text:
Q: Pentaho Data Integration setVariable not working I am on PDI 7.0 and have a "Modified Java Script Value" step inside a transformation as below:
var numberOfDays = 100;
Alert(numberOfDays);
setVariable("NUMBER_OF_DAYS", numberOfDays, "r");
Alert(getVariable("NUMBER_OF_DAYS", ""));

However, when I run the transformation, the first Alert correctly throws 100, but the next Alert is blank (meaning the variable is not set).
What is wrong here?

A: As a rule of thumb, you should never set a variable and read it within the same transformation.
See a warning that pops up in Spoon when setting up Set Variables step:

That said, what you could do, if you really insist on setting this via Java Script is the following design:

where
1) Set variable transformation is used to set the value:
var numberOfDays = 100;
Alert(numberOfDays);
setVariable("NUMBER_OF_DAYS", numberOfDays, "r");

2) Get variable transformatoin only reads it
Alert(getVariable("NUMBER_OF_DAYS", ""));

Both transformations use the same steps, but they have separate task.


text:
Q: Finding actual source file line number when JavaScript Error occurs? What is the industry standard or professional process of finding out where the actual line number in the source code of your rendered page is happening?
I have used browser debug tools and it of course shows you the error, but the line number is not the same for the source code file that is being served up. I know that usually server side scripts are making the file longer than it really is and etc.
I usually just do a find for functions or code near the error and can eventually find it, but is there a better way?

A: The simplest way is to ensure that most of your JS is written in non-templated .js files, rather than inline <script> blocks in your templated html.

A: I develop with Visual Studio.net 2013, which will stop at breakpoints and break on server and client side errors.
If you aren't developing with a tool like VisualStudio that has a built in debugger with breakpoints, etc., the built in developer tools in Chrome and IE are awesome (IMHO). Since Javascript runs clientside, you'll need to debug it using the browser.  If you don't like the built in developer tools, you can also try Fiddler and Firebug.


text:
Q: ubuntu seed file syntax All,
I have a shell script which is attempting to both copy and install a .deb as part of a late_command. I used what I found from this link as a guide.
https://gist.github.com/moonwitch/11100762

Here are the echo commands appending things to the end of lubuntu.seed
echo "d-i preseed/late_command string \ " >> "$WORK_DIR/preseed/lubuntu.seed"
echo "cp /cdrom/pool/extras/my.deb . ; \ " >> "$WORK_DIR/preseed/lubuntu.seed"
echo "d-i preseed/late_command string in-target dpkg -i /cdrom/pool/extras/my.deb ; " >> "$WORK_DIR/preseed/lubuntu.seed"

What really honks me off is the cp command doesn't appear to leave the file on the target no matter what I do. There are some other things I would like to copy and unzip.
I'm working with Ubuntu 15 32-bit. Really don't care about tools that "used to work" with earlier releases. I have spent 3 days searching through every discussion and every example/tool was for a really old version of Ubuntu. Haven't found one which still works today. Some kind of run, but they don't fully function.
My current problem is due to the fact I'm not a packager person, but this has to get done and I didn't get out of the way fast enough.
What I need is an actual functioning cp statement which copies a file from the CD to the target and leaves it there through reboot. So far nothing has.
Thank you

A: This is the line I used for the late command:
d-i preseed/late_command string cp /cdrom/somefile /target/system/folder && cp /cdrom/someshellscript.sh /target/system/folder && chroot /target chmod a+x /target/system/folder/someshellscript.sh && chroot /target sh /system/folder/someshellscript.sh

I appended the line above to my preseed file.  This line basically copies some script from the cdrom or iso to some folder in the target system.  During installation the /target folder is the "target" systems root system (get it?).
So for me I copied all the files I need from the CD or iso to some folder like root or opt or even tmp in the target system.  Then I changed root to /target and executed all the regular linux commands.  Wrote a shell script that executes after all the copying is done to do what I want it to do.
Note:
Inside my shell script, I unset all of the installer's environment stuff:
unset DEBCONF_REDIR

unset DEBCONF_FRONTEND

unset DEBIAN_HAS_FRONTEND

unset DEBIAN_FRONTEND

Then proceed accordingly.
Hope this helps.


text:
Q: Why does the Parse.com Join Table not work? I use this code for the Table View:
@implementation FollowerTableViewController

- (instancetype)initWithStyle:(UITableViewStyle)style {
    self = [super initWithStyle:style];
    if (self) { // This table displays items in the Todo class
        self.parseClassName = @"FriendClass";
        self.pullToRefreshEnabled = YES;
        self.paginationEnabled = YES;
        self.objectsPerPage = 25;
    }
    return self;
}

- (PFQuery *)queryForTable {
    PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];
    [query whereKey:@"to" equalTo:[PFUser currentUser]];

    // If no objects are loaded in memory, we look to the cache first to fill the table
    // and then subsequently do a query against the network.
    if (self.objects.count == 0) {
        query.cachePolicy = kPFCachePolicyCacheThenNetwork;
    }

    [query orderByDescending:@"date"];

    return query;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object {

    static NSString *cellIdentifier = @"cell1";

    PFTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[PFTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                      reuseIdentifier:cellIdentifier];

    }

    // Configure the cell to show todo item with a priority at the bottom
    cell.textLabel.text = object[@"from"];

    NSLog(@"%@", object[@"from"]);
    //cell.detailTextLabel.text = [NSString stringWithFormat:@"Priority: %@",  object[@"priority"]];
    NSLog(@"%@ , %@", object[@"from"], object[@"to"]);

    return cell;
}
@end

And this I uploaded before:
-(void)follow {
    // suppose we have a user we want to follow
    PFUser *otherUser = (PFUser *)textField.text;
    NSLog(@"%@", otherUser);

    // create an entry in the Follow table
    PFObject *follows = [PFObject objectWithClassName:@"FriendClass"];
    [follows setObject:[PFUser currentUser]  forKey:@"from"];
    [follows setObject:otherUser forKey:@"to"];
    [follows setObject:[NSDate date] forKey:@"date"];
    [follows saveInBackground];
}

any idea why it doesn't work.


text:
Q: What is "mssqljdbc_temp_sp_columns_result" table in SQL Server? We are seeing avg cpu time for the below query to be more than 100, occasionally in our production system. This is resulting in downtime for our services for few minutes.
Query:
INSERT INTO @mssqljdbc_temp_sp_columns_result
EXEC sp_columns_100 @P0,@P1,@P2,@P3,@P4,@P5


text:
Q: put  on, or put on
Put our bracelet on and don't let those numbers trouble you any more!

Is this correct? I am not sure about using the phrasal verb put on together, or separated by a noun :)
And in the second part of sentence, is those used correctly?

A: I won't touch the numbers part because the reasons or better call them issues you mention in your comments are not the numbers though most of them are expressed with some numeric values.
Okay, the first part: If you want to put on with put, go for it, that's okay!
on in put on serves as an adverbial particle. And, they can go between the verb and the object noun. Said that, **Put on our bracelets* is utterly grammatical. I can recall one of the examples from Swan's PEU on this where Switch off the light (or similar kind of sentence) was said correct [However, This does not mean that they are always together. Read some more examples where these particles are detached from the verb and placed after the object.
Now the second part.
The pronoun those is okay if you have already mentioned what those numbers are. In other words, if this is the first sentence of any literature, those does not make any sense. You need to mention first what those is as a general rule of pronouns that replace nouns.

A: Answering questions in order:

*

*Is [put our bracelet on] correct? Yes, it is valid English.

*Is [let those numbers] used correctly? Possibly, if the numbers in question are far away from the speaker.

In English, Demonstratives denote their proximity (closeness) to the speaker. The words this and these denote they are close (proximal), while the words that and those denote that they are further away (distal). To illustrate, these cups in my hands are much closer than those cups on the far end of the table.
Tying that back to the example sentence, the word those denotes that the numbers are a distance away from the speaker. Therefore, if the numbers are displayed on a screen across the room, or written on a piece of paper in the next room, the usage would be correct. Even if the numbers in question are a group of rabid living numerals which have been caught and dragged into cages in a different building, the use of those would be correct.
If, however, the numbers are displayed on a nearby monitor, or written on the very bracelet being put on which is in the hands of the speaker, the correct word to use would be these.


text:
Q: How to get JSON response from API with multiple same responses? I am trying to make it make it return just the message ids (so I can check each one separately)
Here is my code:
@client.command()
async def inbox(ctx, username, domain):
    url = ('https://www.1secmail.com/api/v1/?action=getMessages&login=' + username + '&domain=' + domain)

    response = requests.get(url)
    ids = response.json()['id']

    embed = discord.Embed(description=f"Ids: {ids}")

    await ctx.send(embed=embed)

If I remove ['id'] it works but will show all the headers etc

A: when you use response.json() - you receive an all JSON stucture that has been converted to python dict. I checked this endpoint https://www.1secmail.com/api/v1/?action=getMessages it returns the following JSON:
[
    {
        "id": 639,
        "from": "someone@example.com",
        "subject": "Some subject",
        "date": "2018-06-08 14:33:55"
    }, {
        "id": 640,
        "from": "someoneelse@example.com",
        "subject": "Other subject",
        "date": "2018-06-08 14:40:55"
    }
]

So if you need to gather all id from list. You can use this approach.
# I recommend you use a try/except block to catch the exceptions here
response_data = response.json()
ids = [message.get("id") for message in response_data]


text:
Q: Compare files without extension and delete files from folder in Powershell I compare files inside a folder. In this folder some files are existing in two file formats (filename1.jpg, filename1.bmp, ...) and some files are only existing in one format.
I try to find all files which are only existing in .bmp format and delete them.
The Code I got so far is:
$jpg = Get-ChildItem "C:\..\" -File -Filter *.jpg | ForEach-Object -Process {[System.IO.Path]::GetFileNameWithoutExtension($_)}
$bmp = Get-Childitem "C:\..\" -File -Filter *.bmp | ForEach-Object -Process {[System.IO.Path]::GetFileNameWithoutExtension($_)}

Compare-Object $jpg $bmp | where {$_.SideIndicator -eq  "=>"}

This lists me the files I am looking for but I have trouble deleting them. I tried some things like:
Compare-Object $jpg $bmp | where {$_.SideIndicator -eq  "=>"} | ForEach-Object {
    Remove-Item  "C:\..\($_.FullName)"
    }

but without any success. Does anyone have a hint how I could solve this?

A: In your foreach your variable is not a file, it is the result from the compare.
Try this:
$a = Get-ChildItem "D:\a" -File -Filter *.jpg
$b = Get-Childitem "D:\b" -File -Filter *.bmp
Compare-Object $a.BaseName $b.BaseName | where {$_.SideIndicator -eq  "=>"}  | foreach {
    $name = $_.InputObject
    $File = $b.Where({$_.BaseName -eq $name})

    if ($File.Count -gt 1) {
        throw "Conflict, more than one file has the name $name"
    } else {
        Remove-Item -Path $File.FullName
    }
}


text:
Q: Estimation of Rth(ja) when not provided I am looking at the datasheet of a SiC MOSFET, which has a junction to case thermal resistance  Rth(j-c) max of 1.41°C / W.

The junction to ambient thermal resistance is not provided, as this type of power transistors are usually used with a heatsink.
Is there a way to estimate the Rth(j-a) ? I want to estimate the losses without a heatsink.
Thanks.

A:
Is there a way to estimate the Rth(j-a) ?

There are some hints on this wiki site about TO-220 packages and there is a useful paragraph that compares values including that of the TO-247-3 package (used in that rather feeble GeneSic MOSFET you are asking about): -

If more heat needs to be dissipated, devices in the also widely used
TO-247 (or TO-3P) package can be selected. TO-3P has a typical
junction-to-ambient (heatsink) thermal resistance of only about 40
°C/W

So, I think the answer you require is ~ 40°C/W

I want to estimate the losses without a heatsink

Well, the "losses" will be the same for a given current and voltage but, the temperature difference will be vastly changed.

Be aware that the G3R160MT12D device is rather poor on peak power dissipation (see figure 14 in its data sheet) compared to other 1,200 volt devices such as those from ON-SEMI. However, you may be considering this part not because it might appear to be attractive but, because it is available. Be very aware about its limitations


text:
Q: How to use join together with dict I have been working on a small projects where I have a counter to check if a characters reaches a specific number, then it will print it out on given count. If it doesnt reach the counter then we just print out the whole dicts.
I have done something like this:
payload = {'40': None, '42': None, '44': '6', '43': '3', '46': None, '45': '7', '51': None, '48': None, '47': None,
           '39': None}

characterCount, i = 0, 0
for j, item in enumerate(payload):

    if len(item) + characterCount > 5:
        print('\n'.join(payload[i:j]))
        characterCount, i = len(item), j
    else:
        characterCount += len(item)

if characterCount:
    print('\n'.join(payload[i:]))

I do have two problems.

*

*This would probably work very well when using lists instead of dicts but yeah, thats not my options so I wonder if its possible to execute by calling indexes as I have done. I am fully aware that this will give an error: TypeError: unhashable type: 'slice' but I do not know if there is something similar way or maybe even better.

*Also I would like to print the Key and Value (ONLY if value has a value, if it doesnt contain any value then we skip to print the None)
Is this sometihng that is possible to do?
EDIT:
This is how I used to do use before when I used Lists instead, however I have of course needed more knowledge where I need to store in key:value, Instead of having two lists where I store key and value for itself (There is probably better way) but I found that dict would be a better suite for me.
This is what I had before:
payload = ['40', '42', '44', '43', '46', '45', '51', '48', '47', '39']

characterCount, i = 0, 0
for j, item in enumerate(payload):

    if len(item) + characterCount > 5:
        print("Inside the if statement")
        print('\n'.join(payload[i:j]))
        characterCount, i = len(item), j
    else:
        characterCount += len(item)

if characterCount:
    print('\n'.join(payload[i:]))

Outprint
Inside the if statement
40
42
Inside the if statement
44
43
Inside the if statement
46
45
Inside the if statement
51
48
47
39

and this is what im trying to do but using dicts instead :)

A: I did not quite understand what the point of the program is, but if I understood what you want to do it correctly, then you could use a filtered dictionary with key-value pairs that has value (not None).
print('\n'.join(list(filter(lambda k: payload[k] is not None, payload))))

Edit, here is an updated version, hopefully it's closer to what you're looking for:
payload = {'40': None, '42': None, '44': '6', '43': '3', '46': None, '45': '7', '51': None, '48': None, '47': None,
           '39': None}

characterCount, i = 0, 0
for j, item in enumerate(payload):
    if len(item) + characterCount > 5:
        selectedPayloads = ['{0} {1}'.format(k, payload[k]) for k in list(payload)[i:j] if payload[k] is not None]
        if len(selectedPayloads) != 0:
            print('\n'.join(selectedPayloads))
        characterCount, i = len(item), j
    else:
        characterCount += len(item)


text:
Q: How to implement SAML 2.0 single sign on in Excel VBA? Currently I have a login form which opens upon opening the excel workbook and is using basic authentication to validate login credentials from Oracle Fusion via a simple SOAP request. However, now I'm required to implement Microsoft single sign on. Is it possible to achieve this using SOAP or REST API's? The authentication needs to be done via SAML 2.0 against my organizations Azure AD.
The code I'm currently using:
    Dim vFlag As Integer
    Dim tmpReport As String
    Dim documentID As String

    Dim sURL As String
    Dim xmlhtp As New MSXML2.XMLHTTP60
    vFlag = 0

    Dim xmldoc As Object
    Dim xmlnode As Object
    Set xmldoc = CreateObject("Microsoft.XMLDOM")
    xmldoc.SetProperty "SelectionLanguage", "XPath"
    xmldoc.async = False
    Dim xml As String
    sURL = Constants.EXT_REPORT_SERVICE_URL
    setStatus ("Calling report ..." & sURL)
    tmpReport = tmpReport & vbCrLf & "<soapenv:Envelope xmlns:soapenv=""http://www.w3.org/2003/05/soap-envelope"" xmlns:pub=""http://xmlns.oracle.com/oxp/service/PublicReportService""> "
    tmpReport = tmpReport & vbCrLf & "   <soapenv:Header/>                                                                                "
    tmpReport = tmpReport & vbCrLf & "   <soapenv:Body>                                                                                "
    tmpReport = tmpReport & vbCrLf & "      <pub:validateLogin/>                                                                                "
    tmpReport = tmpReport & vbCrLf & "   </soapenv:Body>                                                                                "
    tmpReport = tmpReport & "</soapenv:Envelope>"

    With xmlhtp
        .Open "post", sURL, False
        .SetRequestHeader "Content-Type", "application/soap+xml; charset=UTF-8"
        .SetRequestHeader "soapAction", "validateLogin"
        .SetRequestHeader "Authorization", "Basic " & Base64.EncodeTextBase64(username + ":" + password)
        .Send tmpReport
    xml = .ResponseText
    If InStr(1, xml, "true", vbTextCompare) Then
        vFlag = 1
    End If
    validateLogin = vFlag
    End With
End Function```


text:
Q: Name validation using jquery validation framework I want to add a custom function using jquery validation framework, to help validating names (first name and last name) inside a form.
I understand I could just eliminate numbers... but wondering if there is a 'best practice' way using jquery validation framework, somebody could suggest me...?
Thanks

A: I used regular expression to validate the name fields on the form : ^[a-zA-Z'-]+$
using the jquery.validator.addMethod


text:
Q: XMLHttpRequest always sends as GET So I wrote an AJAX js library a while ago (a simple one) and today I suddenly noticed it wasn't working anymore.
Now, I've ripped some of the code out of it and manually put it into a script to test it. Again, it's not working correctly. I was wondering if anyone could help me figure out why?
This is the javascript code:
Now here, the first one works and the second one doesn't...
  $loginBtn.on("click", function() {
    if(validateForm($loginForm))
    {
      var xhttp = new XMLHttpRequest();
      xhttp.open("POST", "/login/login/", true);
      xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      xhttp.send("fname=Henry&lname=Ford");

      var url    = $loginForm.attr('action');
      var params = "username=foo&password=bar";
      var xhttp2 = new XMLHttpRequest();
      xhttp2.open('POST', url, true);
      xhttp2.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
      xhttp2.send(params);

    }
    return false;
  });

The end goal is to do this with formData(), but i'm going back to basics to see what's going wrong here.
The thing is, that even though the XMLHttpRequest DOES fire, it seems to completely ignore everything I set for it.
The headers return as a GET while I'm setting it to POST, the content-type I set is nowhere to be seen. No matter what header I add, it's not being added.
It just sends a GET for no apparent reason. The call in itself is succesful and gives the appropriate response, though.
things I've tried so far;

*

*checked any type of caching and made sure I'm not using cached scripts

*stripped away all extra functions to make sure there is nothing else going wrong

*Made sure there is no server-side caching of any kind

*Disabled all other scripts for testing reasons.


text:
Q: Error while installing wxpython with conda and pip (import error) I am experiencing some troubles installing wxpython.
I tried to install it via conda, but I get the following result while running a script:
Traceback (most recent call last):
  File "test.py", line 5, in <module>
    import wx
  File "/home/me/anaconda3/envs/myenv/lib/python3.8/site-packages/wx/__init__.py", line 17, in <module>
    from wx.core import *
  File "/home/me/anaconda3/envs/myenv/lib/python3.8/site-packages/wx/core.py", line 12, in <module>
    from ._core import *
ImportError: /home/me/anaconda3/envs/myenv/lib/python3.8/site-packages/wx/../../../././libharfbuzz.so.0: undefined symbol: FT_Get_Transform

The package in pip has the following description:
Name: wxPython
Version: 4.1.1
Summary: Cross platform GUI toolkit for Python, "Phoenix" version
Home-page: http://wxPython.org/
Author: Robin Dunn
Author-email: robin@alldunn.com
License: wxWindows Library License (https://opensource.org/licenses/wxwindows.php)
Location: /home/me/anaconda3/envs/myenv/lib/python3.8/site-packages
Requires: numpy, pillow, six

and in conda:
 # Name                    Version                   Build  Channel
    wxpython                  4.1.1            py38hc041153_7    conda-forge

The same problem occurs when installing it via a simple pip install wxpython.
I am running python 3.8.13 on Ubuntu 20.04.4.
Do you have any recommendation on how to proceed?


text:
Q: Why does this factorial program work? This is a factorial program shown in the tutorialpoints C# tutorial, I understand the basic concept of recursion, but i'm not sure why it works in this context. The program is this:
public int factorial(int num)
{
    /* local variable declaration */
    int result;
    if (num == 1)
    {
        return 1;
    }
    else
    {
        result = factorial(num - 1) * num;
        return result;
    }
}

static void Main(string[] args)
{
    NumberManipulator n = new NumberManipulator();
    //calling the factorial method
    Console.WriteLine("Factorial of 6 is : {0}", n.factorial(6));
    Console.WriteLine("Factorial of 7 is : {0}", n.factorial(7));
    Console.WriteLine("Factorial of 8 is : {0}", n.factorial(8));
    Console.ReadLine();
}

A: During your recursion you will decrease the value of num by 1 and when the recursion stop because num == 1 then you will return your recursion and mutltiply each values.
factorial(5)
      -> factorial(4) * 5
           -> factorial(3) * 4
                    -> factorial(2) * 3
                             -> factorial(1)

at the end if will do : 1 * 2 * 3 * 4 * 5 = 120;


text:
Q: "The service is disabled now." on Synology Diskstation When I try to execute phpMyAdmin on my DS213 under DSM 4.3-3810 I get the message "The service is disabled now."
I have tried uninstalling phpMyAdmin and disabling Web Station and MySQL, rebooting and enabling Web Station and MySQL and reinstalling phpMyAdmin.
I have also reset the Diskstation and re-installed DSM, but I still get the message.

A: Note: Before connecting to phpMyAdmin to manage the MySQL, make sure you have enabled the Web Station service on the web management UI of the Synology Server.
http://www.synology.com/en-us/support/tutorials/458#t3


text:
Q: NullPointerException in bottomsheetbehavior (only in release variant) I am getting NPE (NullPointerException) on BottomSheetBehavior only when build variant is in release mode. If i test with debug variant it is working fine. But when i make this as release variant the app is crashing. I am calling the setBottomSheet() method in onCreate() lifecycle.
This is my XML code :
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/coordinator_scanactivity"
android:layout_width="match_parent"
android:layout_height="match_parent"
>

<include layout="@layout/activity_scan_content" />

<!--<include layout="@layout/bottom_sheet" />-->

<RelativeLayout
    android:id="@+id/bottom_sheet_layout"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:background="@android:color/white"
    android:orientation="vertical"
    app:behavior_hideable="true"
    app:behavior_peekHeight="35dp"
    app:layout_behavior="android.support.design.widget.BottomSheetBehavior">

    <LinearLayout
        android:id="@+id/bottom_sheet_header"
        android:layout_width="match_parent"
        android:layout_height="35dp"
        android:background="@color/colorPrimary"
        android:orientation="vertical">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:padding="5dp"
            android:src="@drawable/bottom_sheet_up" />
    </LinearLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/bottom_sheet_header"
        android:layout_marginBottom="16dp"
        android:layout_marginTop="16dp" />
</RelativeLayout>

<ImageView
    android:id="@+id/add_device_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/divider_view"
    android:paddingBottom="10dp"
    android:paddingRight="10dp"
    android:src="@drawable/add"
    app:layout_anchor="@id/bottom_sheet"
    app:layout_anchorGravity="top|end" />
</android.support.design.widget.CoordinatorLayout>

This is my java code :
private void setBottomSheet() {

    llBottomSheet = (RelativeLayout) findViewById(R.id.bottom_sheet_layout);

    bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
        @Override
        public void onStateChanged(@NonNull View bottomSheet, int newState) {
            if (newState == BottomSheetBehavior.STATE_EXPANDED) {
                System.out.println("Inactive Device Bottom Sheet Expanded");
            }
        }

        @Override
        public void onSlide(@NonNull View bottomSheet, float slideOffset) {
            add_device_btn.animate().scaleX(1 - slideOffset).scaleY(1 - slideOffset).setDuration(0).start();
        }
    });
}

And my log file:
FATAL EXCEPTION: main
Process: com.webmobi.trackm, PID: 2676
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.ViewDragHelper.processTouchEvent(android.view.MotionEvent)' on a null object reference
    at android.support.design.widget.BottomSheetBehavior.onTouchEvent(BottomSheetBehavior.java:315)
    at android.support.design.widget.CoordinatorLayout.resetTouchBehaviors(CoordinatorLayout.java:396)
    at android.support.design.widget.CoordinatorLayout.onAttachedToWindow(CoordinatorLayout.java:238)
    at android.view.View.dispatchAttachedToWindow(View.java:15532)
    at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2918)
    at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2925)
    at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2925)
    at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2925)
    at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2925)
    at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2925)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1572)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1300)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6405)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:876)
    at android.view.Choreographer.doCallbacks(Choreographer.java:688)
    at android.view.Choreographer.doFrame(Choreographer.java:623)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:862)
    at android.os.Handler.handleCallback(Handler.java:754)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:163)
    at android.app.ActivityThread.main(ActivityThread.java:6205)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)

A: Add this code:
if (mViewDragHelper == null) {
mViewDragHelper = ViewDragHelper.create(parent, mDragCallback);
}

before mViewDragHelper.processTouchEvent(event); into ViewPagerBottomSheetBehavior file (line probably 274).


text:
Q: Java- Comparing names to a list of names using if/else and switch statements I am a beginner coder who is trying to figure out how to use nested if/else and switch statements. I decided to challenge myself to write 2 programs (one with if/else and one with switch) that will compare 1 person's name to at least 15 other people's. If that 1 name matches with any of the 15 other names (besides that person's own name), it will print something. For example, the 15 names will be the names of everyone on a football team. I want to see if someone on the team has someone that shares their name. For the if/else program, I currently have this:
package practice;

    public class ClassmatesIfElse {

        public static void main(String[] args) {
            String name = "person";
            if(name.equals("person1")|| name.equals("person2") || name.equals("person3") || name.equals("person4") || name.equals("person5") || name.equals("person6") || name.equals("person7") || name.equals("person8") || name.equals("person10"))
                System.out.println("Duplicate");
            else System.out.println("Unique");
        }

    }

But obviously, it is very cumbersome and it doesn't work unless you remove the person you want to test from the list, which kind of defeats the purpose of the program. And I do not know where to start for the switch statement one. What is the best way to go about this? Thank you.

A: So I agree with the comments that if you are looking for the most efficient way to determine if there are duplicates in 15 names, that you would want to use something other than nested if/then statements or a switch. I would actually suggest using a Map for this kind of work, storing the name as the key, and the count of its appearance as the value (I'm happy to create an example of this; just let me know).
However to answer your question of how you would execute the same code using a switch statement, please see below. The code actually ends up being quite lengthy but it perhaps easier to read:
class SwitchExample {

    private static final String SUCCESS= "Hey! You have a name doppleganger in the class!";

    public static void main(String[] args) {
        String name = "person";

        switch(name) {
        case "person1":
            System.out.println(SUCCESS);
            break;

        case "person2":
            System.out.println(SUCCESS);
            break;

        case "person3":
            System.out.println(SUCCESS);
            break;

        case "person4":
            System.out.println(SUCCESS);
            break;

        case "person5":
            System.out.println(SUCCESS);
            break;

        case "person6":
            System.out.println(SUCCESS);
            break;

        case "person7":
            System.out.println(SUCCESS);
            break;

        case "person8":
            System.out.println(SUCCESS);
            break;

        case "person10":
            System.out.println(SUCCESS);
            break;

        default:
             System.out.println("Your name is unique in this class!");

        }
    }
}


text:
Q: Why isnt open mp parallelizing this code? This code is not making the code calculating the 4 sums faster. Instead, it even takes more time.
Also The output is not as expected.
#include <stdio.h>
#include <omp.h>
int main()
{
    int i,j,k,l;
    int sum = 0,sum1 = 0,sum2 = 0,sum3 = 0;
    #pragma omp parallel
    {
        #pragma omp sections
        {
            #pragma omp section
            {
                printf("%d",omp_get_thread_num());
                for(i = 0; i < 500000000; i++) sum = sum + 1;
            }
            #pragma omp section
            {
                printf("%d",omp_get_thread_num());
                for(i = 0; i < 500000000; i++) sum1 = sum1 + 1;
            }
            #pragma omp section
            {
                printf("%d",omp_get_thread_num());
                for(i = 0; i < 500000000; i++) sum2 = sum2 + 1;
            }
            #pragma omp section
            {
                printf("%d",omp_get_thread_num());
                for(i = 0; i < 500000000; i++) sum3 = sum3 + 1;
            }
        }
    }
    printf("sum is %d %d %d %d",    sum,sum1,sum2,sum3);
}

The output is sum is 218748707 222052401 239009041 196849489
Do let me know the flaw in using openmp here.

A: The slowdown stems from the fact that sum, sum1, sum2 and sum3 are shared variables and as such the compiler must generate fetch / update / store instructions for each increment instead of just keeping intermediate sum in a register as is the case for the serial version.
You should make each sum local to the thread it is used in. The easiest way to do it is to make a reduction over each sum:
#pragma omp parallel private(i) reduction(+:sum,sum1,sum2,sum3)
{
    // Rest of the code goes unchanged
}

private(i) will solve the problem with incorrect results. reduction(+:sum,sum1,sum2,sum3) will make each thread accumulate its own copy of sum, sum1, sum2 and sum3, and in the end local copies will be added up to form the final values.
Here are some performance figures:
Serial version - 3.812 seconds:
$ gcc -o mp.x mp.c -lgomp
$ time ./mp.x
0000sum is 500000000 500000000 500000000 500000000
./mp.x  3.81s user 0.00s system 99% cpu 3.812 total

OpenMP version with shared variables - 7.982 seconds:
$ gcc -fopenmp -o mp.x mp.c
$ time OMP_NUM_THREADS=4 ./mp.x
0132sum is 500000000 500000000 500000000 500000000
OMP_NUM_THREADS=4 ./mp.x  21.88s user 0.86s system 284% cpu 7.982 total

OpenMP version with reduction - 1.226 seconds:
$ gcc -fopenmp -o mp.x mp.c
$ time OMP_NUM_THREADS=4 ./mp.x
0321sum is 500000000 500000000 500000000 500000000
OMP_NUM_THREADS=4 ./mp.x  4.53s user 0.00s system 370% cpu 1.226 total

There is also another code transformation that additionally slows things down and it is the fact that sum, sum1, sum2 and sum3 are located on the stack of the main program while the sections code is being extracted by the OpenMP processor and put into separate function that is then called by each thread in the parallel team. This function is provided a data structure that contains pointers to the four shared sums and the code operates with those pointers. You can compare the assembler output in both cases and see for yourself - it is very instructive to do so if you'd like to dive deeper into parallel performance stuff.

A: It's not always free to use concurrency. There may be overhead involved that you don't see, for example creating new threads, locking memory areas and such. You can't always expect a performance boost for trivial tasks.
The reason you don't get the expected output is because all threads uses the same loop variable (i). This causes data races, which is also the reason your sums don't add up to 500000000.


text:
Q: Llamar a metodo dentro de otro tengo un problema a la hora de llamar al otro método. Hice un método para no estar haciendo mucho código. Pero a la hora de llamar al otro método no me funciona.
matrizButaca = muestraMatriz();
Mas que todo tengo mi problema ahí, no se porque no se están llamando, si pueden ayudarme se los agradecería demasiado.
En el IDE me tira esto: reason: actual and formal argument lists differ in length
    // Declaracion de VARIABLES.
    int menuTeatroOpciones;

    //Declaración matriz principal
    char matrizButaca[][] = new char [5][22];
    matrizButaca = muestraMatriz();
    do
    { // Inicio DO.

        System.out.println("*************\n"+"MENU\n"+"*************\n"+"[1] Mostrar butacas\n"+"[2] Registrar reserva\n"+
        "[3] Registrar venta de butacas\n"+"[4] Anular venta de butacas\n"+"[5] Mostrar resumen de butacas\n"+"[6] Salir\n");
        menuTeatroOpciones = sc.nextInt();

        switch(menuTeatroOpciones){ // Inicio SWITCH.
            case 1:
                System.out.println("Butacas disponibles: ");
                muestraMatrizPrincipal(matrizButaca);
                break;
            case 2:
                muestraRegistrarReserva(matrizButaca);
                break;
            System.out.println("Adiós ");
            break;*/

            default:
                System.out.println("Opción de menú INCORRECTA.");
                break;
        } // Fin SWITCH.
    }while(menuTeatroOpciones != 2);

} // Fin segundo.

// Inicio de METODOS.
public static void muestraMatriz(char matriz [][]){ // Inicio METODO.
    for(int f = 0 ; f < matriz.length ; f++){ // Inicio FOR.
        for(int c = 0 ; c < matriz[f].length ; c++){ // Inicio FOR.

            matriz[f][c]= 'L';
            matriz[f][5] = 'P';
            matriz[f][16] = 'P';
        } // Fin FOR.

    } // Fin FOR.

} // Fin METODO.

// Metodo que abarca todo

public static void muestraMatrizPrincipal(char matriz [][]){ // Inicio METODO

    for(int f = 0 ; f < matriz.length ; f++){
        for(int c = 0 ; c < matriz[f].length ; c++){
            System.out.print(matriz[f][c]+" ");
        }
        System.out.println("");
    }
}// Fin METODO.

A: Estás tratando de llamar a muestraMatriz() sin parámetros y además tratando de asignárselo al Array de tipo char matrizButaca[][] que ya está inicializado anteriormente en la siguiente línea.
char matrizButaca[][] = new char [5][22]; // creado e inicializado en la misma línea

El error:

reason: actual and formal argument lists differ in length

Se podría traducir a que, la cantidad de parámetros que estás tratando de pasar a un método, no coinciden con la cantidad de parámetros que este recibe de acuerdo a como fue construido.

Es debido a que estás tratando de llamar a un método sin pasar ningún parámetro:
matrizButaca = muestraMatriz(); //llamada al método sin ningún parámetro

Pero cuando creaste el método muestraMatriz() este recibe Array de tipo char como parámetro:
public static void muestraMatriz(char matriz [][]){...} //recibe un parámetro

Para que el método trabaje con el Array matrizButaca, debes de mandarla como parámetro, no tratar de asignarlo.
muestraMatriz(matrizButaca); // array pasado como parámetro


text:
Q: The moderator queue is no longer a queue The items in the moderator queue are no longer showing up in order from newest to oldest.  As I write this, the items in the list on Stack Overflow have the following time stamps:
2 hours ago
3 mins ago
1 min ago
11 min ago
...

There was a recent update (which I really like, by the way) that adds a note to each item in the list when a moderator performs some action on the flagged post.  If this is related, is the new order [status-bydesign]?  If not, can we get it changed back to the newest-to-oldest order?

A: Actually there is some truth in Michael's answer; we're playing with things that should make the most pressing issues appear first, to make moderation easier. I also plan on merging the three tabs, and tracking the number of mods that have viewed a post without doing anything urgently.
All suggestions and feedback welcome here.
To be specific, in addition to taking the cumulative flags into account, there is a subtle variation between users; users with a history of flags that lead to action by moderators will be ranked a little bit above users who have a history of false-positive flags.


text:
Q: Unet Segmentation Model I am trying to solve Baby detection with unet segmentation model. I already collected baby images, baby segments and also passed the adult images as negative (created black segments for this).
So if I will do in this way is unet model can differentiate the adults and babies? if not what I have to do next?

A: It really depends on your dataset.
During the training, Unet will try to learn specific features in the images, such as baby's shape, body size, color, etc. If your dataset is good enough (e.g. contains lots of babies examples and lots of adults with a separate color and the image dimensions are not that high) then You probably won't have any problems at all.
There is a possibility however, that your model misses some babies or adults in an image. To tackle this issue, There are a couple of things you can do:

*

*Add Data Augmentation techniques during the training (e.g. random crop, padding, brightness, contrast, etc.)

*You can make your model stronger by replacing Unet model with a new approach, such as Unet++ or Unet3+. According to Unet3+ paper, it seems that it is able to outperform both Unet & Unet++ in medical image segmentation tasks:
https://arxiv.org/ftp/arxiv/papers/2004/2004.08790.pdf
Also, I have found this repository, which contains a clean implementation of Unet3+, which might help you get started:
https://github.com/kochlisGit/Unet3-Plus


text:
Q: Fortran SAVE statement I've read about the save statement in the (Intel's) language reference document, but I cannot quite grasp what it does. Could someone explain to me in simple language what it means when the save statement is included in a module ?

A: Normally, local variables go out of scope once execution leaves the current procedure, and so have no 'memory' of their value on previous invocations. SAVE is a way of specifying that a variable in a procedure should maintain its value from one call to the next. It's useful when you want to store state in a procedure, for example to keep a running total or maintain a variable's configuration.
There's a good explanation here, with an example.

A: In principal when a module goes out-of-scope, the variables of that module become undefined -- unless they are declared with the SAVE attribute, or a SAVE statement is used.   "Undefined" means that you are not allowed to rely on the variable having the previous value if you again use the module -- it might have the previous value when you re-access the module, or it might not -- there is no guarantee.  But many compilers don't do this for module variables -- the variables probably retain their values -- it isn't worth the effort for the compiler to figure out whether a module remains in scope or not and probably module variables are treated as global variables -- but don't rely on that!   To be safe, either use "save" or "use" the module from the main program so that it never goes out of scope.
"save" is also important in procedures, to store "state" across invocations of the subroutine or function (as written by @ire_and_curses) -- "first invocation" initializations, counters, etc.
subroutine my_sub (y)

integer :: var
integer, save :: counter = 0
logical, save :: FirstCall = .TRUE.

counter = counter + 1

write (*, *) counter

if (FirstCall) then
   FirstCall = .FALSE.
   ....
end if

var = ....

etc.
In this code fragment, "counter" will report the number of invocations of subroutine x.   Though actually in Fortran >=90 one can omit the "save" because the initialization in the declaration implies "save".
In contrast to the module case, with modern compilers, without the save attribute or initialization-on-a-declaration, it is normal for local variables of procedures to lose their values across invocations.  So if you attempt to use "var" on an later call before redefining it in that call, the value is undefined and probably won't be the value calculated on a previous invocation of the procedure.
This is different from the behavior of many FORTRAN 77 compilers, some of which retained the values of all local variables, even though this wasn't required by the language standard.  Some old programs were written relying on this non-standard behavior -- these programs will fail on the newer compilers.  Many compilers have an option to use the non-standard behavior and "save" all local variables.
LATER EDIT: update with a code example that shows incorrect usage of a local variable that should have the save attribute but doesn't:
module subs

contains

subroutine asub (i, control)

   implicit none

   integer, intent (in) :: i
   logical, intent (in) :: control

   integer, save :: j = 0
   integer :: k

   j = j + i
   if ( control ) k = 0
   k = k + i

   write (*, *) 'i, j, k=', i, j, k

end subroutine asub

end module subs

program test_saves

   use subs
   implicit none

   call asub ( 3, .TRUE. )
   call asub ( 4, .FALSE. )

end program test_saves

Local variable k of the subroutine is intentionally misused -- in this program it is initialized in the first call since control is TRUE, but on the second call control is FALSE, so k is not redefined.   But without the save attribute k is undefined, so the using its value is illegal.
Compiling the program with gfortran, I found that k retained its value anyway:
 i, j, k=           3           3           3
 i, j, k=           4           7           7

Compiling the program with ifort and aggressive optimization options, k lost its value:
 i, j, k=           3           3           3
 i, j, k=           4           7           4

Using ifort with debugging options, the problems was detected at runtime!
 i, j, k=           3           3           3
forrtl: severe (193): Run-Time Check Failure. The variable 'subs_mp_asub_$K' is being used without being defined

A: A short explanation could be: the attribute save says that the value of a variable must be preserved across different calls to the same subroutine/function. Otherwise normally when you return from a subroutine/function, "local" variables lose their values since the memory where those vars were stored is released. It is like static in C, if you know this language.


text:
Q: Permutation representation inner product Let $\rho : S_n \rightarrow \text{GL}(n, \mathbb{C})$ be the homomorphism mapping a permutation $g$ to its permutation matrix. Let $\chi(g) = \text{Trace}(\rho(g))$.
What is the value of $\langle \chi, \chi \rangle = \displaystyle \frac{1}{n!} \sum_{g \in S_n} \chi(g)^2$ ? Computing this expression for small $n$ yields $2$. Is this always true?

A: The trace of a permutation matrix is the number of fixed points of the corresponding permutation.  This is a special case of the identity proved in "An identy for fixed points of permutations" by Goldman, where the average of the $k^{th}$ powers of the number of fixed points is shown to be the $k^{th}$ Bell number $B_k$ when $k<n$.  Your case follows because $B_2=2$.

A: Much as I like Burnside's Lemma, induced (permutation) representations, and other parts of group theory, I can't resist pointing out an alternative argument that uses essentially no group theory but relies on the fact that expectation (of random variables) is linear.  Since $\chi(g)$ is the number of fixed-points of $g$, its square is the number of fixed ordered pairs $(x,y)$, where of course fixing a pair means fixing both its components.  So the $\langle\chi,\chi\rangle$ in the question is the average number of fixed pairs of a permutation $g$, in other words the expectation (with respect to the uniform probability measure on $S_n$) of the random variable "number of fixed pairs."  That random variable is the sum, over all pairs $(x,y)$, of the indicator variable $F_{x,y}$ whose value at any permutation $g$ is 1 or 0 according to whether $g$ fixes $x$ and $y$ or not.  So $\langle\chi,\chi\rangle$ is the sum, over all $x,y$,  of the expectations of these $F_{x,y}$, and these expectations are just the probabilities that a random permutation fixes $x$ and $y$.  For each of the $n$ pairs where $x=y$, that probability is $1/n$, so all these together contribute 1 to the sum.  For each of the remaining $n^2-n$ pairs, the probability is $(1/n)(1/(n-1))$ (namely, probability $1/n$ to fix $x$ and conditional probability $1/(n-1)$ to fix $y$ given that $x$ is fixed).  So these pairs also contribute 1 to the sum, for a total of 2.

A: Here's another proof.
If $G$ acts transitively on $X$, then the permutation representation of $G$ is induced from the permutation representation of the stabilizer $S$ of an arbitrary point. As a result, $\langle \chi , \chi \rangle$ counts the number of orbits of $S$ on $X$.
In your situation $G=S_n$ is acting transitively on $X=\{1,\ldots,n\}$. Let $S$ be the stabilizer of $n$; this is pretty much $S_{n-1} \subset S_n$, which has two orbits on $X$: $\{1,\ldots, n-1\}$ and $\{n\}$.

A: Alternatively, let $X=\{1,\dots,n\}$ and $A=\{(x,y,g)\in X\times X\times S_n:gx=x, gy=y\}$. The sum $\sum_g\chi(g)^2$ can be evaluated counting elements of $A$ in two different ways, as explained in W.R.Scott's Group theory, Thm. 10.1.6.

A: Another fact, of which this is a special case, well-known to (many) group theorists, is that if $G$ is a finite transitive permutation group, and $H$ is a point-stabilizer, then the squared-norm of the permutation character $1_{H}^{G}$ is the number of distinct $(H,H)$-double cosets in $G$,
which is the same as the number of orbits of $H$ on the points in the permutation
action.  This is a standard application of Mackey's formula for the restriction
to one subgroup of a character (or representation) induced from another subgroup
(this result can be found in standard texts such as Curtis and Reiner), after first applying
Frobenius reciprocity to conclude that  $\langle 1_{H}^{G}, 1_{H}^{G}\rangle$
is equal to $\langle (1_{H}^{G})_{H},1 \rangle$.

A: You are computing the inner product of $\chi$ with itself.
Since $\chi=\mathrm{triv}+\mathrm{std}$ as a $S_n$-module, with $\mathrm{triv}$ being the trivial reprsentation, and $\mathrm{std}$ its orthogonal complement, which is an irreducible $S_n$-module, and since the inner product is, well, an inner product and distinct irreducible characters are orthogonal, your $2$ follows from $$\langle\chi,\chi\rangle=\langle\mathrm{triv}+\mathrm{std},\mathrm{triv}+\mathrm{std}\rangle=\langle\mathrm{triv},\mathrm{triv}\rangle+\langle\mathrm{std},\mathrm{std}\rangle=1+1$$.

A: A small generalization.  Any doubly transitive action of a group $G$ on a set $X$ has the property that $\frac{1}{|G|} \sum_{g \in G} \text{Fix}(g)^2 = 2$.  This is because, by double transitivity, the diagonal action of $G$ on $X^2$ has precisely two orbits, the orbit where the first factor equals the second and the orbit where it doesn't, so the result follows by Burnside's lemma.  Similarly, any $k$-transitive action of a group $G$ on a set $X$ with $k < |X|$ has the property that $\frac{1}{|G|} \sum_{g \in G} \text{Fix}(g)^k = B_k$, since the orbits of the diagonal action of $G$ on $X^k$ can naturally be put into bijection with partitions of a $k$-element set.  For $k \ge |X|$ the sum evaluates to the number of partitions of a $k$-element set into at most $|X|$ parts (of course, the action can only be $k$-transitive for $k = |X|$ if $G$ is in fact the full group of permutations on $X$!).
The representation-theoretic upshot of all this is that the permutation representation corresponding to a doubly transitive group action always breaks down into the direct sum of one copy of the trivial representation and an irreducible representation.  This is an easy way to write down nice irreducible representations of groups like $PSL_2(\mathbb{F}_q)$, which has a triply transitive action on $\mathbb{P}^1(\mathbb{F}_q)$ (edit: when $q$ is even!)