text:
Q: Is it possible to generate token using ADAL.net library with out Azure secret Key through C#? From Azure function i am calling an end point of another Azure function(http trigger) under the same Azure subscription(same Azure Tenant ID).
So now I have "TenantID" and "ClientID" of the destination Azure function with me , but i don't have Secret Key of it. Is it possible to generate token with out a Secret key ?
   string authority = string.Format(CultureInfo.InvariantCulture, authorityUri, tenantId);

   AuthenticationContext authContext = new AuthenticationContext(authority);

   ClientCredential credential = new ClientCredential(clientId, "");

   var result = await authContext.AcquireTokenAsync(resourceUri, credential);

PS : From angular we can access this same API using ADAL library with out Secret Key.

A: If you do not have a signed-in user, your application must authenticate with either a secret or a certificate.
If you have a user who can sign in, then you can use e.g. authorization code flow to acquire tokens that allow you to call your API on behalf of the user.
But ultimately, either your app or the user (or both) has to authenticate to get a token.


text:
Q: Prepared Statements, MyISAM with 100 million records and Caching on MySQL I have 10 large read-only tables. I make a lot of queries that have the same format with different parameters, for example:
SELECT 'count' FROM table1 WHERE x='SOME VARIABLE';
SELECT 'count' FROM table1 WHERE x='SOME OTHER VARIABLE';
...
SELECT 'count' FROM table2 WHERE x='' AND y='';
SELECT 'count' FROM table2 WHERE x='' AND y='';
...
SELECT 'count' FROM table3 WHERE x='' AND y='' AND z='';

The variables used are different each query so I almost never execute the same query twice. Is it correct that query caching and row caching on the MySQL side would be wasteful and they should be disabled? Table caching seems like it would be a good thing.
On the client side, I am using prepared statements which I assume is good. If I enable Prepared statement caching (via Slick) though won't that hurt my performance since the parameters are so variable? Is there anything else I can do to optimize my performance?
Should auto-commit be off since I'm only doing selects and will never need to rollback?

A: Given that you are using the MYISAM engine and have tables which have hundreds of millions of active rows, I would take care less of how I query the cache (due to your low complexity, this is most likely the least problem), but more focus on the proper organization of the data within the database:

*

*Prepared Statements are totally ok. It may be helpful to not prepare the statement over and over again.  Instead, just reuse the existing prepared statement (some environments even allow to store prepared statements on the client side) with a new set of parameter values. However, this mainly only saves time, which is being used in the query cache. As the complexity of your query is quite low, it can be assumed that this won't be the biggest time consumer.

*Key Caching (also called Key Buffering), however, is - as the name already suggests - key for your game! Most DB configurations of MySQL suffer greatly from wrong values in that area, as the buffers are way too small. In a nutshell, key caching makes sure that the references to the data (for instance in your indices) can be accessed in main memory. If they are not in memory, they need to be retrieved from the disk, which is slow. To see if your key cache is efficient, you should watch the key hit ratio, when your system is under load. Details about that is greatly explained at https://dba.stackexchange.com/questions/58182/tuning-key-reads-in-mysql.

*If the caches become large or are being displaced frequently due to the usage of other tables, it may be helpful to create own key caches for your tables. For details, see https://dev.mysql.com/doc/refman/5.5/en/cache-index.html

*If you always access large portions of your table via the same attributes, it may make sense to change the ordering of the data storage on the disk by using ALTER TABLE ... ORDER BY expr1, expr2, .... For details on this approach see also https://dev.mysql.com/doc/refman/5.5/en/optimizing-queries-myisam.html

*Avoid using variable-length columns, such as VARCHAR, BLOB or TEXT. They might help to save some space, but especially comparing their values can become time-consuming. Please note, however, that already one single column of such a type will MySQL make switch to Dynamic column mode.

*Run ANALYZE TABLE after huge data changes to keep the statistics up to date. If you have deleted huge areas, it might help to OPTIMIZE TABLE, helping to make sure that there are no large gaps around which need to be skipped when reading.

*Use INSERT DELAYED to write changes asynchronously, if you do not need the reply. This will greatly improve your performance, if there are other SELECT statements around at the same point in time.

*Alternatively, if you need the reply, you may use INSERT LOW_PRIORITY. Then the execution of the concurrent SELECTs are preferred compared to your INSERT. This may help to ease the pain of the fact a little, that MyISAM only supports table-level locking.

*You may try to provide Index Hints to your queries, especially if there are multiple indices on your table which are overlapping each other. You should try to use that index which has the smallest width, but still covers the most attributes.
However, please note that in your case the impact must be quite small: You are not ordering/grouping or joining, so the query optimizer should already be very good at finding the best one. Simply check by using EXPLAIN on your SELECT statement to see, if the choice of the index used is reasonable.

In short, Prepared Statements are totally ok. Key Caching is key - and there are some other things you can do to help MySQL getting along with the whole bulk of data.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to resolve the multiple records using find in Graphql with Mongoose and ES6 promises I recently started working with Graphql when find multiple records with a condition(like find({'author.id':id})) from the database i am getting the response NULL.In console all records are getting printed, but when resolve the response shows null.
my code like:
 export default {
    eventByUserId: {
        type: new GraphQLList(EventType),
        args: {
          id: {
            type: GraphQLID
          }
        },
        resolve: (root, {id}) => {
      return new Promise((resolve, reject) => {
        Event.find({'author.id': id}).exec((err, res) => {
        console.log(res);
         err ? reject(err) : resolve(res);
        });
      });
    };
   }
  };

passing Query like:
  {
  eventByUserId
    (
      id:"55dd69e702a488b81c4dd8ed"

     )
     {
        title
        description
        start
        media{url}
        location{state,city}
        author{id, name}
        comments{text,created,author{id,name}}
        posts{url,mediaType,imageUrl,note,author{id,name}}
        _id
      }
    }

response like:
{
    "data": {
        "eventByUserId": {
            "title": null,
            "description": null,
            "start": null,
            "media": null,
            "location": null,
            "author": null,
            "comments": null,
            "posts": null,
            "_id": null
        }
    }
}

this is my EventType:
export default new GraphQLObjectType({
  name: 'Event',
  description: 'A event',
  fields: () => ({
       _id: {
      type: GraphQLString,
      description: 'The id of the event.',
    },
    title: {
      type: GraphQLString,
      description: 'The title of the event.',
    },
     description: {
      type: GraphQLString,
      description: 'The description of the event.',
    },
    start: {
      type: GraphQLString,
      description: 'The start date of the event.',
    },
    media:{
      type:new GraphQLList(MediaType),
      description:'List of media.',
    },
    location:{
      type:new GraphQLList(LocationType),
      description:' The list of location. ',
    },
    comments:{
      type:new GraphQLList(CommentType),
      description:' The list of Comments. ',
    },
    posts:{
      type:new GraphQLList(PostType),
      description:' The list of Posts. ',
    },
    created: {
      type: GraphQLString,
      description: 'The created at.',
    },
    author:{
       type: AuthorType,
      description: 'The author for the event.',
    }
  })
});

A: In this situation we are trying to resolve a list of data, so in eventByUserId we have to give GraphQLList as type like type:new GraphQLList(EventType) in the place of type:EventType. I am also editing my post. Thank you for your support..


text:
Q: How to get the value of a certain key of a nested JSON object (2nd level and in general)? I have a nested JSON Object called "data".
console.log(Object.values(data['Meta']['Symbol']));

That gives me every single letter/character of the value:
Array(3) [ "S", "A", "P" ]

What I want, is the whole String: "SAP"
Where is the mistake?
Things I have tried:
That gives me the whole array (including "SAP") but I just want the String i.e. value "SAP":
console.log(Object.values(data['Meta']

That gives me an empty array (of three elements):
console.log(Object.keys(data['Meta']['Symbol']));

Information that I was looking for on the internet, doesn't adress this issue.
Structure of the JSON object:
{
    "Meta": {
        "Symbol": "SAP"
    }
}

A: Firstly, this is not JSON; JSON is a string. Next, if you want to turn an array into a string, use array.join("");
console.log(data['Meta']['Symbol'].join(""));

A: If the JSON object is
{
    "Meta": {
       "Symbol": "SAP"
    }
}

And you import it with let data = JSON.parse("MY JSON")
Then it's just console.log(data.Meta.Symbol)

A: Why
const data = { Meta: { Symbol: 'SAP' } };

/**
 * 1. String is an object;
 * 2. Using the Objects.prototype.values method will return an array of all the values (e.g. All the characters in the String.);
 *
 * MDN documentation
 * ------------------------------------------------------
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values
 * ------------------------------------------------------
 */
console.log(Object.values(data['Meta']['Symbol']));

Output
[ 'S', 'A', 'P' ]

How
const data = { Meta: { Symbol: 'SAP' } };

/**
 * To retrieve the value of the string, you must access it using the dot notation or bracket notation.
 *
 * Dot notation: data.Meta.Symbol
 * Bracket notation: data['Meta']['Symbol']
 *
 * MDN documentation
 * ------------------------------------------------------
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors
 * ------------------------------------------------------
 */
console.log(data['Meta']['Symbol']);

Output
SAP


text:
Q: In Python, why does .append give different results than using +? I want to implement a very simple tree data structure in Python.
I want to make it so that everytime I add a new node and I specify its parent, then it is automatically added to the children attribute of its parent.
I have two different ways to do it, one works and one doesn't but I don't understand why.
class Node():
    def __init__(self, value, parent = None, children = []):
        self.value = value          #This is for us to see the name
        self.parent = parent        #Parent node
        self.children = children    #List of child nodes

        #Set this Node as a children of its own parent
        if not parent == None:
            #self.parent.children.append(self)  <--- wrong code
            self.parent.children = self.parent.children + [self]

    def __repr__(self):
        return str(self.value)

tree    = Node("tree")
branch1 = Node("branch1", parent = tree)
branch2 = Node("branch2", parent = tree)
leaf    = Node("leaf", parent = branch1)

Here is what I get with the code as is and what I would get if I replace the last line of __init__ with the commentated line.
print(tree.children)
#[branch1, branch2]        <--- expected
#[branch1, branch2, leaf]  <--- with wrong code

print(branch1.children)
#[leaf]                    <--- expected
#[branch1, branch2, leaf]  <--- with wrong code

Using the .append method adds the node not only to the list children of its parent but to everybody. Even if I define a new Node("other") completely detached from the others. Why is that?

A: The problem is in the use of mutable default value:
def __init__(self, value, parent = None, children = []):

The empty list [] gets created only once, when the function is defined, and all invocations share the same list! This is why append to one list of children modifies all of them - because they all are one and the same list object. When you use + to append to the list, you work around the above bug because you re-create the list every time, thus unsharing the children objects.
The correct solution is to replace children=[] with something like:
def __init__(self, value, parent=None, children=None):
    if children is None:
        children = []

That will guarantee the creation of a new list for children, and then append and + should have the same result.


text:
Q: What is the correct casing convention for C# local and instance variables? There are a lot of former Java developers at my company who use camel casing in C# for both of these. What casing is most widely accepted / used for C#?

A: Here is the Microsoft Conventions

Here is the full MSDN conventions
And here are the internal guidelines via Brad Abrams (covers just about everything, not just the highlights)

A: ...and this one...
Internal Coding Guidelines (Design Guidelines, Managed code and the .NET Framework)
I like this one more, there is a clear-cut paragraph on naming/casing. It's only a tad more restrictive.
EDIT: this should be the new link, archived - Internal Coding Guidelines

A: The most common casing is camelCasing.
The Microsoft .NET Framework Reference Guidelines, require method parameters to be in camelCasing, since these are like local variables, I would treat them the same.

A: Exactly the same as in Java:
int someVeryLongLocalVariableName;

Official soure:

Camel Casing
The first letter of an identifier is lowercase and the first letter of each subsequent concatenated word is capitalized.
When an identifier consists of multiple words, do not use separators, such as underscores ("_") or hyphens ("-"), between words. Instead, use casing to indicate the beginning of each word.
The following guidelines provide the general rules for identifiers.
Do use Pascal casing for all public member, type, and namespace names consisting of multiple words.
Note that this rule does not apply to instance fields. For reasons that are detailed in the Member Design Guidelines, you should not use public instance fields.
Do use camel casing for parameter names.
The following table summarizes the capitalization rules for identifiers and provides examples for the different types of identifiers.


text:
Q:  inside link () tag I want to make a div click-able and but inside this
 i have another
 which also should be click-able or linked.
HTML

CSS
.box{
    float:left;
    width:100px;
    height:100px;
}
.plus{
    float:left;
    width:30px;
    height:30px;
}

Can i make both
s to link and for different links?
and Is this proper way use div inside a href ?

A: This is a classic case of divitis - you don't need a div to be clickable, just give the  tag a class. Then edit the CSS of the class to display:block, and define a height and width like a lot of other answers have mentioned.
The  tag works perfectly well on its own, so you don't need an extra level of mark-up on the page.

A: As of HTML5 it is OK to wrap  elements around a
 (or any other block elements):

The a element may be wrapped around entire paragraphs, lists, tables, and so forth, even entire sections, so long as there is no interactive content within (e.g. buttons or other links).

Just have to make sure you don't put an  within your  ( or a <button>).

A: No, the link assigned to the containing  will be assigned to every elements inside it.
And, this is not the proper way. You can make a  behave like a
.
An Example [Demo]
CSS
a.divlink {
     display:block;
     width:500px;
     height:500px;
     float:left;
}

HTML

         The text or elements inside the elements

         Another text or element

A: Nesting of 'a' will not be possible.
However if you badly want to keep the structure and still make it work like the way you want,
then override the anchor tag click in javascript /jquery .
so you can have 2 event listeners for the two and control them accordingly.

A: I think you should do it the other way round.
Define your Divs and have your a href within each Div, pointing to different links

A: I would just format two different a-tags with a { display: block; height: 15px; width: 40px; } . This way you don't even need the div-tags...


text:
Q: What is TFDDatSRow? I use Delphi 10.3. I try to make a memory database, append data to it and find data in it.
I wrote the following code referring other's and it works well.
procedure TForm1.DataAppendFind;
var
  _FieldDef: TFieldDef;
  _FDDatsRow: TFDDatSRow;
  i: Integer;
begin
  _FieldDef := FDMemTable1.FieldDefs.AddFieldDef;

  _FieldDef.Name := 'field1';
  _FieldDef.DataType := ftInteger;

  _FieldDef := FDMemTable1.FieldDefs.AddFieldDef;

  _FieldDef.Name :='field2';
  _FieldDef.DataType := ftString;
  _FieldDef.Size := 10;

  FDMemTable1.CreateDataSet;

  FDMemTable1.Append;

  FDMemTable1.FieldValues['field1'] := 1;
  FDMemTable1.FieldValues['field2'] := 'one';

  FDMemTable1.Append;

  FDMemTable1.FieldValues['field1'] := 2;
  FDMemTable1.FieldValues['field2'] := 'two';

  FDMemTable1.First;

  for i := 0 to FDMemTable1.RecordCount - 1 do
  begin
    _FDDatsRow := FDMemTable1.GetRow;

    if _FDDatsRow.Values['field1'] = 2 then
    begin
      Caption := _FDDatsRow.ValueS['field2'];
    end;

    FDMemTable1.Next;
  end;
end;

I can't understand TFDDatSRow that I tried to search it through Delphi references and google for it. But there is no clear document about that. I can guess it is similar with a row but is not a row because it has a long and complex name which is not just a tROW.
What is TFDDatSRow, why there is no reference about it and where can I get the proper information about that? And lastly is the code above correct?

A: Yes, your code works correctly.  I confess I had not come across TFDDatSRow
before your q, but having looked at it, it's pretty obvious what it is for.
FireDAC's dataset components all descend from TDataSet, and therefore comply
with its way of modelling dataset operations, which is to say that while a dataset
is open, it has a logical cursor which is "over" exactly one record in the dataset
and it is that record, the "active" one in Delphi's terms, on which operations like Edit, Post, FieldByName,
etc take place.  This works fine but makes some operations impossible, such as working
on two records simulataneously, e.g. when you want to exchange values between two
different records, because they can't both be the active record of the dataset at the same time.
I said it's pretty obvious what TFDDatSRow is for and one thing is to allow
exactly that kind of concurrent access to 2 or more records possible.
For example, this code
  FDMemTable1.First;
  FDDatsRow1 := FDMemTable1.GetRow;
  FDMemTable1.Next;
  FDDatsRow2 := FDMemTable1.GetRow;

  FDDatSRow1.BeginEdit;
  FDDatSRow1.Values['Field2'] := FDDatSRow2.Values['Field2'];
  FDDatSRow1.EndEdit(False);

enables data to be transferred from the second row to the first in a way that
wouldn't be possible without TFDDatSRow.
Why isn't it documented?  Don't know, ask EMBA.
How did I find out its methods?  Simple, I declared a variable
 var FDDatSRow1 : TFDDatSRow;

and then typed
  FDDatSRow1.

and the IDE's code completion popped them up.
Also, selecting TFDDatSRow and doing Ctrl-Click takes me to its declaration
in the FireDac.DatS unit.  Looking in there, FireDAC's author obviously
hand in mind a lot more than is shown in my example.


text:
Q: Connection times out when I add ssl I am trying to add ssl to my website using this tutorial (https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-14-04). The browser is redirected to https://www.example.com but then it times out. I've looked at similar questions on here with no luck. Is there anything I'm missing? Please see my nginx config below (actual domain name removed):
server {
        listen 80;
        server_name example.com www.example.com;
        return 301 https://www.example.com$request_uri;
       }

server {
        listen 443;
        ssl on;

        root /var/www/example/public;
        index index.php index.html index.htm;

        server_name www.example.com;

        ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem;

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers on;
        ssl_dhparam /etc/ssl/certs/dhparam.pem;
        ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA';
        ssl_session_timeout 1d;
        ssl_session_cache shared:SSL:50m;
        ssl_stapling on;
        ssl_stapling_verify on;
        add_header Strict-Transport-Security max-age=15768000;

        location / {
                try_files $uri $uri/ /index.php?$query_string;
        }

        location /blog/ {
                try_files $uri $uri/ /blog/index.php?$query_string;
        }

    location ~ \.php$ {
        try_files $uri /index.php =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

A: Your server is listening for http on port 443, not https. Change your listen line to
listen 443 ssl;

If you build Nginx to enable http2 it might look like this
listen 443 ssl http2;

You can compare your config to the ones I've posted on this page, which all work. That same tutorial also shows you how to build Nginx with http2 enabled - it's surprisingly easy.

A: Change server-name and redirect parameters from example to your real site name. Then restart nginx
# sudo service nginx restart

And check that ngnix service is running
# sudo service nginx status


text:
Q: STM32 write signed short into EEPROM I use STM32F0 mcu with emulated EEPROM. The EEPROM takes data as EE_WriteVariable(uint16_t VirtAddress, uint16_t Data) and returns them as EE_ReadVariable(uint16_t VirtAddress, uint16_t* Data) but my data are int16_t. So my question is, how do I write and read signed short?

A: Unfortunately the C language is being daft when it comes to things like hardware-related programming, such as EEPROM emulation. Therefore, the only reliable solution you can use is this:
uint16_t u16;
EE_ReadVariable(VirtAddress, &u16);
int16_t i16;
i16 = (int16_t)u16;

or alternatively:
memcpy(&i16, &u16, 2);

Anything else is unsafe and dangerous. In particular, you cannot do this:
EE_ReadVariable(VirtAddress, (uint16_t*)&i16); // BAD

Nor can you do i16 = *(int16_t*)&u16; // BAD.
More information about why, can be found here: What is the strict aliasing rule?

A: As per the application note The data is stored as 16-bit words in memory, so it's uint16_t. That's the underlying data type that anything your store in emulated EEPROM must be. Regardless of what you store, it has to have this type.
int16_t is guaranteed to have the same size as uint16_t. Use an intermediary variable of type uint16_t.


text:
Q: Datetime Format Convert C# Here is my date time format displayed
Dr["DATE"]       =========>     Jun 27 2014 9:06PM
I want it to display like this one =========> 27.06.2014
Here is my code:
ltrlNotlar.Text = Dr["DATE"].ToString()

How to change first format to the second one?
Thankss

A: use DateTime to do the conversion for you
var dt = DateTime.Parse(Dr["DATE"].ToString());

ltrlNotlar.Text = dt.ToString("dd.MM.yyyy");

A: If Dr is a DataRow, you can this
ltrlNotlar.Text = dr.Field<DateTime>("DATE").ToString("dd.MM.yyyy");

I like using .Field because it does the casting for you. However this only works if the sql column is a Date or DateTime (or possibly DateTimeOffset). If you are storing your date as a string in the database, this won't work.
If the sql column DATE is nullable, make sure to change the generic argument to DateTime?.

A: you could also use something like this:
Convert.ToDateTime(SomeDateTime).ToString("MM.dd.yyyy");


text:
Q: python 2.7: hex netmask to dotted decimal output of ifconfig command on aix gives the netmask in hex.
>>> import subprocess
>>> import os
>>> import re
>>> import socket
>>> ifconfig_output = subprocess.check_output(['/usr/sbin/ifconfig', '-a']).decode()
>>> result = re.findall(r'[\s]+inet ([\d\.]+) netmask ([\w.]+) broadcast ([\d\.]+)', ifconfig_output, re.S | re.M)
>>> print(result)
[(u'172.17.14.50', u'0xfffff800', u'172.17.15.255'), (u'172.16.156.50', u'0xffffc000', u'172.16.191.255'), (u'172.16.12.10', u'0xfffffe00', u'172.16.13.255'), (u'127.0.0.1', u'0xff000000', u'127.255.255.255')]

i tried this but this does not let me use the 0x prefix.
>>> s = '0xffffc000'
>>> print '.'.join(str(int(i, 16)) for i in ([s[i:i+2] for i in range(0, len(s), 2)]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <genexpr>
ValueError: invalid literal for int() with base 16: '0x'
>>> s = 'ffffc000'
>>> print '.'.join(str(int(i, 16)) for i in ([s[i:i+2] for i in range(0, len(s), 2)]))
255.255.192.0
>>>

so how to convert the netmask to dotted decimal notation only with standard lib (no modules)? remember that this is python 2.7.

A: One method is bit-shifting and mask:
s = int('0xffffc000', 16)
mask = 0x000000ff

print(".".join(map(str, [mask & (s >> 24), mask & (s >> 16), mask & (s >> 8), mask & s])))

Output:
255.255.192.0

EDIT: Using your method, just start with 2 in range() instead of 0
range(2, len(s), 2)


text:
Q: Using multicore Mac in R through console This is my first question ever in StackOverflow, so please excuse me if I do any mistake, or if my question is too basic.
I am performing clustering with R version 3.3.0 "Supposedly Educational" and I would like to use multicore in my MacBook Pro. I have read throughout many articles regarding calling multicore using parallel package, as well as %dopar%, but I understand that:
1st. This is for script writing instead of console (I use workspace directly from console).
2nd. Actually, I would love that every action performed in R is made using the two cores of my laptop, from importing csv files (with 24 variables and 300000 rows), to calculating for loops, etc. If that's possible, of course. That would save me some time, I think; I am not a computing expert.
Thank you all for reading.


text:
Q: Unclear Eigen example about resizing matrix base class I'm working with Eigen library and trying to understand what authors wanted to say about resizing base class within template.
#include <iostream>
#include <Eigen/Dense>

using namespace std;
using namespace Eigen;

template <typename Derived, typename OtherDerived>
void cov(const MatrixBase<Derived>& x, const MatrixBase<Derived>& y, MatrixBase<OtherDerived> const & C_)
{
  typedef typename Derived::Scalar Scalar;
  typedef typename internal::plain_row_type<Derived>::type RowVectorType;

  const Scalar num_observations = static_cast<Scalar>(x.rows());

  const RowVectorType x_mean = x.colwise().sum() / num_observations;
  const RowVectorType y_mean = y.colwise().sum() / num_observations;

  MatrixBase<OtherDerived>& C = const_cast< MatrixBase<OtherDerived>& >(C_);

  C.derived().resize(x.cols(),x.cols()); // resize the derived object
  C = (x.rowwise() - x_mean).transpose() * (y.rowwise() - y_mean) / num_observations;
}

int main()
{
  MatrixXf x = MatrixXf::Random(100,3);
  MatrixXf y = MatrixXf::Random(100,3);
  MatrixXf C;
  cov(x, y, C);
  cout << C << endl;

  return 0;
}

As I understand the goal is to resize the base class and to do that they use MatrixBase<OtherDerived> const & C_ which is then const-casted const_cast<> to a derived class and they resize this derived class...
I wondered what would be if instead MatrixBase<OtherDerived> const & C_ I simply write MatrixBase<OtherDerived>& C and comment the const_cast<> line? Apparently the example still works and you can check that using online compiler
So why authors have dedicated a chapter for that task if there is a simpler solution? Probably I'm missing something?


text:
Q: How can I change turtle images in order every time I press the same button in Python? I want to write a program that changes the turtle image in order each time I press the 'n' key.
It should first start with the 'classic' shape, and every time the 'n' key is pressed, change the shape to 'circle', 'arrow', 'turtle' and then loop back to 'classic'.
import turtle
canvas = turtle . Screen ()
t = turtle . Turtle ()

def changeTurtle () :
    for n in range (1, 5) :
        if n == 1 :
            t . shape ('circle')
        elif n == 2 :
            t . shape ('arrow')
        elif n == 3 :
            t . shape ('turtle')
        elif n == 4 :
            t . shape ('classic')

t . shape ('classic') # first turtle 'classic' shape
canvas . onkey (changeTurtle, 'n') # press 'n'key

canvas . listen ()
turtle . mainloop ()

It should have changed once when I pressed the 'n' key. The problem is, it is changing too quickly.

A: You're going through all possible values of n at once with the for loop. What you need to do instead is save a value of n outside the function, and change it every time the function is called:
n = 1
def changeTurtle():
    global n
    n = (n % 4) + 1  # cycle through 1, 2, 3, 4, 1, 2, 3, 4, ...
    if n == 1:
        t.shape('circle')
    elif n == 2:
        t.shape('arrow')
    elif n == 3:
        t.shape('turtle')
    else:
        t.shape('classic')

A: Here's how I'd over-engineer this problem (and eliminate the need for a global statement):
from turtle import Screen, Turtle

def changeTurtle():
    index = shapes.index(turtle.shape()) + 1
    shape = shapes[index % len(shapes)]

    turtle.shape(shape)
    screen.title(shape)

turtle = Turtle()
turtle.shapesize(3)
turtle.shape('classic')  # first turtle 'classic' shape

screen = Screen()
screen.title(turtle.shape())
shapes = screen.getshapes()

screen.onkey(changeTurtle, 'n')  # press 'n' key

screen.listen()
screen.mainloop()

A: An alternative to your function would be to have an infinite iterator (like itertools.cycle) loaded with all the shapes you want to cycle through. When you want the next shape, your program simply asks for it, changes the turtle, and then continues with anything else it was doing before. The following program demonstrates how this can be done:
import itertools
import turtle

def main():
    canvas = turtle.Screen()
    t = turtle.Turtle()
    # noinspection PyProtectedMember
    shapes = itertools.cycle(sorted(canvas._shapes.keys()))
    t.shape(next(shapes))
    canvas.onkey(lambda: t.shape(next(shapes)), 'n')
    canvas.listen()
    canvas.mainloop()

if __name__ == '__main__':
    main()


text:
Q: Computing length of polygon segments using geopandas I have this little issue I am trying to solve and I have looked everywhere for an answer. It seems odd that I cannot find it, but it might just be me.
So, I have this dataframe
df=
id     x_zone     y_zone
0  A1  65.422080  48.147850
1  A1  46.635708  51.165745
2  A1  46.597984  47.657444
3  A1  68.477700  44.073700
4  A3  46.635708  54.108190
5  A3  46.635708  51.844770
6  A3  63.309560  48.826878
7  A3  62.215572  54.108190

that I convert into a geopandas dataframe:
df_geometry = gpd.GeoDataFrame(geometry=df.groupby('id').apply(
    lambda g: Polygon(gpd.points_from_xy(g['x_zone'], g['y_zone']))))
df_geometry = df_geometry.reset_index()
print(df_geometry)

which returns:

id                                        geometry
A1  POLYGON ((65.42208 48.14785, 46.63571 51.16575...
A3  POLYGON ((46.63571 54.10819, 46.63571 51.84477...

and for which I can compute the area and the perimeter:
df_geometry["area"] = df_geometry['geometry'].area
df_geometry["perimeter"] = df_geometry['geometry'].length

which gives:
id                                           geometry       area  perimeter
0  A1  POLYGON ((65.42208 48.14785, 46.63571 51.16575...  72.106390  49.799695
1  A3  POLYGON ((46.63571 54.10819, 46.63571 51.84477...  60.011026  40.181476

Now, to the core of my problem: IF one can calculate the length, surely the length of each segment of the polygons is being calculated. How can I retrieve this?
I understand that for very complicated polygons (e.g. country maps, this might be problematics to store). Anyone with an idea?

A: You can use df_geometry.geometry.exterior[0].xy[0] to get all x coordinates and df_geometry.geometry.exterior[0].xy[1] to get y coordinates as tuple and then calculate distance using Euclidean distance.


text:
Q: Is there any way to upgrade from a German Vista Ultimate to English Windows 7 without a clean install? I guess the subject says it...
I have a German version of Vista Ultimate installed and would like to upgrade to Windows 7 Ultimate, but the German version of Windows 7 is not out yet. A clean install is out of the question.
Is there still a way (in other words, hack) I can upgrade without waiting until October?

A: There will not be a different version of Windows 7 Ultimate in German.
The reason why I'm saying that is that Windows 7 Ultimate (as well as Windows Vista Ultimate) comes with the ability to switch the language after the installation using language packs. All you have to do is install the English distribution and then install the language pack with the language of your choice (a German language back is available already for Windows 7). File wise, both the English version and the German version has the exact same file signatures.
That being said, you can upgrade to Windows 7 using the normal upgrade route whether your Windows Vista is in English or not since your Windows Vista Ultimate in German is just the English version with the language pack installed. Before upgrading, open the Change display language item in the Control Panel and switch your display language back to English. Then switch to the Administrative tab, and use the  Copy Settings button to copy the language setting to the SYSTEM and DEFAULT accounts. Windows 7 will then proceed to upgrade without complaining.
You might need to install the language pack after, which is on a separate DVD marked as Windows 7 Language Pack (x86) - DVD (Multiple Languages) (or Windows 7 Language Pack (x64) - DVD (Multiple Languages) for 64-bit) in your MSDN Downloads.
Edit: After verification, MSDN also provides a DVD of Windows 7 Ultimate with the German language pack already installed, marked as Windows 7 Ultimate (x86) - DVD (German) (or Windows 7 Ultimate (x64) - DVD (German) for 64-bit). Then again, the only difference between the German and the English version is the fact that the German download has the language pack slipstreamed in the disk.

A: I'm not sure if the German version is supported, but Scott Hanselman wrote an excellent blog on upgrading XP to Windows 7 that might work for Vista:
http://www.hanselman.com/blog/StepByStepHowToUpgradeFromWindowsXPToWindows7.aspx


text:
Q: VueJS + VeeValidator + Multiple fields Versions:

*

*VueJs: 2.2.2

*Vee-Validate: 2.0.0-beta.25

Description:
I'm wondering if there's a way to have a unique validator for multiple fields?
Typically, an Address form with 1 input fot the street, 1 for the number and 1 for the city
I want to make a validation on the combination of all the elements.
I've read the documentation but I can't find an exemple that could help me for that.

A: You could apply a custom validator to a custom component that contained all the fields you want to validate together. For example, you could build a location component (using location instead of address because address is an HTML5 element, and you cannot name a Vue component the same as an existing HTML element).
Vue.component("location", {
  props:["value"],
  template: "#location-template",
  data(){
    return {
      location: this.value
    }
  },
  methods:{
    update(){
      this.$emit('input', Object.assign({}, this.location))
    }
  },
})

Then you can build a validator for that component.
const locationValidator = {
  currentLocation: null,
  getMessage(field, args) {
    if (!this.currentLocation.street)
      return "Location requires a street";
    if (!this.currentLocation.street_number)
      return "Location requires a street_number";
    if (!this.currentLocation.city)
      return "Location requires a city";
  },
  validate(location, args) {
    this.currentLocation = location;

    if (!location.street || !location.street_number || !location.city)
      return false;

    return true
  }
};

Finally, you can pull that together in your Vue.
new Vue({
  el:"#app",
  data:{
    loc: {}
  },
  created(){
    this.$validator.extend("location", locationValidator)
  }
})

And your Vue template
{{ errors.first('location') }}
<location v-validate="'location'" v-model="loc" data-vv-name="location"></location>

Here is an example.


text:
Q: Skype segmentation fault ubuntu 13.04 Skype (from depots and website) Crashes with :

Erreur de segmentation (core dumped)
  Tried to reinstall, no .skype in my /home

Maybe a clue : https://bbs.archlinux.org/viewtopic.php?id=154571
I'll make some more tests When I have some time.
Thx


text:
Q: GraphQL schema equivalent of this Json? I'm newbie to GraphQL, and was wondering if someone could help me figure out what is the equivalent of below JSON into GraphQL schema:
[
 {
   "id": "1",
   "name": "A",
   "fldDef": [
    {
      "name": "f1",
      "type": "str",
      "opt": false
    },
    {
      "name": "f2",
      "type": "bool"
    }]
 },
 {
    "id": "2",
    "name": "B",
    "fldDef": [
     {
       "name": "f3",
       "type": "str",
       "opt": true
     },
     {
       "name": "f4",
       "type": "str",
       "opt": true
     }]
  }
]

So far I managed to map above response to below object:
  public class FldDef {

     private String name, type;
     private boolean opt;
     // getters & setters
 }

 public class Product {

    private String id, name;
    private Map<String, FldDef> fldDef;

   // getters & setters

 }

Then my schema looks like below, but the problem I'm having is as a part of Product object, I've a Map which I would like to get the schema right for it, but I'm having difficulty getting the schema right!
type FldDef {
   name: String!
   type: String!
   opt: Boolean!
}

type Product {
   id: String!
   name: String!
   fldDef: FldDef! // now here I don't know what is the syntax for representing MAP, do you know how to achieve this?
 }

I get below exception:
Causedby:com.coxautodev.graphql.tools.TypeClassMatcher$RawClassRequiredForGraphQLMappingException: Type java.util.Map<java.lang.String, com.grapql.research.domain.FldDef> cannot be mapped to a GraphQL type!  Since GraphQL-Java deals with erased types at runtime, only non-parameterized classes can represent a GraphQL type.  This allows for reverse-lookup by java class in interfaces and union types.
Note: I'm working with Java eco-system (graphql-java)

A: giving you a schema from your JSON is not really possible because a schema contains much more information than just simply the shape of your data. I think the best for you would be to learn the basics of GraphQL, designing simple schemas is then very easy and fun! Maybe start with the learning section on graphql.org. They have a section about the schema. Basically you build your schema from scalars (aka primitives) and object types. All types can additionally be wrapped in the non-nullable type and/or of the list type. GraphQL was designed for clients. The easiest way of understanding GraphQL is making some queries against an existing API. Launchpad has a lot of examples that you can use (and modify when you know some JavaScript).

A: You can try some changes as below:
Schema definition:
type FldDef {
   name: String!
   type: String!
   opt: Boolean!
}

type Product {
   id: String!
   name: String!
   fldDef: [FldDef]! // make it as Collection of FldDef
 }

Java Class:
public class FldDef {

    private String name;
    private String type;
    private boolean opt;
    // getters & setters
}

public class Product {

    private String id;
    private String name;
    private List<FldDef> fldDef; // Change to List of FldDef
    // getters & setters
}

Hope it can help.


text:
Q: Collision of two balls in wpf and getting the paths of colliding balls This question is regarding WPF.
I have two balls, one static and the other is moving towards the static ball. On collision the balls would move in the direction that would be decided by the collision that at which angle they would collide and move accordingly.
My question is basically for suggestions for what is the easiest and the most effective way of colliding the objects in WPF and after collision giving them a path to move accordingly. Apart from deceleration etc, what should be the best strategy that should be applied to DETECT collision and GIVE NEW PATHS TO THE BALLS AFTER COLLISION.

A: I would calculate the distance (pythagoras) between them, if the distance is smaller than the two radius added, a collision occurs.
Check here for the angle between the points:
Math Calculation to retrieve angle between two points?
You could check this one:
Ball to Ball Collision - Detection and Handling

A: Simply figure out the distance of the centers of the 2 balls.
if (distance(ball1.Center, ball2.Center) <= ball1.Radius + ball2.Radius)
{
    // collision
}

For the distance use this:
double x = ball1.Center.X - ball2.Center.X;
double y = ball1.Center.Y - ball2.Center.Y;
double distance = Math.sqrt(x*x + y*y); // pythagoras

For calculating the new directions you'll need some more math. Have a look for a geometrics library like it is delivered with XNA. Try googeling your question again and use XNA in the search instead of WPF - this will solve your problem, i guess.


text:
Q: JsDocs: How do I use `@type` on class methods I was refactoring some code to use a class, rather than a static object.  And I discovered that all my jsDocs break.
I would like to label Class Methods with types the same way that I label Functions inside Objects.  Because it's rather prone to error to copy the same 6-line block to the top of each method, rather than 1-line.  Almost all the methods/functions in this class have the same signature.  I do not know how to make it reuse the one @type decorator.
import { Request, Response, Handler } from "express";

const WorkingController = {
  /**
   *
   * @param {Request} request
   * @param {Response} response
   * @param {Handler} next
   */
  async getAll(request, response, next) {
    // intellisense works
  },

  /**@type {Handler}*/
  async get(request, response, next) {
    // intellisense works
    // and it's much slimmer
  }
}

class ControllerClass {
  /**@type {Handler}*/
  async getAll(request, response, next) {
    // !!!no intellisense!!!
  }

  /**
   *
   * @param {Request} request
   * @param {Response} response
   * @param {Handler} next
   */
  async get(request, response, next) {
    // intellisense works
  }

For reference, I'm using vsCode version 1.47.1, without any jsdoc-specific extensions.


text:
Q: how to combine two columns to one column like a map in hive? In hive I have two columns in a table:
user_id    product_id    score
1          1, 2, 3       0.7, 0.2, 0.1
2          2, 3, 1       0.5, 0.25, 0.25

The type of product_id and score are both string. Now I wish to generate a new column which is combined by product_id and score like this:
user_id    product_score
1          1:0.7, 2:0.2, 3:0.1
2          2:0.5, 3:0.25, 1:0.25

In the new table, the column product_score is like a map, the product_id is the key and the score is the value, but it is actually still a string. The product_id and score is connected by ':'.  The different product_ids are connected by ',' and oredered by the initial order in product_id in initial table. How can I achieve this?

A: Use split() to get arrays, map() to convert to map
select user_id,
       map(product_id[0], score[0],
           product_id[1], score[1],
           product_id[2], score[2]
       ) as product_score

(
select user_id, split(product_id,',') as product_id, split(score,',') as score
  from ...
)s;

A: Solved - merge two arrays columns like key and value map with order.
Approach - Explode array with posexplode method and get equal pos value from multiple columns
SQL Query -
with rowidcol as
(
   select user_id, split(product_id, ',') prod_arr, split(score, ',') score_arr, row_number() over() as row_id
   from prod
),
coltorows as
(
   select row_id, user_id, prod_arr[prd_index] product, score_arr[score_index] score, prd_index, score_index
   from rowidcol
      LATERAL view posexplode(prod_arr) ptable as prd_index, pdid
      LATERAL view posexplode(score_arr) prtable as score_index, sid
),
colselect as
(
   select row_id, user_id, collect_list(concat(product, ':', score)) product_score
   from coltorows
   where prd_index = score_index
   group by row_id, user_id
)
select user_id, concat_ws(',', product_score) as prodcut_score
from colselect
order by user_id;

Input -
Table Name - Prod -
user_id  product_id    score
1         A,B,C,D      10,20,30,40
2         X,Y,Z        1,2,3
3         K,F,G        100,200,300

Output -
user_id   prodcut_score
1         A:10,B:20,C:30,D:40
2         X:1,Y:2,Z:3
3         K:100,F:200,G:300


text:
Q: Number of transitive relations on a set Let $T(n)$ denote the number of transitive binary relations on an $n$-element set. So T(1) = 2 and T(2) = 13, for of the 16 possible relations on a 2-element set {a,b}, the only three which are not transitive are
(i) {(a,b), (b,a)},
(ii) {(a,a), (a,b), (b,a)},
(iii) {(b,b), (a,b), (b,a)}.
There is some literature on this function - a wikipedia entry, a sequence in Sloane up to $n=18$, a few research papers on this and similar kinds of functions, including some complicated formulas for $T(n)$. However, I have not seen anywhere a "nice asymptotic estimate" for $T(n)$. Using the data in Sloane I computed, for $1 \leq n \leq 18$, the function $f(n) = \frac{\log_{2} T(n)}{n^2}$, obtaining the following approximate values
1, 0.9251, 0.8242, 0.7477, 0.6894, 0.6435, 0.6063, 0.5755, 0.5494, 0.5270, 0.5075, 0.4903, 0.4751, 0.4614, 0.4491, 0.4380, 0.4278, 0.4184
So my general question is whether anything (non-trivial) is known about the asymptotics of $T(n)$, and a more specific question is whether $f(n) \rightarrow 0$ as $n \rightarrow  \infty$ ?

A: If $P(n)$ is the number of partial orders, then $\log_2 P(n) = n^2/4 + o(n^2)$, an old result of Kleitman. Look in MathSciNet for many different sharpenings. Now if $T(n)$ is the number of  transitive relations, then Klaska proved that $T(n)$ and $2^n P(n)$ are asymptotically equal.  Therefore,  $\log_2 T(n) = n^2/4 + o(n^2)$.  Ref to Klaska: MR1446401 (98c:05006)
Klaška, Jiří. Transitivity and partial order. Math. Bohem. 122 (1997), no. 1, 75–82.

A: Yes, a lot is known. Transitive relations are the same (essentially; there is a slight problem with  self-loops) as strongly connected digraphs. See:
http://www.math.uwaterloo.ca/~nwormald/papers/dicores.pdf
and references therein.
EDIT oops, answers a wrong (but related) question... Formulas (though not asymptotics) for the quantities in question appear in
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.100.6879&rep=rep1&type=pdf
Another Edit Partial orders (as mentioned by @Aaron) have been asymptotically enumerated, and the log is asymptotic to $n^2/4.$ (see Kleitman, D. J.; Rothschild, B. L.
Asymptotic enumeration of partial orders on a finite set.
Trans. Amer. Math. Soc. 205 (1975), 205–220. )


text:
Q: Convert System.Object[] and dereference properties Azure CLI returns System.Object[] which aren't handy to work with. For example I can create an App-Insights with a script and az cli returns a System.Object[] including the instrumentation key. I can write methods to iterate over the array and extract the required fields, but there must be an easier way
I tried to convert the object to different formats but I couldn't find a possibility to convert the result of an cli command to an object with dereferencable properties
$a = az monitor app-insights component show -a myfuntions -g my-group
$a

{
  "appId": "<id>",
  "applicationId": "myfunctions",
  "applicationType": "web",
  "creationDate": "2019-05-17T15:22:05.042607+00:00",
  "etag": "\"8000ece5-0000-0200-0000-4edfe57e0000\"",
  "flowType": "Bluefield",
  "hockeyAppId": null,
  "hockeyAppToken": null,
  "id": "/subscriptions/1111111-4d7d-4df4-8dae-5311111111/resourceGroups/dev-api/providers/microsoft.insights/components/dev-validierung-functions"
  "instrumentationKey": "3232323-23e05-32da-bf03-a8b8b4d18783",
  "kind": "web",
  "location": "westeurope",
  "name": "myfunctions",
  "provisioningState": "Succeeded",
  "requestSource": "rest",
  "resourceGroup": "mygroup",
  "samplingPercentage": null,
  "tags": {},
  "tenantId": "<the tenant id>",
  "type": "microsoft.insights/components"
}

The var $a contains the System.Object[]. It's possible to iterate over all objects in the array in a self-defined function, but I think I'm missing some detail. There must be an easy way to convert into dereferencable objects.

A: You can use PsObject property:
$object = @"
{
"appId": "<id>",
"applicationId": "myfunctions",
"applicationType": "web",
"creationDate": "2019-05-17T15:22:05.042607+00:00",
"etag": "\"8000ece5-0000-0200-0000-4edfe57e0000\"",
"flowType": "Bluefield",
"hockeyAppId": null,
"hockeyAppToken": null,
"id": "/subscriptions/1111111-4d7d-4df4-8dae-5311111111/resourceGroups/dev-api/providers/microsoft.insights/components/dev-validierung-functions",
"instrumentationKey": "3232323-23e05-32da-bf03-a8b8b4d18783",
"kind": "web",
"location": "westeurope",
"name": "myfunctions",
"provisioningState": "Succeeded",
"requestSource": "rest",
"resourceGroup": "mygroup",
"samplingPercentage": null,
"tags": {},
"tenantId": "<the tenant id>",
"type": "microsoft.insights/components"
}
"@

$j = $object | ConvertFrom-Json
$j.PsObject.Properties | % { Write-Host "Name $($_.Name) ; Value $($_.Value)"}

Output:
Name appId ; Value <id>
Name applicationId ; Value myfunctions
Name applicationType ; Value web
Name creationDate ; Value 2019-05-17T15:22:05.042607+00:00
Name etag ; Value "8000ece5-0000-0200-0000-4edfe57e0000"
Name flowType ; Value Bluefield
Name hockeyAppId ; Value
Name hockeyAppToken ; Value
Name id ; Value /subscriptions/1111111-4d7d-4df4-8dae-5311111111/resourceGroups/dev-api/providers/microsoft.insights/components/dev-validierung-functions
Name instrumentationKey ; Value 3232323-23e05-32da-bf03-a8b8b4d18783
Name kind ; Value web
Name location ; Value westeurope
Name name ; Value myfunctions
Name provisioningState ; Value Succeeded
Name requestSource ; Value rest
Name resourceGroup ; Value mygroup
Name samplingPercentage ; Value
Name tags ; Value
Name tenantId ; Value <the tenant id>
Name type ; Value microsoft.insights/components

Hope that helps.

A: Convert it from json.
$obj = $a | convertfrom-json


text:
Q: Ajax file upload rest returns 415 I created simple HTML form for file upload:
<form method="post" enctype="multipart/form-data" action="#" id="upload-file">
      <input id="file" class="browse-files-button" value="Browse" type="file" name="files"></input>
</form>

And here is my ajax call:
var data = new FormData(AJS.$('#upload-file')[0]);
 AJS.$.ajax({
        type: "POST",
        url: getAttachmentUrl(),
        data: file,
        dataType: "json",
        cache: false,
        processData: false,
        contentType: false,
        headers: {
        "X-Atlassian-Token": "nocheck"
        },
        error : function() {
            console.log("Error while uploading file!");
        },
        success : function(result){
            console.log("File successfully uploaded!");
        }
    });

And in the result i'am receiving response 415 that indicates that 415 Unsupported Media Type.

A: Problem was that server wants to receive a file parameter with name "file" but i sent as "files".
<form method="post" enctype="multipart/form-data" action="#" id="upload-file">
      <input id="file" class="browse-files-button" value="Browse" type="file" name="file"></input>
</form>


text:
Q: Cart Rules for tiered promotion with exclusions I'm trying to run a simple rule based on cart subtotal. If itfalls between 2 amounts, a $ discount gets applied.
The problem starts when I need to set conditions about what items can be "counted" towards this subtotal. I.e, certain items are to be excluded.
I can't seem to get this to work. Is it even possible? I defined conditions under "Apply the rule only to cart items matching the following conditions (leave blank for all items)." but it did not do what I want.


text:
Q: Why is Google's quantum supremacy experiment impressive? In the Nature paper published by Google, they say,

To demonstrate quantum supremacy, we compare our quantum processor against state-of-the-art classical computers in the task of sampling the output of a pseudo-random quantum circuit. Random circuits are a suitable choice for benchmarking because they do not possess structure and therefore allow for limited guarantees of computational hardness. We design the circuits to entangle a set of quantum bits (qubits) by repeated application of single-qubit and two-qubit logical operations. Sampling the quantum circuit's output produces a set of bitstrings, for example {0000101, 1011100, …}. Owing to quantum interference, the probability distribution of the bitstrings resembles a speckled intensity pattern produced by light interference in laser scatter, such that some bitstrings are much more likely to occur than others. Classically computing this probability distribution becomes exponentially more difficult as the number of qubits (width) and number of gate cycles (depth) grow.

So, from what I can tell, they configure their qubits into a pseudo-randomly generated circuit, which, when run, puts the qubits into a state vector that represents a probability distribution over $2^{53}$ possible states of the qubits, but that distribution is intractable to calculate, or even estimate via sampling using a classical computer simulation. But they sample it by "looking" at the state of the qubits after running the circuit many times.
Isn't this just an example of creating a system whose output is intractable to calculate, and then "calculating" it by simply observing the output of the system?
It sounds similar to saying:

If I spill this pudding cup on the floor, the exact pattern it will form is very chaotic, and intractable for any supercomputer to calculate. But I just invented a new special type of computer: this pudding cup. And I'm going to do the calculation by spilling it on the floor and observing the result. I have achieved pudding supremacy.

which clearly is not impressive at all. In my example, I'm doing a "calculation" that's intractable for any classical computer, but there's no obvious way to extrapolate this method towards anything actually useful. Why is Google's experiment different?
EDIT: To elaborate on my intuition here, the thing I consider impressive about classical computers is their ability to simulate other systems, not just themselves. When setting up a classical circuit, the question we want to answer is not "which transistors will be lit up once we run a current through this?" We want to answer questions like "what's 4+1?" or "what happens when Andromeda collides with the Milky Way?" If I were shown a classical computer "predicting" which transistors will light up when a current is run through it, it wouldn't be obvious to me that we're any closer to answering the interesting questions.

A:
To elaborate on my intuition here, the thing I consider "impressive" about classical computers is their ability to simulate other systems, not just themselves. When setting up a classical circuit, the question we want to answer is not "which transistors will be lit up once we run a current through this?" We want to answer questions like "what's 4+1?" or "what happens when Andromeda collides with the Milky Way?"

There isn't a real distinction here. Both quantum and classical computers only do one thing: compute the result of some circuit. A classical computer does not fundamentally know what $4+1$ means. Instead current is made to flow through various transistors, as governed by the laws of physics. We then read off the final state of the output bits and interpret it as $5$.
The real distinction, which holds in both cases, is whether you can program it or not. For example, a simple four-function calculator is a classical system involving lots of transistors, but the specific things it can compute are completely fixed, which is why we don't regard it as a classical computer. And a pudding is a quantum system involving lots of qubits, but we can't make it do anything but be a pudding, so it's not a quantum computer.
Google can control the gates they apply in their quantum circuit, just like loading a different program can control the gates applied in a classical CPU. That's the difference.

A: The big difference between the quantum supremacy experiment and your pudding experiment is that the quantum supremacy experiment solved an unambiguous, well-posed mathematical problem. While people sometimes describe the computational task as "simulating the physical Sycamore computer", that's not right. The actual task was calculating the output of an abstract quantum logical circuit, of which the Sycamore computer was an approximate physical instantiation. The difference is subtle but crucial. From a computational perspective, the math came first and the physics came second.
Crucially, the quantum supremacy problem was mathematically well-specified, and so it could be checked on a classical computer. The parallel classical computation wasn't just there to provide a time benchmark, but also - crucially - to check the quantum computation for accuracy.
There's no such "slower but equivalent" computation to the pudding experiment. In the pudding experiment, you need to specify exact which of these two problems you're trying to solve:

*

*Simulate the pattern that will result if you knock a generic pudding cup off the table.

*Simulate the pattern that will result if you knock a particular pudding cup off the table [where you specify enough detail to nail down the initial conditions in enough detail to model its fall].

The first variant is obviously massively underspecified and doesn't have a unique answer. The second variant does in principle have a unique answer, but crucially, you can't actually capture all the necessary details about the initial condition in practice. So neither variant can actually be framed as a mathematically well-posed question.
In the quantum supremacy experiment, the abstract problem to be solved (which was solving the abstract logical circuit, not simulating the physical hardware) was simple enough to pose that you could (very slowly) solve it exactly on a classical computer as well as on a quantum one.

A: I co-run an experimental research group in which, among other things, we develop the ability to control quantum bits so as to do (one day) quantum computing. In our lab we have the most precise quantum bits and operations, but we have only ever performed (or tried to perform) operations on two or three bits at a time. This is partly because we have taken an interest in other aspects of the problem, and partly because if we were to put ten or more qubits into our experiment (which would be easy to do), we would merely reproduce small-scale circuits rather than learn how to build a large computer.
I would say that the question asked by Bridgeburners is well asked, and it correctly characterises the limited nature of Google's calculation. However, one can look at Google's result from an experimental perspective, and then it does become, I think, very impressive.
From an experimental point of view, Google's achievement is that they have achieved sufficient experimental control over a circuit containing 53 qubits that it can generate entangled states involving all or most of the qubits, in such a way that the fidelity of the state is not immediately lost before the state can even be measured in some way. We would certainly not be able to achieve this in our lab today. If we devoted all our effort to doing the same thing, I think it would take us
a year or more to implement the required extensions to our experimental equipment with the required precision. So it is indeed very impressive. (Meanwhile
with our trapped ion methods we can also do some things which Google's machine could not do.)
Looking now to the near future, there are two main technologies showing promise for quantum computing. These are atomic ions confined in high vacuum, and superconducting circuits of the type employed by Google. A few years ago, a rough 'competition' was held, involving computations requiring only 10 or so qubits, and the trapped ion methods won because they could take advantage of greater inter-connectability of their qubits, and good general precision in operations and measurements. If such a competition were to be held now, it is not so clear which technology would win. Nor is it clear which is the better bet for complete control of 50 qubits in such a way that general-purpose computing could be done, answering questions people really want to know (as opposed to computer-science abstractions). But what is clear, I think, is that this stage will be reached by either or both paths, and this will happen on a timescale of years not decades. What John Martinis and his colleagues have done is shown that the superconducting circuit approach is a very strong contender, and they have shown great expertise and mastery in overcoming many and severe technical challenges to get this far.

A: It is (in isolation) no different from you pudding computer.

However, the context is very important. Their are certain useful problems that we know how to solve much faster on a quantum computer than a classical one. Those problems are miles out of reach, and probably will not be solved for 10 or 20 years still (I am more pessimistic than most, maybe too much so).
In the meantime thousands of people all around the world are working on lots of different quantum computer ideas, superconducting ones like Google and IBM, but also optical ones of various types with quantum dots, down conversion sources or nitrogen vacancy centres.
These different communities have computers that work with fundamentally different hardware, so they are hard to compare against one another. This Google result indicates several things: (1) It shows that they are making some progress. (2) It is to "show off" how they are doing compared to the other approaches. For example optics people are still at around 8-qubits, while superconducting stuff is at 53. This is not a useful comparison (the two machines are too different) but that won't stop people from showing off.
The real story is not the "quantum supremacy", its that they have a 53 qubit circuit that seems to kind of half-work some of the time. (This is where the optics people get to gloat, their stuff has less qubits but actually works most of the time.) In order to "sell" this machine as an interesting step along the way to something useful they had to actually do something with it.

A:
If I spill this pudding cup on the floor, the exact pattern it will
  form is very chaotic, and intractable for any supercomputer to
  calculate. But I just invented a new special type of computer: this
  pudding cup. And I'm going to do the calculation by spilling it on the
  floor and observing the result. I have achieved pudding supremacy.

You are right. But only half of the story
The other half is, this pudding spilled pattern can also be used to solve a mathematical problem which is very useful and impossible to be solved by conventional non-pudding system. It also could be controlled to make it deterministically solve that same problem anytime you want. If your pudding spilled can do that then it gain label of supremacy over conventional computer
The point is we need to solve a problem by any means and method as efficient as possible, if the pudding spilled are completely efficient way to do it, it would reign supremacy and we will make a pudding machine and pudding factory for solving problem
Now, replace pudding with quantum


text:
Q: css navigation bar not appearing horizontally at top of page on same line as logo I cannot seem to get my css navigation bar to appear on the same line as my logo.  I am guessing that this has a simple enough solution but as a learner it seems to be some teething problems for me that unfortunately I cannot resolve.  Code from both css and html file are in the jsbin link below where you can get a full visual too:
https://jsbin.com/qopuqahute/edit?html,css,output
Your assistance and advice will be much appreciated.
HTML

            Tailored Web Solutions

 About Us

 Services

CSS
body{
    margin: 0;
    font-family: Arial, Helvetica, sans-serif;
    background-color: #f7f7f7;
}

#topbar{
    background-color: black;
    width: 100%;
    height: 90px;
    color: #f7f7f7;
}

#logodiv{
    padding-left: 20px;
    padding-top: 30px;
    font-size: 35px;
    font-family: fantasy;
    font-style: italic;
    font-weight: bold;
}

#navigationbar ul{
    list-style-type: none;

}

#navigationbar ul li{
    color: red;
    display: inline;
    float: left;
}

A: Start here:
add a float:left; property to your #logodiv rule like this:
#logodiv{
    padding-left: 20px;
    padding-top: 30px;
    font-size: 35px;
    font-family: fantasy;
    font-style: italic;
    font-weight: bold;
    float: left;
}

A: Your #logodiv and #navigationbar are both divs which are by default block elements. To get them to line up use display: inline-block.
https://jsfiddle.net/Leztux5k/
CSS
#logodiv{
    padding-left: 20px;
    padding-top: 30px;
    font-size: 35px;
    font-family: fantasy;
    font-style: italic;
    font-weight: bold;
  display: inline-block;
}
#navigationbar{
  display: inline-block;
}


text:
Q: Error: RuntimeError: abort(Error: EMFILE: too many open files, open I'm new to mobile development and I'm using expo on Windows, when I'm going to export the apk as the command expo build:android -t apk, I'm getting the following error:
RuntimeError: abort(Error: EMFILE: too many open files, open 'C:\Users\danto\AppData\Roaming\npm\node_modules\expo-cli\build\utils\handleErrors.js'). Build with -s ASSERTIONS=1 for more info.
at process.abort (C:\Users\danto\OneDrive\Documentos Pessoais\ignite-lab\rockethelp\node_modules\metro-hermes-compiler\src\emhermesc.js:402:15)
at process.emit (node:events:539:35)
at process.emit (C:\Users\danto\AppData\Roaming\npm\node_modules\expo-cli\node_modules\source-map-support\source-map-support.js:439:21)
at processEmit [as emit] (C:\Users\danto\AppData\Roaming\npm\node_modules\expo-cli\node_modules\signal-exit\index.js:199:34)
at emit (node:internal/process/promises:140:20)
at processPromiseRejections (node:internal/process/promises:274:27)
at processTicksAndRejections (node:internal/process/task_queues:97:32)

I've searched a lot on the internet and found something about updating the watchman , but this one from what I've noticed only works with Linux and Mac. I'm Brazilian and I don't speak fluent English, so I'm translating this message through google translator, sorry for any spelling mistakes.


text:
Q: Too many re-renders on search API I am new to this so I hope this is the right place to get help!
As titled, executing this code is giving me the "Too many re-renders" error on React.
I have tried going through all lines and checking my hooks repeatedly, but nothing seems to work.
I am guessing this is happening due to useEffect, so pasting the code for the relevant components below:
UseResults:
import { useEffect, useState } from 'react';
import yelp from '../api/yelp';

export default () => {
    const [results, setResults] = useState([]);
    const [errorMessage, setErrorMessage] = useState('');

    const searchApi = async () => {
        try {
            const response = await yelp.get('/search', {
                params: {
                    limit: 50,
                    term,
                    location: 'san francisco'
                }
            });
            setResults(response.data.businesses);
        } catch (err) {
            setErrorMessage('Something went wrong')
        }
    };

    useEffect(() => {
        searchApi('pasta');
    }, []);

    return [searchApi, results, errorMessage];
}

SearchScreen:
import React, { useState } from 'react';
import { Text, StyleSheet } from 'react-native';
import { ScrollView } from 'react-native-gesture-handler';
import ResultsList from '../components/ResultsList';
import SearchBar from '../components/SearchBar';
import useResults from '../hooks/useResults';

const SearchScreen = (navigation) => {
    const [term, setTerm] = useState('');
    const [searchApi, results, errorMessage] = useResults();

    const filterResultsByPrice = (price) => {
        return results.filter(result => {
            return result.price === price;
        });
    };

    return <>
        <SearchBar
            term={term}
            onTermChange={setTerm}
            onTermSubmit={searchApi()}
        />
        {errorMessage ? <Text>{errorMessage}</Text> : null}
        <Text>We have found {results.length} results</Text>
        <ScrollView>
            <ResultsList
                results={filterResultsByPrice('$')}
                title="Cost Effective"
                navigation={navigation}
            />
            <ResultsList
                results={filterResultsByPrice('$$')}
                title="Bit Pricier"
                navigation={navigation}
            />
            <ResultsList
                results={filterResultsByPrice('$$$')}
                title="Big Spender"
                navigation={navigation}
            />
        </ScrollView>
    </>
};

const styles = StyleSheet.create({});

export default SearchScreen;

ResultsList:
import React from 'react';
import { View, Text, StyleSheet, FlatList } from 'react-native';
import { TouchableOpacity } from 'react-native-gesture-handler';
import ResultsDetail from './ResultsDetail';

const ResultsList = ({ title, results, navigation }) => {
    return (
        <View style={styles.container} >
            <Text style={styles.title}>{title}</Text>
            <FlatList
                horizontal
                showsHorizontalScrollIndicator={false}
                data={results}
                keyExtractor={result => result.id}
                renderItem={({ item }) => {
                    return (
                        <TouchableOpacity onPress={() => navigation.navigate('ResultsShow')}>
                            <ResultsDetail result={item} />
                        </TouchableOpacity>
                    )
                }}
            />
        </View>
    );
};

const styles = StyleSheet.create({
    title: {
        fontSize: 18,
        fontWeight: 'bold',
        marginLeft: 15,
        marginBottom: 5
    },
    container: {
        marginBottom: 10
    }
});

export default ResultsList;

TIA!


text:
Q: create-react-app npm WARN config global `--global`, `--local` are deprecated When I create react app for any project then I am facing this on npm WARN config global --global, --local are deprecated. Use --location=global instead. How do I fix this problem?

A: Open powershell as administrator and run:
Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force
npm install --global --production npm-windows-upgrade
npm-windows-upgrade --npm-version latest

A: Try to run in terminal
npm install


text:
Q: Анимация css движется не равномерно от изначальной точки Знатоки, нужен хелп. Имеется анимация расширяемого круга от точки, но движется он как то в сторону, а не равномерно во все стороны от неё. Подскажите как исправить проблему. Занимаюсь анимациями недавно(

.changegalview{
    margin: 20px 20px;
}

.changegalview .circle1{
        border-radius: 50%;
        border: solid 3px #333;
      /*  transform: translateX(-80%) translateY(-20%); */
        position: absolute;
        opacity: 0.2;
        animation: changegalview 2s linear infinite 0.25s;
       top: 15px;
        left: 38px;
}

@keyframes changegalview {
      50% {
        width: 30px;
        height: 30px;
        opacity: 0.5;
      }

      75% {
        width: 40px;
        height: 40px;
        opacity: 0.2;
      }

      100% {
        width: 50px;
        height: 50px;
        opacity: 0.05;
      }
}

    <svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" viewBox="0 0 26 26" fill="#f50101">
        <path fill-rule="evenodd" clip-rule="evenodd" d="M13.0046 25C13.0046 25 23.2319 18.1818 23.2319 10.2273C23.2319 7.51483 22.1544 4.91348 20.2364 2.9955C18.3184 1.07751 15.7171 0 13.0046 0C10.2922 0 7.69083 1.07751 5.77284 2.9955C3.85486 4.91348 2.77734 7.51483 2.77734 10.2273C2.77734 18.1818 13.0046 25 13.0046 25ZM16.4164 10.2272C16.4164 12.11 14.8901 13.6363 13.0073 13.6363C11.1246 13.6363 9.59826 12.11 9.59826 10.2272C9.59826 8.3444 11.1246 6.8181 13.0073 6.8181C14.8901 6.8181 16.4164 8.3444 16.4164 10.2272Z" fill="#BDBDBD"></path>
    </svg>

A: Вот так, видимо?

.changegalview{
    margin: 20px 20px;
}

.changegalview .circle1{
        border-radius: 50%;
        border: solid 3px #333;
      /*  transform: translateX(-80%) translateY(-20%); */
        position: absolute;
        opacity: 0.2;
        animation: changegalview 2s linear infinite 0.25s;
       top: 60px;
        left: 60px;
}

@keyframes changegalview {
      0% {
        top: 60px;
        left: 60px;
        width: 0px;
        height: 0px;
        opacity: 0.5;
      }

      100% {
        top: 35px;
        left: 35px;
        width: 50px;
        height: 50px;
        opacity: 0.05;
      }
}

    <svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" viewBox="0 0 26 26" fill="#f50101">
        <path fill-rule="evenodd" clip-rule="evenodd" d="M13.0046 25C13.0046 25 23.2319 18.1818 23.2319 10.2273C23.2319 7.51483 22.1544 4.91348 20.2364 2.9955C18.3184 1.07751 15.7171 0 13.0046 0C10.2922 0 7.69083 1.07751 5.77284 2.9955C3.85486 4.91348 2.77734 7.51483 2.77734 10.2273C2.77734 18.1818 13.0046 25 13.0046 25ZM16.4164 10.2272C16.4164 12.11 14.8901 13.6363 13.0073 13.6363C11.1246 13.6363 9.59826 12.11 9.59826 10.2272C9.59826 8.3444 11.1246 6.8181 13.0073 6.8181C14.8901 6.8181 16.4164 8.3444 16.4164 10.2272Z" fill="#BDBDBD"></path>
    </svg>


text:
Q: How to structure a C++ library with language wrappers? I have a question about good practices for writing a C++ library that includes wrappers for other languages, such as Python and Matlab. This may be a simple question or a duplicate, but I haven't found a good resource or another answer which helps explain how to do this.
For background, I am working on a C++ library project that has C wrappers included specifically for compatibility with other languages. The library is a scientific computing library written in C++, and I have already written the C wrappers for the functions and classes to be used as part of a shared library.
My question is how to incorporate the C wrappers into the modules for other languages, such as wrapper libraries for Python and Matlab. I'm not asking for specifics on how to implement the code for these other languages, because that is another question entirely, and I already have a basic understanding of how to write the code that can be built and loaded for each language as its own library. My question is mainly about including the C wrappers into these other builds.
For example, I have the following directory structure, where each folder contains code relevant to a different language/module.
top
├─ matlab
│  ├─ CMakeLists.txt
│  ├─ matlab_wrapper.hpp
│  └─ matlab_wrapper.cc
├─ python
│  ├─ CMakeLists.txt
│  ├─ python_wrapper.hpp
│  └─ python_wrapper.cc
├─ src
│  ├─ CMakeLists.txt
│  ├─ c_wrapper.hpp
│  ├─ c_wrapper.cc
│  └─ other code...
└─ CMakeLists.txt

I understand that each folder should be self-sufficient, and buildable on its own, but I am having trouble figuring out how to distribute the code so that it includes the C wrappers. Basically, I have the C implementation in the c_wrapper files and I would like to use this in the matlab and python libraries.
Normally, I would include the other source files during the build step and be done with it (this may just be the answer), but everything in the src folder is built and distributed as its own shared library. It seems redundant to either rewrite the C wrappers in the matlab_wrapper and python_wrapper files (basically creating 3 versions of the same function) or to include the c_wrapper files in the build step of the other libraries because they are already included in the main C++ library.
I'm not an expert in packaging shared libraries, so what is the best way to go about this? Should I just include the c_wrapper source files as part of the build step, rewrite the C++ wrappers in each module, or is there another way to include the code in c_wrapper in the wrapper libraries? Ideally, each module will share the same (or very similar) API, so it would be great if there were a way to include this code without rewriting the same function every time a new C wrapper is added. Any help or advice is greatly appreciated.

A: You might be able to make a single shared library for all purposes: the PyInit_foo that Python looks for will simply be ignored by Matlab, after all.  But you still might not want to alter your main library to support such uses: maybe it has other compiled clients that need no wrapper, or maybe it's supposed to be installed separately from special wrappers, or maybe it needs to be usable on a machine without the hosts installed.
Another option is to make one shared library for each ultimate client.  Linking the same object files into each defeats some of the purpose of shared libraries, like sharing memory between a Matlab process and a concurrent Python process each using your library.  It might (I'm not sure) also end up running global constructors more than once, but those are best avoided anyway.  These issues might not matter for your use cases, but the same build issues as before for the real C++ library apply.
Otherwise, you'll have multiple shared libraries in one process (one for the "real" C++ library and another for the host language module).  There are ABI issues here; one way to avoid them is by providing, as you suggested, a C API in the core library.  There are, of course, other ways of dealing with those issues, especially when you control all the compilations.
There are yet more approaches: the main library could include the interface for one host language (especially if it can also serve as the C API) but not another, or one shared library could serve multiple languages without including the C++ core.  Given the C API, you may be able to use a FFI from the host language (ctypes for Python) instead of writing (more) C specifically for the host.
Whatever link strategy you choose, compiling is always the same: just #include whatever of your headers are relevant (those for the C API if appropriate) and any needed for the host language (if any) and go.


text:
Q: Probability that a point is closer to a side than a diagonal So I have a rectangle in which a point is randomly chosen. One side is $a$ and the other is $b=a\sqrt3$. I am supposed to find the probability that a point is closer to a side than to the closest diagonal.
I have found the probability that the point is closer to $a$ (0.71) and to $b$ (0.24). Now I was wondering how I can put these two probabilities together to form the asked-for probability. Thanks

A: I answered a very similar question involving a square instead of a $\sqrt3$ rectangle here.

Points in the shaded area are closer to a side than a diagonal. The rectangle divides into four triangles, each containing one shaded triangle; the apexes of the shaded triangles are the incentres of the larger triangles they lie in.
Assuming that the shorter side is 1, the shaded triangles on the east and west have altitude (from the rectangle sides) $\frac1{2\sqrt3}$, so have a combined area of $\frac1{2\sqrt3}$ also. Those on the north and south have altitude $\frac{\sqrt3}2\tan15^\circ=\sqrt3-\frac32$ and combined area $\sqrt3(\sqrt3-\frac32)=3-\frac{3\sqrt3}2$. The shaded area is therefore $3-\frac{3\sqrt3}2\frac1{2\sqrt3}=\frac{9-4\sqrt3}3$. The rectangle's area is of course $\sqrt3$, so its shaded proportion – and therefore the probability a point inside it is closer to a side than a diagonal – is
$$\frac{9-4\sqrt3}{3\sqrt3}=\sqrt3-\frac43=0.398717\dots$$

A: The red areas are of points closer to a side of the rectangle. Its area is the sum of the triangles, two acutangle and two obtusangle.
The two acutangle are each $1/3$ of the equilateral triangle having side $1$ and half diagonals. A diagonal is $\sqrt{3+1}=2$ so half diagonal is $1$ (that's why they are equilateral).
So the area of the two acutangle is $2\times \dfrac{1}{3} \cdot\dfrac{\sqrt 3}{4}=\dfrac{\sqrt 3}{6}$
As their sides are the angle bisector of the $30°$ angle the two obtusangle have the vertex that is the incentre (centre of the inscribed circle) of the bigger triangle formed by the diagonals whose area is $\dfrac{\sqrt 3}{4}$ and whose perimeter is $2+\sqrt 3$.
The radius of the inscribed circle is $h=\dfrac{area}{half\,perimeter}=\dfrac{\frac{\sqrt 3}{4}}{\frac{2+\sqrt 3}{2}}=\dfrac{\sqrt{3}}{2 \left(2+\sqrt{3}\right)}$
The two obtusangle triangle have an area $\sqrt{3}\times \dfrac{\sqrt{3}}{2 \left(2+\sqrt{3}\right)}=\dfrac{3}{2 \left(2+\sqrt{3}\right)}$
Therefore the red area is $\dfrac{\sqrt 3}{6}+\dfrac{3}{2 \left(2+\sqrt{3}\right)}=\dfrac{1}{3} \left(9-4 \sqrt{3}\right)$
The area of the rectangle is $\sqrt 3$ so the probability of getting a point closer to the sides of the rectangle is $p=\dfrac{\frac{1}{3} \left(9-4 \sqrt{3}\right)}{\sqrt 3}=\dfrac{1}{3} \left(3 \sqrt{3}-4\right)\approx 0.3987$


text:
Q: Trigger JVectorMap drill-down with link or button I am using the JVectorMap plugin and have successfully created a drill-down map.
My question is, is it possible to trigger the drill-down function externally outside the map elsewhere on the page i.e. on click of a link or button.

A: Let say you have correctly initialized a jVectorMap drill-down map:
var drillDownUSMap;

$(document).ready(function () {
  drillDownUSMap= new jvm.MultiMap({
    container: $('#map'),
    maxLevel: 1,
    main: {
    map: 'us_lcc',
    regionsSelectable: true,
    regionStyle: {
        selected: {
            fill: 'green'
            }
        },
    },
    mapUrlByCode: function(code, multiMap){
      var path = 'maps/us-counties/',
          county = code.toLowerCase(),
          proj = multiMap.defaultProjection,
          mapData = 'jquery-jvectormap-data-' + county + '-' + proj + '-en.js';
      return path + mapData;
    }
  });
});

(IMHO I would store the reference to the returned map object) then, use it like as follows:
function drillDownUSMapTo(code) {
  var mapData = drillDownUSMap.params.mapNameByCode(code, drillDownUSMap);
  drillDownUSMap.drillDown(mapData, code);
}

... whereby You should already have some buttons to click, as You said in Your question:
onclick="drillDownUSMapTo('US-TX');"

BTW, thanks to bjornd for the great jVectorMap.


text:
Q: Django created_at field not added when creating an object I'm trying to get Django automatically add a field to an object where the date and time is saved in the field as a timestamp.
When I create the object in my view and I go check in admin page, every other field is created but not this one.
views.py :
newconf = ConfigUser.objects.create(
        ref=''.join(random.SystemRandom().choice(
            string.ascii_lowercase + string.ascii_uppercase + string.digits
        ) for _ in range(20)),
        name='',
        user=request.user,
        # Here I don't add created_at because I want it to be automatic (see models.py)
        cpu=cpu[0],
        gpu=gpu[0],
        ram=ram[0],
        ssd_m2=ssd_m2[0],
    )

models.py :
class ConfigUser(models.Model):

    ref = models.CharField(max_length=20, unique=True, default='')
    name = models.CharField(max_length=128, default='')
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

    cpu = models.ForeignKey(CPU, on_delete=models.CASCADE)
    gpu = models.ForeignKey(GPU, on_delete=models.CASCADE)
    ram = models.ForeignKey(RAM, on_delete=models.CASCADE)
    ssd_m2 = models.ForeignKey(SSD_M2, on_delete=models.CASCADE)

    def __str__(self):
        return self.name

A: If a field inside model is created with auto_now attribute set, it will also include the property editable=False and therefore it will not show up in the admin panel.
To overcome this, you need to override your save method:
class ConfigUser(models.Model):
    # some code
    created_at = models.DateTimeField(editable=False)

    def save(self, *args, **kwargs):
        if not self.id:
            self.created_at = timezone.now()
        return super(User, self).save(*args, **kwargs)

A: First of all, make sure to check if all model migrations have been done.
Secondly, as an alternative, you could try to create the "newconf" object from the class directly, and not via the objects.create() method, like so:
# Create the record as object of the model class
newconf = ConfigUser(ref=''.join(random.SystemRandom().choice(
            string.ascii_lowercase + string.ascii_uppercase + string.digits
            ) for _ in range(20)),
            name='',
            user=request.user,
            cpu=cpu[0],
            gpu=gpu[0],
            ram=ram[0],
            ssd_m2=ssd_m2[0])

newconf.save()

To have this method working you should only add the def__init__ method in the model ConfigUser, passing all the initialization parameters in.


text:
Q: PHP upload image file issue I am currently working on a site, of which needs to have it be possible for users to upload an image file. I have the HTML form setup and it seems to be working, this isn't the part with the issue. The issue is the PHP part, where I am getting the file upload, gathering the extension of that file and renaming the file to a specific timestamp and then uploading it into a specific folder.
I have an if statement to check for the upload, but every time I run the code it returns the "error" statement and when it "echo's" the file name it is missing the extension.
I have tried to run the code through syntax error checkers and nothing returns and when running the code it doesn't show any alerts.
I am not completely sure where the code goes wrong.
Below here is the HTML form
<form action="uploadProdu.php" method="POST" id="productUploadForm">

<input type="file" name="productImage" id="uploadImageFile" class="center-block"><br>
<input type="submit" value="Submit Product" id="submitFormButton">

</form>

Below here is the PHP part
<?php

     //This retrieves all the other information from the form
     $productImage=($_FILES['productImage']['name']);

     //Get the extension of the image uploaded
     $imageExtens = pathinfo($productImage, PATHINFO_EXTENSION);

    //Generate a timestamp to use and rename the file upload
     $ran = round(microtime(true)) ;

     //Add a dot to the random number, to then add extension later
     $ran2 = $ran.".";

     //Subdirectory for image upload (the targeted folder)
     $target = "productimages/";

    //Combine the folder, the timestamp name and the extension
    $target = $target . $ran2 . $imageExtens;

    if(move_uploaded_file($_FILES['productImage']['tmp_name'], $target)) {
     echo "The file has been uploaded as ".$ran2.$imageExtens;
     }  else {
     echo "Sorry, there was a problem uploading your file.";
     echo "The file you tried to upload was called ".$ran2.$imageExtens;
      echo "And with directory full length ".$target;
     }
     ?>


text: Q: How to prevent the user from leaving my page I'm trying to make an online test using spring-mvc and html, css, jquery and I want to prevent the user that is doing the test from leave the test screen while doing the test. Does anybody know how I can do that?


text:
Q: Mappings are not getting updated in ElasticSearch using java code I have tried updating my mappings in elastic Search using Java Code.
But to my dismay the mappings are not getting updated
Following is my code
String settingsAsJson =getJsonString("settingFile");
client.admin().indices().close(new        CloseIndexRequest(indexName)).actionGet().isAcknowledged();
boolean settingsAck =   client.admin().indices().prepareUpdateSettings().setSettings(settingsAsJson).setIndices(indexName).execute().actionGet().isAcknowledged();
System.out.println("Applied SETTINGS "+ settingsAck);
String mappingAsJson = getJsonString("mappingFile");
boolean mappingack = client.admin().indices().preparePutMapping().setIndices(indexName).setType(indexType).setSource(mappingAsJson).execute().actionGet().isAcknowledged();
System.out.println("Applied Mappings "+ mappingack);
client.admin().indices().open(new OpenIndexRequest(indexName));
client.admin().indices().prepareFlush(indexName);

Following is my mapping file
{
"profiles": {
 "dynamic" : "true",
 "_all": {
 "type": "string",
 "analyzer": "standard"
 },
 "properties": {
 "employee_id": {
 "type": "integer",
  "analyzer":"standard"
  }
}
}
}

Also note, only the dynamic property changes the rest all new updation on mappings dont get updated.
Is there any other way to update mappings using java code?


text:
Q: Sort WooCommerce product category sub menu items by name ASC in Wordpress menu I am adding in my main WordPress menu to WooCommerce product category menu items, the children subcategory terms as submenu items with the following code and it works.

The code:
add_filter("wp_get_nav_menu_items", function ($items, $menu, $args) {

    // don't add child categories in administration of menus
    if (is_admin()) {
        return $items;
    }
    foreach ($items as $index => $i) {

        if ("product_cat" !== $i->object) {
            continue;
        }
        $term_children = get_term_children($i->object_id, "product_cat");
        // add child categories
        foreach ($term_children as $index2 => $child_id) {
            $child = get_term($child_id);
            $url = get_term_link($child);
            $e = new \stdClass();
            $e->title = $child->name;
            $e->url = $url;
            $e->menu_order = 500 * ($index + 1) + $index2;
            $e->post_type = "nav_menu_item";
            $e->post_status = "published";
            $e->post_parent = $i->ID;
            $e->menu_item_parent = $i->ID;
            $e->type = "custom";
            $e->object = "custom";
            $e->description = "";
            $e->object_id = 0;
            $e->db_id = 0;
            $e->ID = 0;
            $e->position = 0;
            $e->classes = array();
            $items[] = $e;
        }
    }

    return $items;

}, 10, 3);

But I would like to sort that submenu items alphabetically in Ascending order and I didn't find a way to do it yet. How can I sort that submenu items by name (alphabetically) in Ascending order?

A: An additional foreach loop is required, to sort category sub menu items by name. Also there was some little oversights in your code (to avoid some errors). To finish you should always name your hooked functions for many different reasons.
The revisited code:
add_filter( 'wp_get_nav_menu_items', 'custom_submenu_product_categories', 10, 3 );
function custom_submenu_product_categories( $items, $menu, $args ) {
    // don't add child categories in administration of menus
    if (is_admin()) {
        return $items;
    }

    $taxonomy = 'product_cat';

    foreach ($items as $index => $post) {

        if ( $taxonomy !== $post->object ) {
            continue;
        }

        $children_terms_ids = get_term_children( $post->object_id, $taxonomy );
        $unsorted_terms     = array(); // Initializing

        // Loop through children terms to prepare them to be sorted by name
        foreach ( $children_terms_ids as $child_id ) {
            $child_term = get_term( $child_id, $taxonomy );

            $unsorted_terms[$child_term->name] = $child_term; // Set each term in an array for sorting
        }

        ksort($unsorted_terms); // Sort menu sub-items by term name ASC

        $index2 = 0; // Initializing

        // Loop through sorted child terms to set them as sorted sub menu items
        foreach ( $unsorted_terms as $child_term_name => $child_term ) {
            $item = new \stdClass();

            $item->title            = $child_term_name;
            $item->url              = get_term_link( $child_term, $taxonomy );
            $item->menu_order       = 500 * ($index + 1) + $index2;
            $item->post_type        = 'nav_menu_item';
            $item->post_status      = 'published';
            $item->post_parent      = $post->ID;
            $item->menu_item_parent = $post->ID;
            $item->type             = 'custom';
            $item->object           = 'custom';
            $item->description      = '';
            $item->object_id        = 0;
            $item->db_id            = 0;
            $item->ID               = 0;
            $item->position         = 0;
            $item->classes          = array();
            $item->target           = ''; // <= Missing - Mandatory to avoid an error
            $item->xfn              = ''; // <= Missing - Mandatory to avoid an error

            $items[] = $item;
            $index2++;
        }
    }
    return $items;
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.


text:
Q: How to get several processes to "chat" together? I am trying to simulate a 2-players game in bash. More precisely, there should be one central program (the game engine) and two player programs. The game engine should send the game info to player1, then get player1's output, then send the game info to player2, then get player2's output, and repeat.
If at all possible, I'd prefer the game engine not to be in charge of dispatching its outputs, and instead rely on a bash script to schedule the whole thing.
After reading stuff about named pipes, I figured that they were exactly what I needed, and came up with the following setup:
#!/bin/bash

trap "rm -f $in1 $in2 $out1 $out2 $in $out; kill $pid; kill $pid1; kill $pid2" KILL

in1=/tmp/testpipe_in1
in2=/tmp/testpipe_in2
out1=/tmp/testpipe_out1
out2=/tmp/testpipe_out2
in=/tmp/testpipe_in
out=/tmp/testpipe_out

for p in $in1 $in2 $out1 $out2 $in $out; do
    [[ -p $p ]] || mkfifo $p
done

echo 0 > $in
./center.sh < $in > $out &
pid=$!
./player1.sh < $in1 > $out2 &
pid1=$!
./player2.sh < $in2 > $out2 &
pid2=$!

i=0
while true; do
    i=$((i+1))
    echo "Round $i" >&2
    cat < $out > $in1
    cat < $out1 > $in
    cat < $out > $in2
    cat < $out2 > $in
done

I'm testing this with the following game and players:
center.sh:
#!/bin/bash

while true; do
    sleep 2
    read i
    echo "Center : $i $((i+2))" >&2
    echo $((i+2))
done

player1.sh:
#!/bin/bash

while true; do
    sleep 1
    read i
    echo "Player1 : $i $((i-1))" >&2
    echo $((i-1))
done

player2.sh:
#!/bin/bash

while true; do
    sleep 1
    read i
    echo "Player2 : $i $((i+1))" >&2
    echo $((i+1))
done

I expected it to output something like
Center : 0 2
Round 1
Player1 : 2 1
Center : 1 3
Player2 : 3 4
Center : 4 6
Round 2
Player1 : 6 5
...

... but of course it doesn't work.
Instead, I get:
Round 1
Center : 0 2
Center :  2
Center :  2
...

Is the problem something obvious in my players? Or what is the correct way to setup this kind of dispatch of inputs/outputs?

A: Here's some changes that may get you further on:

*

*there's a typo in your 1st script. It should be:
./player1.sh < $in1 > $out1 &

i.e. out1 not out2.

*

*move the echo 0 > $in to after starting the players.

*change the final while loop to:
  while true; do
      i=$((i+1))
      echo "Round $i" >&2
      read <&5; echo "$REPLY" >&6
      read <&7; echo "$REPLY" >&8
      read <&5; echo "$REPLY" >&9
      read <&4; echo "$REPLY" >&8
  done 5<$out 6>$in1 7<$out1 8>$in 9>$in2 4<$out2

Initially the reader of a fifo is blocked until a writer writes into
the fifo. Once the writer closes the fifo, the reader reads eof but is
no longer blocked so continues to read eof until the writer re-opens
the fifo and writes again.
You would need to check the return code of read and re-open the fifo
as the reader in order to block again.
You can see this easily with:
while sleep 1; do read;echo "$? $REPLY";done  <testpipe_out1 &
sleep 5
echo hi >testpipe_out1

The read will block until the "hi", then loop with return code "1".