text:
Q: Tests are passing in postman but not in newman I am creating postman tests to upload a csv file, when running my code in postman the test passes and I get a fileId as response.
However when running the same test in newman I got the following error :
I have also noticed that an other error is displayed :
Form param `file0`, file load error: "/C/Workspace/scf/scf-everything-shared/src/test/simulation/DDT/tests/files/Newman.csv", no such file

I have copied the file in the same fodler as my colection and used both absolute and relative path!
{
  "error": {
    "code": "UnsupportedMediaType",
    "message": "application/csv content type is not supported for this request. Supported media types are: multipart/form-data"
  }
}

As I am using form-data in body postman sets the content-type automatically but this triggered the error above.
I have also tried to set content type to application/csv instead but it still only passes in postman but not newman thanks for your help!

A: Sorry guys, I am launching a command from a docker container conataining newman.I should instead put the path referring the the file in my docker container after copying it (not in my localhost). After changing the path it works now.


text:
Q: How do I git clone a http repo behind a socks proxy? I can tunnel the ssh if I want to clone from a ssh repo, but what happens if I want to clone a http repo (accessible only via the socks proxy)?
For example, cloning https://git.repo.com/repo.git via socks proxy 127.0.0.1:1080.
I am currently using proxychains4 git clone to do this (setting proxy in proxychains conf). I know there is a global flag where to can change the global proxy setting for git but that is not desirable since I only would use it one time (I can change it back afterward but it feels less legit that way).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trouble importing images with Pillow / TCL struggles I'm getting some errors trying to use Pillow to import pictures that make me feel like I'm running in circles. My code follows the 'Toolbar' example here.
I got this error to start with:
objc[571]: Class TKApplication is implemented in both /System/Library/Frameworks/Tk.framework/Versions/8.5/Tk and /Library/Frameworks/Tk.framework/Versions/8.6/Tk. One of the two will be used. Which one is undefined.
objc[571]: Class TKMenu is implemented in both /System/Library/Frameworks/Tk.framework/Versions/8.5/Tk and /Library/Frameworks/Tk.framework/Versions/8.6/Tk. One of the two will be used. Which one is undefined.
objc[571]: Class TKContentView is implemented in both /System/Library/Frameworks/Tk.framework/Versions/8.5/Tk and /Library/Frameworks/Tk.framework/Versions/8.6/Tk. One of the two will be used. Which one is undefined.
objc[571]: Class TKWindow is implemented in both /System/Library/Frameworks/Tk.framework/Versions/8.5/Tk and /Library/Frameworks/Tk.framework/Versions/8.6/Tk. One of the two will be used. Which one is undefined.
Segmentation fault: 11

After looking at previous StackOverflow posts, I decided to uninstall version 8.6 to fix the version conflict. However, after I did that, I received this error since version 8.6 can no longer be found:
Traceback (most recent call last):
  File "untitled.py", line 66, in <module>
    main()
  File "untitled.py", line 61, in main
    app = Example(root)
  File "untitled.py", line 26, in __init__
    self.initUI()
  File "untitled.py", line 41, in initUI
    eimg = ImageTk.PhotoImage(self.img)
  File "build/bdist.macosx-10.6-intel/egg/PIL/ImageTk.py", line 115, in __init__
  File "build/bdist.macosx-10.6-intel/egg/PIL/ImageTk.py", line 180, in paste
  File "build/bdist.macosx-10.6-intel/egg/PIL/_imagingtk.py", line 7, in <module>
  File "build/bdist.macosx-10.6-intel/egg/PIL/_imagingtk.py", line 6, in __bootstrap__
ImportError: dlopen(/Users/Hanners 1/.python-eggs/Pillow-3.2.0-py2.7-macosx-10.6-intel.egg-tmp/PIL/_imagingtk.so, 2): Library not loaded: /Library/Frameworks/Tcl.framework/Versions/8.6/Tcl
  Referenced from: /Users/Hanners 1/.python-eggs/Pillow-3.2.0-py2.7-macosx-10.6-intel.egg-tmp/PIL/_imagingtk.so
  Reason: image not found

Any ideas would be appreciated!


text:
Q: Library feedback - for C++ I've written a new library, with an idea in it which I feel is fairly original. I'm looking for general feedback on it, and decided that I could submit to Boost- regardless of if it's rejected or accepted, I'd get some feedback. But I've checked the Boost site and it's seriously arcane, the whole mailing list thing is completely impenetrable.
Are there other library aggregation sites to submit to, or is it just Boost?

A: reddit.com/r/programming may be a good place to get some feedback.

A: You could post to any of a myriad of open-source hosting sites -- see this other question for recommendations:
https://stackoverflow.com/questions/10490/best-open-source-project-hosting-site


text:
Q: Can Schubert cells be defined, set theoretically, by less equations then the standard ones? Let $V = \mathbb{C}^n$ with basis $e_1,\dots,e_n$, and $U = \langle e_1,\dots,e_k\rangle$. Let
$$\Sigma(U)=\{\sigma\in Gr(V,2)\mid \sigma\in U \}$$
be the Schubert cell of $2$-planes contained in $U$. The equations for $\Sigma(U)$ are the Plucker relations, in addition to the relations
$$w_{ij}=0\quad 1\leq i\leq k, i< j\leq n$$
where $w_{ij}$ are the induced (by $e_1,\dots,e_n$) coordinates on $\wedge^2 V$. Write
$$K = \text{span}(w_{ij})_{1\leq i\leq k, i< j\leq n}\subset (\wedge^2 V)^*\subset \mathbb{C}[w_{ij}]_{1\leq i<j\leq n}.$$
Hence we write the ideal defining $\Sigma(U)$ as
$$I(\Sigma(U)) = P+\langle K\rangle$$
where $\langle K\rangle$ denotes the ideal generated by $K$, and $P$ is the ideal of Plucker relations. My question is the following: does there exist a subspace $L\subsetneq K$ such that
$$V(P+\langle L\rangle) = \Sigma(U)$$
($V(P+\langle L\rangle)$ denotes the variety defined by $P+\langle L\rangle$) or equivalently,
$$\sqrt{P+L}=P+K.$$
In other words, can we defined $\Sigma(U)$ as the intersection of $Gr(V,2)$ with a subspace larger then $V(K)$?
It is clear that we cannot leave out any of the $w_{ij}$, but I'm having a hard time proving that there is no such $L\subsetneq K$ at all.

A: The dimension of $Gr(V,2)$ is $2 (n-2)$.  For each point $x$ of $Gr(V,2)$ not in $\Sigma(U)$, the codimension of the space of subspaces $L$ that vanish on $x$ in the space of $m$-dimensional subspaces $L$ of $K$ is $m$. Hence the codimension of the space of subspaces $L$ that vanish on any point of $Gr(V,2)- \Sigma(U)$ is $m- 2(n-2)$. Thus as soon as $m> 2(n-2)$, there exists a suitable $L$. Because the dimension of $U$ is ${n \choose 2} - {k \choose 2}$, this is viable as soon as $2 \leq k \leq n-3$.


text:
Q: How to sort JavaScript Object with parent child tree I have the following JavaScript Object structure.
[
   [
      null,
      "A"
   ],
   [
      "A",
      "B"
   ],
   [
      "A",
      "C"
   ],
   [
      null,
      "D"
   ],
   [
      "D",
      "E"
   ],
   [
      "D",
      "F"
   ],
   [
      "B",
      "G"
   ]
]

And I need to sorting it to be the following structure.
[
   {

      parent: "A",
      child : [
         {
            parent : "B",
            child : [
               {
                  parent : "G"
               }
            ]

         },
         {
            parent : "C"
         }
      ]

   },
   {

      parent: "D",
      child : [
         {
            parent : "E"

         },
         {
            parent : "F"

         }
      ]

   }
]

A: Hope this helps you:
var a = [
   [
      null,
      "A"
   ],
   [
      "A",
      "B"
   ],
   [
      "A",
      "C"
   ],
   [
      null,
      "D"
   ],
   [
      "D",
      "E"
   ],
   [
      "D",
      "F"
   ],
   [
      "B",
      "G"
   ]
];

var result = [];

for(var iter = 0; iter < a.length; iter++){

  var ele = a[iter];

  // element has no parent
  if(!ele[0] || !getParentByName(result,ele[0])){
    result.push({ parent: ele[1]});
  }
  // element has got parent
  else if(ele[0] && getParentByName(result,ele[0])){

    var parent = getParentByName(result,ele[0]);

    if(!parent.child)parent.child=[];

    parent.child.push({ parent: ele[1]});

  }

}

function getParentByName(result,name){

  for(var p=0; p <result.length;p++){

    if(result[p].parent == name)return result[p];

    for(var c=0; result[p].child && c <result[p].child.length;c++){
      if(result[p].child[c].parent == name)return getParentByName(result[p].child,name);
    }

  }

}

console.log(result);

A: You can add parents in result tree in straightforward way. But for adding children you will have to use recursion. Refer following solution.
var result_tree = [];
var test_data = [
   [
      null,
      "A"
   ],
   [
      "A",
      "B"
   ],
   [
      "A",
      "C"
   ],
   [
      null,
      "D"
   ],
   [
      "D",
      "E"
   ],
   [
      "D",
      "F"
   ],
   [
      "B",
      "G"
   ]
];

function create_tree(test_data) {
  test_data.forEach(function (node) {
    // create new root parent node if node does not have any parent
    if (node[0] === null) {
      result_tree.push(
        {
          parent: node[1],
        }
      )
    }
    // else search for existing parent and attach child to it
    else {
      search_and_attach_child(result_tree, node[0], node[1]);
    }
  });
}

function search_and_attach_child(tree, parent, child) {
  if (!tree) {
    return;
  }
  tree.forEach(function (node) {
    if (node.parent === parent) {
      if (node.child) {
        node.child.push({parent: child})
      } else {
        node.child = [{parent: child}]
      }
    } else {
      search_and_attach_child(node.child, parent, child);
    }
  })
}

create_tree(test_data);
console.log(JSON.stringify(result_tree));


text:
Q: Not able to recieve the messages RabbitMQ I am following tutorial 4 (Routing). Following is the code for send.py
import pika
import sys

connection = pika.BlockingConnection(pika.ConnectionParameters(
        host='localhost'))
channel = connection.channel()

channel.exchange_declare(exchange='direct_logs',
                         type='direct')

severity = sys.argv[1] if len(sys.argv) > 1 else 'info'
message = ' '.join(sys.argv[2:]) or 'Hello World!'

channel.basic_publish(exchange='direct_logs',
                      routing_key=severity,
                      body=message)
print(" [x] Sent %r:%r" % (severity, message))
connection.close()

and below is the code for receive.py
import pika
import sys

connection = pika.BlockingConnection(pika.ConnectionParameters(
        host='localhost'))
channel = connection.channel()

channel.exchange_declare(exchange='direct_logs',
                         type='direct')

result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue

severities = sys.argv[1:]
if not severities:
    sys.stderr.write("Usage: %s [info] [warning] [error]\n" % sys.argv[0])
    sys.exit(1)

for severity in severities:
    channel.queue_bind(exchange='direct_logs',
                       queue=queue_name,
                       routing_key=severity)

print(' [*] Waiting for logs. To exit press CTRL+C')

def callback(ch, method, properties, body):
   print "Hello"
   print(" [x] %r:%r" % (method.routing_key, body))

channel.basic_consume(callback,queue=queue_name,no_ack=True)
channel.start_consuming()

But when I am running the scripts I'm unable to fetch any message from the temporary queue. I guess my callback function  is not being called. The  codes are taken as it is from the site.
I am running the codes as:
python send.py

for which I'm getting:
 [x] Sent 'info':'Hello World!'

And when I run
python rec.py info

I get:
 [*] Waiting for logs. To exit press CTRL+C

And else nothing is printed.
I have even restarted RabbitMQ using
rabbitmqctl stop_app
rabbitmqctl start_app

Please let me know where am I going wrong and how can I get message

A: run the receive.py first
the problem is, rabbitmq will not hold messages that are not routed to queues.
your send.py does not declare a queue or a binding to the exchange, so when you send a message through the exchange, there is no queue to which the message can be delivered
if you run your receive.py first, you'll create the needed exchange, queue and binding
then your send.py will be able to send the messages and it will be routed to the queue for the receive.py to pick up

A: If the code is exactly like in the tutorial, you need to run rec.py first and then send.py


text:
Q: match 2 properties' values in array of objects and filter matches based on a 3rd property's value I've got a graph with nodes that can be connected to multiple other nodes.
Every node represents an object in an array. Within every node's object is an array that contains the ids of all the nodes linked to this node and its depth:
 nodes: [
    {"id":1, "depth":0, "next":[], "children":[2, 3]},     // nodes.next = [2, 3]
    {"id":2, "depth":1, "next":[], "children":[1, 4, 5]},  // nodes.next = [4, 5]
    {"id":3, "depth":1, "next":[], "children":[1, 6, 7]},  // nodes.next = [6, 7]
    {"id":4, "depth":2, "next":[], "children":[2, 8]},     // nodes.next = [8]
    {"id":5, "depth":2, "next":[], "children":[2, 9]}      // nodes.next = [9]
]

I would like to traverse the graph from a certain node.
The problem is that a node's children array contains all the nodes linked to it. A node with a depth of 2 points back to a node with a depth of 1.
So I would like to create a new array within the nodes' objects, let's say nodes.next and get rid of the children that point back to a node that has a depth lower than itself.
The part that really baffles me is checking the depth of the nodes in nodes.children. I even haven't been near the part where I might check if the depth of a node in nodes.children is higher than nodes[i].depth and push nodes[i].children[i] to nodes[i].next.
If there is better way to solve this problem I'd be happy to know. My attemps have been fruitless in many ways alike:
let childDepth;
for (let i = 0; i < nodes.length; i++) {
    for (let child in nodes[i].children) {
        if (nodes.id === child) {
            childDepth = nodes[i].depth;
        }
        if (childDepth > graph.nodes[i].depth) {
            nodes[i].next.push(child)
        }
    }
}

Updated array:
const nodes = [
    { "id": 37, "depth": 0, "children": [210, 395, 265], "next": [] },
    { "id": 210, "depth": 1, "children": [37, 260, 259, 391],"next": [] },
    { "id": 256, "depth": 2, "children": [265], "next": [] },
    { "id": 259, "depth": 2, "children": [210, 397, 396], "next": [] },
    { "id": 260, "depth": 2, "children": [210], "next": [] },
    { "id": 265, "depth": 1, "children": [37, 256, 388, 394, 271, 269], "next": [] },
    { "id": 269, "depth": 2, "children": [265], "next": [] },
    { "id": 271, "depth": 2, "children": [265], "next": [] },
    { "id": 388, "depth": 2, "children": [265], "next": [] },
    { "id": 391, "depth": 2, "children": [210], "next": [] },
    { "id": 394, "depth": 2, "children": [265], "next": [] },
    { "id": 395, "depth": 1, "children": [37], "next": [] },
    { "id": 396, "depth": 3, "children": [259, 413], "next": [] },
    { "id": 397, "depth": 3, "children": [259], "next": [] },
    { "id": 413, "depth": 4, "children": [396], "next": [] }
];

A: Kindly take a look on the below code to see if it's what you're looking for
const array = [
  {id:1, depth:0, next:[], children:[2, 3]},
  {id:2, depth:1, next:[], children:[1, 4, 5]},
  {id:3, depth:1, next:[], children:[1, 6, 7]},
  {id:4, depth:2, next:[], children:[2, 8]},
  {id:5, depth:2, next:[], children:[2, 9]}
]

array.forEach(x => {
  let { children, depth } = x;

  for(let i=depth; i< children.length; i++){
    x.next.push(children[i]);
  }
});

Output as below:
[
  {"id":1,"depth":0,"next":[2,3],"children":[2,3]},
  {"id":2,"depth":1,"next":[4,5],"children":[1,4,5]},
  {"id":3,"depth":1,"next":[6,7],"children":[1,6,7]},
  {"id":4,"depth":2,"next":[],"children":[2,8]},
  {"id":5,"depth":2,"next":[],"children":[2,9]}
]


text:
Q: LinearModelFit: Standard error or Standard error of the mean on the slope UPDATED 02/14/16
Let me make this question clearer. Suppose each measurement that I make consists of three points, each with its own error governed by a normal distribution, on an XY plot. Obviously I can get a slope with just one measurement. I can use LinearModelFit to calculate the slope of such one measurement.
Now imagine if I do the same measurements ten times. I can fit for ten slopes. Each LinearModelFit will give me one slope with its error. If I take the mean and SD of the ten slopes, then I only have one averaged slope and one averaged SD.
My question about Mathematica is this. Is the error attributed to the slope the error of one measurement, or is it the error of the averaged slope? Or is it neither of these?
Question as originally posted
I have generated some data points for y = 2x equation. Both x and y have SD of 1 using normal distribution. Now, I can fit the result with LinearModelFit.
 data = {{15.4239559911589, 26.1913865426696}, {1.19200455227252, 1.57147919995481}, {0.760043460978471, -1.85757720391831}, {16.9897724167226, 31.4874783582698}, {11.0624581731998, 21.4927615949096}, {12.4329330755438, 27.1788226475715}, {8.02404253535088, 14.2996782674318}, {17.6582880470789, 32.3219364958568}, {7.5087634129172, 16.067137595272}, {19.1043041675387, 34.5777608701006}, {15.877354843904, 33.6898071105012}, {15.568644370401, 26.6368002511935}, {20.1439513327225, 39.175260292529}, {9.37214779884298, 16.6930629512215}, {14.8229986631303, 27.5584680484107}, {9.56505408355559, 19.8308073325376}, {15.1618882940615, 35.2641818884374}, {3.56408341892867, 6.04027362213018}, {8.09634158598029, 15.8824802631668}, {3.87278838752738, 9.29890330741694}, {20.2006381926558, 41.0156521737783}};
model = LinearModelFit[data, x, x];
model["ParameterTable"]

This yields
.
My question: The standard error reported by the fit. Is it the standard error of ONE measurement, or is it the standard error of the mean?
That is, if I do the same "measurements" again and try to find the slope, would one measurement gives me an SD error of 0.0913537 (and the mean error is smaller by a factor of $1/\sqrt{n}$), or would the MEAN of many measurements gives me an SD error of 0.0913537?
I'm not very solid on Statistics. This question might be more appropriate on other StackExchange forums. But since it involves how Mathematica implements linear fit, I hope I might be able to get some help here.
Data points can be found in CSV format here


text:
Q: WP redirects all pages from new domain to old domain I've moved my Wordpress installation from my development domain to the live domain, but it keeps redirecting every page back to the old (dev) domain.
So far I've:

*

*Added
define('WP_HOME', 'http://example.com']);
define('WP_SITEURL', 'http://example.com');
to 'wp-config.php'

*Edited the 'siteurl' and 'home' entries in 'wp-options' in the database.

*Re-downloaded the database and replaced every mention of the old URL with the new URL, then deleted the (live) database and imported the new one.

*Checked '.htaccess' for any redirects/rewrites.

*Cleared browser cache and server cache (multiple times - after each previous step).
It still redirects every page to the dev-url. For example, if I type in
'new-url.com/post-123'
it redirects me to
'dev-url.com/post-123'
The only thing that works is visiting 'new-url.com/wp-login.php', that way I have access to the backend. The site-/homeurls in the backend are set to 'new-url.com'.
What have I missed? Thanks in advance!
Edit: I had Q-Translate X set up to have a different domain for each language, that's what kept redirecting me to the old site. I don't know if Q-Translate saves settings in the DB, if not that would be why nothing else helped. Thanks for all the help guys!

A: How did you search the database entries of the old domain? If you did it manually i recommend to use wp-cli if you are allowed to install it on the server. Then you can use the command wp search-replace --all-tables "old.domain" "new.domain" (documentation) to replace your domain everywhere in the database.
Edit No.1:

Another possibility: did you changed the database settings to the new database in wp-config.php?
Edit No.2:

Did you cleared (resaved) your permalinks (Settings->Permalinks)?

A: This is maybe weird to say but did you change the home url in your backend?
Because Wordpress uses that URL. Settings-->general--> Wordpress-adres(URL) and Website-adres(url)
Also when you echo the website url on a page of your choice , what do you see?
Edit
The next Wordpress page has everything you need to know about changing your URL
Wordpress changing home URL
OPTION 1
Make sure you don't have wp-config.php with defined url's and edit the URL's in the backend like said above here.
OPTION 2
Define them hard coded in the wp-config.php like this :
define('WP_HOME','http://example.com');
define('WP_SITEURL','http://example.com');

Option 3
Edit your functions.php right after the <?php use this :
update_option( 'siteurl', 'http://example.com' );
update_option( 'home', 'http://example.com' );

Option  4

*

*Edit your wp-config.php fille and put in :
define('RELOCATE',true);
After the "define" statements (just before the comment line that says "That's all, stop editing!"), insert a new line, and type: define('RELOCATE',true);

*Open a web browser and manually point it to wp-login.php on the new server. For example, if your new site is at http://www.yourdomainname.com, then type http://www.yourdomainname.com/wp-login.php into your browser's address bar.

*Login as per normal.

*Look in your web browser's address bar to verify that you have, indeed, logged in to the correct server. If this is the case, then in the Admin back-end, navigate to Settings > General and verify that both the address settings are correct. Remember to Save Changes.

*Once this has been fixed, edit wp-config.php and either completely remove the line that you added (delete the whole line), comment it out (with //) or change the true value to false if you think it's likely you will be relocating again.
Note: When the RELOCATE flag is set to true, the Site URL will be automatically updated to whatever path you are using to access the login screen. This will get the admin section up and running on the new URL, but it will not correct any other part of the setup. Those you will still need to alter manually.
Source : Wordpress changing site url

A: It looks like some of your old site links are there in the database. Thats why it is redirecting to the users to the old site.
My suggestion would be use this
https://interconnectit.com/products/search-and-replace-for-wordpress-databases/
Its a kind of php script. Be sure to keep the database backup before using it. This script will make search and replace the strings from the database. After that just update your permalinks.
Hope this will help you.

A: With this plugin you can search and replace. They have an option for changing site URLs. I hope that it helps. https://nl.wordpress.org/plugins/search-and-replace/


text:
Q: MYSQL - Insert result of concat of multiple rows based on ID I've searched and searched but I think I'm missing something. What I'm trying to accomplish is saving the result of a concat on a single table where multiple rows are combined based on ID.
My table has only 3 columns:
ID - Order_items_id - Customization
The ID is unique but will not matter in the long run.
What I want to accomplish is to concat all rows with the same order_item_id. The concat would only apply to customizations.
An example of my table:
ID - order_item_id - customization
0    1231            19;1
1    1231            75;1
2    2345            10;5

I can get my result to show up the way I want via the following query:
SELECT `order_item_id`, group_concat(`customizations` separator ';')
FROM `ojs_order_ing_export`
GROUP BY `order_item_id`

ID - order_item_id - customization
0    1231            19;1;75;1
2    2345            10;5

Now I'm a bit stumped as to how I can insert the result of this query in a 3rd column, or update the customization column to save the results of the concat query.
The goal of this is to group all data in customization based on order_item_id into a single row so I can then join customization column with another table.
Thank you in advance.

A: I'm not sure that i absolutely understood your goal, but looks like you should so somemthing like INSERT-SELECT statement:
INSERT INTO my_new_table (order_item_id, order_item_customizations)
SELECT `order_item_id`, group_concat(`customizations` separator ';')
FROM `ojs_order_ing_export`
GROUP BY `order_item_id`

or, for example
CREATE TABLE my_new_table
SELECT `order_item_id`, group_concat(`customizations` separator ';')
FROM `ojs_order_ing_export`
GROUP BY `order_item_id`

If you want to have the same table but with "merged" values – just swap original and new table.


text:
Q: Very slow writing of a dataframe to file on Spark cluster I have a test program that writes a dataframe to file. The dataframe is generated by adding sequential numbers for each row, like
1,2,3,4,5,6,7.....11
2,3,4,5,6,7,8.....12
......

There is 100000 rows in the dataframe, but I don't think it is too big.
When I submit the Spark task, it takes almost 20 minutes to write the dataframe to file on HDFS. I am wondering why it is so slow, and how to improve the performance.
val sc = new SparkContext(conf)
val sqlContext = new org.apache.spark.sql.SQLContext(sc)
val numCol = 11

val arraydataInt = 1 to 100000 toArray
val arraydata = arraydataInt.map(x => x.toDouble)
val slideddata = arraydata.sliding(numCol).toSeq
val rows = arraydata.sliding(numCol).map { x => Row(x: _*) }
val datasetsize = arraydataInt.size

val myrdd = sc.makeRDD(rows.toSeq, arraydata.size - numCol).persist()

val schemaString = "value1 value2 value3 value4 value5 " +
                   "value6 value7 value8 value9 value10 label"

val schema =
StructType(schemaString.split(" ").map(fieldName => StructField(fieldName, DoubleType, true)))

val df = sqlContext.createDataFrame(myrdd, schema).cache()

    val splitsH = df.randomSplit(Array(0.8, 0.1))
val trainsetH = splitsH(0).cache()
val testsetH = splitsH(1).cache()

println("now saving training and test samples into files")

trainsetH.write.save("TrainingSample.parquet")
testsetH.write.save("TestSample.parquet")

A: Turn
val myrdd = sc.makeRDD(rows.toSeq, arraydata.size - numCol).persist()

To
val myrdd = sc.makeRDD(rows.toSeq, 100).persist()

You've made a rdd with arraydata.size - numCol partitions and each partition would lead to a task which takes extra run time. Generally speaking, the number of partitions is a trade-off between the level of parallelism and that extra cost. Try 100 partitions and it should works much better.
BTW, the official Guide suggest to set this number 2 or 3 times the number of CPUs in your cluster.


text:
Q: How does +xp per kill on a follower works When I equip a +xp per kill item on a follower, How is the extra xp gained? I've read already that I'll get only 20% of the bonus (so a +5xp will become +1xp) but, will I get it for every kill made by both of us (the player and the follower) or will it be given only for kills done by the follower?

A: All kills by the follower act exactly the same as monsters you've killed yourself.  What that means is that you take 20% of the follower's bonus, add it to your's, and then apply that to all kills done by either of you.

A: See: Do I ever get xp for my party member's kills?
As for the fixed number in experience items ("+5 xp") I believe that adds an extra 5 points of experience with each kill


text:
Q: What vs. which as relative pronouns in relative clauses When are you supposed to use "what" vs. "which" as a relative pronoun in a relative clause?
According to Purdue's Online Writing Lab:

The most common relative pronouns are who/whom, whoever/whomever, whose, that, and which. (Please note that in certain situations, "what," "when," and "where" can function as relative pronouns.)

But it doesn't mention when you should use "what" in that particular role.
Some other examples are:

Where did you buy the dress what you wore last week?
You're that smart banker what killed his wife.

There was an ESL quiz from Singapore where "what" filled in the blank in the following sentence (and "which" was explicitly marked incorrect by the teacher):

This orchestra, ______ these musicians are from, is very good.

According to "First Book in English Grammar" in 1868:

The pronoun what is a relative, when equivalent to that which; when not, it is an interrogative.

Did this use of the pronoun "what" become "officially" ungrammatical at some point?

A: I suspect that the quiz was just marked incorrectly: "This orchestra, what these musicians are from, is very good" is certainly not possible in standard English. The use of "what" as a relative pronoun in relative clauses that come directly after an antecedent nominal phrase, e.g. in sentences like "You're that smart banker what killed his wife", certainly exists, but is dialectal and considered non-standard, as mentioned in WS2's answer here.
I think the Purdue Writing Lab's statement that "in certain situations, 'what,' 'when,' and 'where' can function as relative pronouns" refers to "fused relative" constructions. You can find some information on those in the answers to the following questions: Usage of "what", Wh- clauses vs Relative clauses, Ambiguity of "I don't know what you know.", "What might have appalled us when we'd started our trip just a few days ago no longer impressed us much".


text:
Q: Volatile writes reorder with non volatile writes Does volatile writes are reordered with non volatile writes.
For Ex:
I have two threads T1 and T2:
T1:
i = 10;
volatile boolean result = true;

T2:
while(!result){
}

System.out.println(i);

Does T2 always see the updated value of i(10) or old value?

A: Yes. There is a happens-before relationship for a volatile statement:
Please consider this stackoverflow question: Does Java volatile variables impose a happens-before relationship before it is read?

A write to a volatile field happens-before every subsequent read of
  that same field. Writes and reads of volatile fields have similar
  memory consistency effects as entering and exiting monitors, but do
  not entail mutual exclusion locking.

Also you can read section 3.1.3 (Locking and visbility) in the great book called "Java Concurrency in Practice". There is a relevant explanation there about a similar visibility issue and the outline is this:

Locking is not just about mutual exclusion; it is also about memory visibility.To ensure that all threads see the most up to date values of shared mutable variables, the reading and writing threads must synchronize on a common lock

In your code the lock is the volatile variable

A: As far as I understand it, this is correctly synchronized, so no races occur and 10 is always printed.
The important parts are that within a thread, things occur in program order, and that writes to a volatile variable happen before reads that see that value. Together with the transitive closure rule, this means that the assignment to i happens before the print statement.
i = 10 happens before result = true. result = true happens before result is read as true in thread 2. result is read as true happens before System.out.println(i);. Therefore, i = 10 happens before System.out.println(i);.


text:
Q: PHP. Consulta a Base de datos MySQL no devuelve resultado Obtengo el nombre de una Impresora ingresado por el usuario en un formulario y lo utilizo para saber su ID usando:
$query = mysqli_query($conexion, "SELECT IdImpresora
                                    FROM impresoras
                                    where modelo like '%".$busqueda."%'");

$IdImpresora = mysqli_fetch_array($query);

Ahora trato de usar el ID de la Impresora para obtener un array con los ID de los Toner que son compatibles con esta Impresora en la tabla comp utilizando:
$query2 = mysqli_query($conexion, "SELECT IdCartucho
                                    FROM comp
                                    WHERE IdImpresora = '%".$IdImpresora['IdImpresora']."%'");

$listID = array();
while($row = mysqli_fetch_array($query2)){
    $listID[]=$row['IdCartucho'];
}

No obtengo ningún resultado. Esperaba obtener {3,6,7,8,10,13}
Intente obteniendo el valor entero de $IdImpresora antes de hacer el el query usando:
$IdImpresora = intval($IdImpresora['IdImpresora']);

posteriormente mi query quedo de esta forma:
$query2 = mysqli_query($conexion, "SELECT IdCartucho
                                    FROM comp
                                    WHERE IdImpresora = '%".$IdImpresora['IdImpresora']."%'");

Aun sin resultado.
Probe este query en la consola de MySQL:
select IdCartucho from comp where IdImpresora = 1;

El resultado fue {3,6,7,8,10,13} tal como esperaba
1 es el valor que devuelve el primer query y es también el valor que paso en mi segundo query pero sin obtener resultado.
Al ejecutar el documento no obtengo ningún error.
Supongo el error esta en $query2 pero no se que puede ser.
Necesito el array con los ID de los toner para las operaciones que haré mas adelante.

A: El problema está en que busca un ID que sea string y sin embargo, es un entero. Prueba quitando las comillas del WHERE que hacen referencia al ID:
$query2 = mysqli_query($conexion, "SELECT IdCartucho
                                    FROM comp
                                    WHERE IdImpresora = ".$IdImpresora['IdImpresora']);


text: Q: Looking for a way where I can invoke a Chrome Browser on Remote windows server There are no resources available on the windows server apart from powershell and was looking for a way if it is possible to RDP to the windows server using Python and Selenium from the local machine and then perform some actions on the Chrome browser in the Remote Windows Server


text:
Q: Custom Button background is being drawn wrong (sometimes) I have this custom button, which does not draw himself and has no child views. Right after app launch it looks like this:

At this point I don't know what code and details might be relevant for posting here. The fact is after the app changes state the button checks whether to stay VISIBLE or go INVISIBLE. It remains VISIBLE. It calls setVisibility(View.VISIBLE) and after that, when the screen shows again, it looks like this:

If I click the button it returns to be fine with its original background dimensions.
What have I done so far
I have debugged the code down to android sources.
First onDraw(); I only call there super.onDraw(); and it seems to deal only with the text and not the background, and if so, it works OK, since the text is still positioned and dimensioned as before.
Second onMeasure(); here too I only call super.onMeasure();; it is called several (11) times before showing for the first time and it is called 5 times after setVisibility(); it is not called at all when I click the button.
Third onTouchEvent(), called when I click the button. It sets a different color background for ACTION_DOWN and restores the original color background on ACTION_UP
@Override
protected void onDraw(Canvas canvas) {
    Log.d(TAG + " " + getText(), "+ onDraw(canvas:" + canvas + ")");
    super.onDraw(canvas);
    Log.d(TAG + " " + getText(), "- onDraw()");
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    Log.d(TAG + " " + getText(), String.format("+ onMeasure(widthMeasureSpec:%x, heightMeasureSpec:%x)", widthMeasureSpec,heightMeasureSpec));
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    Log.d(TAG + " " + getText(), String.format("- onMeasure(): width=%d, hieght=%d", getMeasuredWidth(), getMeasuredHeight()));
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    Log.d(TAG + " " + getText(), "+ onTouchEvent(event:" + event + ")");
    super.onTouchEvent(event);

    if( clickable ) {
        if( event.getAction() == MotionEvent.ACTION_UP ) {
            setBackgroundDrawable(normalBackground);
            clickUp.soundPlay();
        } else if( event.getAction() == MotionEvent.ACTION_DOWN ) {
            setBackgroundDrawable(pressedBackground);
            clickDown.soundPlay();
        }
    }

    Log.d(TAG + " " + getText(), "- onTouchEvent()");
    return true;
}

/**
 * Sets the MyButton visible if stateFlags matches.

 * @param stateFlags The current app state.

 */
public void setState(int stateFlags) {
    Log.d(TAG + " " + getText(), "+ setState(stateFlags:" + stateFlags + ")");
    if( state == stateFlags || state == State.NORMAL) {
        setVisibility(View.VISIBLE);
        Log.d(TAG + " " + getText(), "state(" + state + ") VISIBLE before was " + getVisibility());
    } else {
        setVisibility(View.INVISIBLE);
        Log.d(TAG + " " + getText(), "state(" + state + ") INVISIBLE before was " + getVisibility());
    }
    requestLayout();
    Log.d(TAG + " " + getText(), "- setState()");
}

@Override
protected int[] onCreateDrawableState(int extraSpace) {
    Log.d(TAG + " " + getText(), "+ onCreateDrawableState(extraSpace:" + extraSpace + ")");
    Log.d(TAG + " " + getText(), "- onCreateDrawableState()");
    return super.onCreateDrawableState(extraSpace);
}

these are the logs for the button:
*** Beggining - first show ***
+ onMeasure(widthMeasureSpec:800002b8, heightMeasureSpec:800003aa)
- onMeasure(): width=200, hieght=125
+ onMeasure(widthMeasureSpec:40000099, heightMeasureSpec:800003aa)
- onMeasure(): width=153, hieght=125
+ onMeasure(widthMeasureSpec:800002b8, heightMeasureSpec:80000152)
- onMeasure(): width=200, hieght=125
+ onMeasure(widthMeasureSpec:40000099, heightMeasureSpec:80000152)
- onMeasure(): width=153, hieght=125
+ onMeasure(widthMeasureSpec:800002b8, heightMeasureSpec:80000035)
- onMeasure(): width=200, hieght=53
+ onMeasure(widthMeasureSpec:40000099, heightMeasureSpec:80000035)
- onMeasure(): width=153, hieght=53
+ onSizeChanged(w:153, h:53, oldw:0, oldh:0)
- onSizeChanged()
+ onLayout(changed:true, left:12, top:3, right:165, bottom:56)
- onLayout()
+ onMeasure(widthMeasureSpec:800002b8, heightMeasureSpec:80000035)
- onMeasure(): width=200, hieght=53
+ onMeasure(widthMeasureSpec:40000099, heightMeasureSpec:80000035)
- onMeasure(): width=153, hieght=53
+ onLayout(changed:false, left:12, top:3, right:165, bottom:56)
- onLayout()
+ onDraw(canvas:android.view.Surface$CompatibleCanvas@b3e434b0)
+ onCreateDrawableState(extraSpace:0)
- onCreateDrawableState()
- onDraw()

*** App changes state - button shows wrong ****
+ setState(stateFlags:2)
state(1) VISIBLE before was 0
- setState()
+ onMeasure(widthMeasureSpec:800002b8, heightMeasureSpec:80000152)
- onMeasure(): width=200, hieght=125
+ onMeasure(widthMeasureSpec:800002b8, heightMeasureSpec:80000035)
- onMeasure(): width=200, hieght=53
+ onMeasure(widthMeasureSpec:40000099, heightMeasureSpec:80000035)
- onMeasure(): width=153, hieght=53
+ onLayout(changed:false, left:12, top:3, right:165, bottom:56)
- onLayout()
+ onDraw(canvas:android.view.Surface$CompatibleCanvas@b3e434b0)
- onDraw()

*** I am about to click the button, return to show fine ***
+ onTouchEvent(event:MotionEvent { action=ACTION_DOWN, id[0]=0, x[0]=61.0, y[0]=36.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=2879242, downTime=2879242, deviceId=0, source=0x1002 })
- onTouchEvent()
+ onDraw(canvas:android.view.Surface$CompatibleCanvas@b3e434b0)
+ onCreateDrawableState(extraSpace:0)
- onCreateDrawableState()
- onDraw()
+ onTouchEvent(event:MotionEvent { action=ACTION_UP, id[0]=0, x[0]=61.0, y[0]=36.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=2879342, downTime=2879242, deviceId=0, source=0x1002 })
- onTouchEvent()
+ performClick()
- performClick()
+ onDraw(canvas:android.view.Surface$CompatibleCanvas@b3e434b0)
+ onCreateDrawableState(extraSpace:0)
- onCreateDrawableState()
- onDraw()

More details will be posted on demand, if deemed relevant.

A: I found a bypass!, though I would like very much to understand what is really the problem.
The bypass is:
@Override
protected void onDraw(Canvas canvas) {
    // This is a bypass for the problem of partial background redraw.
    // The problem causes are not understood yet.
    // But setting mBackgroundSizeChanged = true; in View causes the next Draw to be OK
    onScrollChanged(0, 0, 0, 0);
    super.onDraw(canvas);
}

The ultimate bypass line is (View.class):
mBackgroundSizeChanged = true;

But mBackgroundSizeChanged is not accessible from derived classes, and it has no setter per se. So I found the closest thing to a setter there is: onScrollChanged(); it does set mBackgroundSizeChanged = true and in my case is all it does. Check the few source code lines in TextView.class and View.class to see if in your case it does other stuff.
Old Bypass (still works  but executes more unecessary lines):
Right after I change the visibility of a button I added these lines:
Drawable d = cb.getBackground();
cb.setBackgroundDrawable(null);
cb.setBackgroundDrawable(d);

And it solved the problem, now the button retains its background.
Explanation how I got there
This forces the button background to reset itself. I did look at the source of setBackgroundDrawable() trying to understand what code in there is making the difference. I first noticed that had to set the background to null first and reset it afterwards to force a redo.
Further debug reduced the difference to:
mBackgroundSizeChanged = true;

In the lasts code lines of setBackgroundDrawable()


text:
Q: Can you use class template argument deduction when the class is template parameter of another template? I tried to write code like this:
#include <string>
#include <vector>
#include <utility>

using namespace std::string_literals;
int main(){
    std::vector v{1,2,3};
    std::pair p{1,"a"s};
    //std::vector<std::pair> vp{{1,"a"s}, {2, "b"s},{3,"c"s}};  // ERROR
}

But it gives compile error in the line where pair is a template parameter of vector.
Is there a way to get class template deduction to work here or do I need to specify template parameters for pair?

A: This is not supported at the moment. From [dcl.type.class.deduct]p2:

A placeholder for a deduced class type can also [in variable declarations too as type] be used in the type-specifier-seq in the new-type-id or type-id of a new-expression, or as the simple-type-specifier in an explicit type conversion (functional notation). A placeholder for a deduced class type shall not appear in any other context.

As you can see from the sentence I highlighted, because your use does not match any of the places mentioned above, your code is ill-formed.
You could do something like this:
std::vector vp{std::pair{1, "a"s}, {2, "b"s}, {3, "c"s}};


text:
Q: Is it really secure to call static class method from view? I am working on Mvc 4 web application. I have a static class which contains static methods. Suppose I have Demo.UserHelper.GetUserName() this method from class UserHelper.
Is it really secure to call this method from view?
Edit
Basically from these methods I am retrieving some data from DB. The security is related to hacking. We are calling a class method from view. Is this really safe?

A: Since as in your comment you say that your concern is hacking, that is the view is calling a class method which gets things from database.
Well, let me assure you that your fears are not valid. What happens is when a user makes a call your website, the MVC framework first thing figures out the route, so it knows which controller and method to call, then the action method prepares its model and viewbag, and calls a view (we are still on server side and your end user can't see anything) .. your view is a cshtml file which is basically html mixed with code (this is pretty normal) the MVC view engine renders your view as pure html and returns the result to the customer. So the customer only sees your html results and have no access to any of your code (unless you have javascript on the page, ofcourse the end user will be able to see it).
You might consider reading a bit more about http protocol in general, and then read about the MVC framework and how it works to help you better understand the round trips between client and server.
I hope this helps.
Edit:
Regarding the notification you need to pull. if it does get updated frequently, you might consider building it as API service, and having the page make a javascript call to get the latest notifications periodically (or maybe add refresh notification button to user)


text:
Q: "LapackError: Parameter a has non-native byte order in lapack_lite.dgesdd" when importing from Matlab files After importing this data file from Matlab with scipy.io.loadmat, things appeared to work fine until we tried to calculate the conditioning number of one of the matrixes within.
Here's the minimum amount of code that reproduces for us:
import scipy
import numpy

stuff = scipy.io.loadmat("dati-esercizio1.mat")
numpy.linalg.cond(stuff["A"])

Here's the extended stacktrace courtesy of iPython:
In [3]: numpy.linalg.cond(A)
---------------------------------------------------------------------------
LapackError                               Traceback (most recent call last)
/snip/<ipython-input-3-15d9ef00a605> in <module>()
----> 1 numpy.linalg.cond(A)

/snip/python2.7/site-packages/numpy/linalg/linalg.py in cond(x, p)
   1409     x = asarray(x) # in case we have a matrix
   1410     if p is None:
-> 1411         s = svd(x,compute_uv=False)
   1412         return s[0]/s[-1]
   1413     else:

/snip/python2.7/site-packages/numpy/linalg/linalg.py in svd(a, full_matrices, compute_uv)
   1313         work = zeros((lwork,), t)
   1314         results = lapack_routine(option, m, n, a, m, s, u, m, vt, nvt,
-> 1315                                  work, -1, iwork, 0)
   1316         lwork = int(work[0])
   1317         work = zeros((lwork,), t)

LapackError: Parameter a has non-native byte order in lapack_lite.dgesdd

All obvious ideas (like flattening and reshaping the matrix or recreating the matrix from scratch reassigning it element by element) failed. How can I want to massage the data, then, in order to make it more agreeable with numpy?

A: It's a bug, fixed some time ago: https://github.com/numpy/numpy/pull/235
Workaround:
np.linalg.cond(stuff['A'].newbyteorder('='))

A: This works for me:
In [33]: stuff = loadmat('dati-esercizio1.mat')

In [34]: a = stuff['A']

In [35]: try: np.linalg.cond(a)
   ....: except: print "Fail!"
Fail!

In [36]: b = np.array(a, dtype='>d')

In [37]: np.linalg.cond(b)
Out[37]: 62493201976.673141

In [38]: np.all(a == b)  # Verify they hold the same data.
Out[38]: True

A: Apparently it's something wrong with the byte order (endianness?) of each number in the resulting ndarray and not just with the ndarray object itself.
Something like this but more elegant should do the trick:
n, m = A.shape()
B = numpy.empty_like(A)

for i in xrange(n):
  for j in xrange(m):
    B[i,j] = float(A[i,j])

del A
B = A

print numpy.linalg.cond(A) # 62493210091.354507

(For some reason an in-place replacement still gives that error - so there's something wrong with the byte order of the whole object, too.)


text:
Q: Adding product variations with multiple attributes I am using the WoocommerceNET Library (Nuget Link) to develop a desktop app that will sync the products from the ERP database to the Woocommerce eshop database.
I added attributes size and color with values eg red,green,blue and s,m,l,xl. Now I need to create the variations.
Tried this:
  List<VariationAttribute> vatrib = new List<VariationAttribute>()
            { new VariationAttribute() { name="Color",option="GREEN" },
              new VariationAttribute() { name="size",option="L" } };

       Variation var = new Variation() {
                             regular_price=1.0M,
                             visible=true,
                             attributes=vatrib,
                             stock_quantity=5,
                             manage_stock=true
                        };
       //... repeat for each variation ....

       List<Variation> varis = new List<Variation>();
       varis.Add(var);
       varis.Add(var1);
       varis.Add(var2);  ... and so on for all variations

       Product p = new Product()
                {
                    //options ....
                    type = "variable",
                    manage_stock = true,
                    in_stock = true,
                    attributes=attribs,
                    variations=varis,
                };
                await wc.Product.Add(p);

But i get an error

Cannot implicitly convert type
  'System.Collections.Generic.List < WooCommerceNET.WooCommerce.v2.Variation >'
  to 'System.Collections.Generic.List < int >'

It looks like the variation attribute of Product is a List that contain the variations ids.
How can I add a new product with variations for color and size?

A: Create the product. Create the variation with the product id.
Product p = new Product()
{
    //options ....
    type = "variable",
    manage_stock = true,
   in_stock = true,
    attributes=attribs,
    //variations=varis,
};

//Returns the new product with the id.
p = await wc.Product.Add(p);

//Returns the new variation with the id
var1 = wc.Product.Variations.Add(var1, p.id.Value);

// Add the variation id to the product
p.Variations.Add(var1.id.Value);

//Update the product
wc.Product.Update(p.id.Value, p);


text:
Q: How can WordPress and YOURLS peacefully coexist at the root level? I want to make a better link shortener service using YOURLS. I've procured a short URL for this: sly.pe.  YOURLS is installed and sly.pe/admin is accessible.
I'd also like to use WordPress to power most of the consumer facing site, at the URL: sly.pe.  The idea being I want users to register for the site using WordPress and a registration plugin like OneAll social.  Once authenticated they get logged in for both YOURLS and WordPress and are redirected to a URL like sly.pe/home that uses WordPress as the site but YOURLS (sly.pe/admin for that user) is embedded and accessible somehow.
Both services make .htaccess changes.  If I leave the file as is, I can't seem to have any other WordPress URL other than sly.pe, but YOURLS works fine.  If I comment out some YOURLS code, WordPress can use other directories, but then YOURLS doesn't work.  How can I have both coexist nicely?  Or at least define the WordPress URLs I want and get those working?
(commenting out the YOURLS code gets WordPress working, but breaks YOURLS):
.htaccess:
# BEGIN YOURLS
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /yourls-loader.php [L]
</IfModule>
# END YOURLS

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

A: I was able to get YOURLS to work with WordPress. Here's how I did it...
I've placed YOURLS in niemannross.com/links - so for me, a redirect looks like http://niemannross.com/link/rlunchlessons
Install the Redirection plugin by John Godley in your copy of WordPress.
Look in Wordpress:Admin:Tools:Redirection. Across the top are several tabs. You should see Redirects | Groups | Logs | 404s | Import/Export | Options | Support.
Choose Redirects
Select Add New Redirection
Source URL: /link/.* - Select Regex.
Target URL: /link/yourls-loader.php
Group: Whatever makes sense in your setup. I've chosen wordpress:redirections
This works for my installation.

A: Simple answer is: you cannot. Both WordPress and YOURLS (please, YOURLS, not YourLS) need to process server requests to return the expected result (eg when requesting http://sho.rt/blah, each app needs to check if blah is content it manages)
Long answer: you should not because all of the following.
Basically you would need something that works when:

*

*blah is an WP article but not a YOURLS short URL

*blah is a YOURLS short URL but not an WP article

*blah is neither a WP article or a YOURLS short URL

*optionally decide what to do when blah is both a WP article and a YOURLS short URL

Your code would also need to :

*

*prevent WP to create a "slug" that is already a YOURLS short URL

*prevent YOURLS to create a short URL that already matches a WP slug

You'd need to have code for this both in the WP area and in the YOURLS area.
Bottom line: lots of edge cases to deal with. What might work in some case on your side might not work in other cases, on your side or with others.

A: I think you're going to have to work around the problem as mentioned by @Ozh, but here's a plugin that will make it easier for your WordPress users to use YOURLS: https://wordpress.org/plugins/yourls-link-creator/

A: You cannot, I tried different ways, maybe with new apache 2.4 using the if else statement you will, but I am not an expert on those commands, I want to share what I did to have the shortener option in the root page and the html site in a subdirectory, with this solution you can still give people normal url for the website (e.g. sho.rt):
set your website in a folder under root with a name e.g. "w", that means it will be at "sho.rt/w"
then use this .htaccess
# BEGIN YOURLS
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^.*$ /yourls-loader.php [L]
    RewriteRule ^$ /w [L]
</IfModule>
# END YOURLS

This will give you the option to still use sho.rt as your website address if the user doesn't pass any subfolder in the url, but if they do, it will check in yourls first and go to your folders if nothing found.
One more thing, do not forget to add "w" in the $yourls_reserved_URL array in /user/config.php (Yourls config file)

A: I finally solved this for my website.
I have a subdomain http://sub.domain where I installed YOURLS, but the short URLs are at http://domain/someshortlink
And the wordpress website is also at http://domain/
It used to work with the swap plugin ( https://github.com/gerbz/Yourls-Swap-Short-Url ).
Just with the htaccess provided by that YOURLS plugin, and no wordpress. But since I decided to move to wordpress, this combination won't work.
Here is the trick:

*

*On your htaccess, keep it simple, as wordpress wants it to be. Remove the snippet htaccess for the YOURLS swap plugin, if you have it added.

*Edit your 404.php page theme. Mine was at: wp-content/themes/twentynine/404.php
At the very begin, just add:
<?php
header('Location: http://sub.domain' . $_SERVER['REQUEST_URI'] );
exit;
?>

This will allow:

*

*All files and directories will honor the basic htaccess from which they are simply served

*All URLS not files and folders will be handled by wordpress in the usual manner.

*If a page is not found, wordpress will trigger 404.php which will send that page to YOURLS to try

*If YOURLS also don't find it, a 404 page from YOURLS will show.

Remember to edit the 404 page from YOURLS also, to match your wordpress theme.
Best of luck!
Reference: https://github.com/gerbz/Yourls-Swap-Short-Url/issues/11


text:
Q: Image will not resize to fit window, all other fixes make the image disappear - React Native I'm having an issue with React Native.  I'm trying to put an image as a header, which needs to resize itself responsively to fit inside of the viewport and be centred horizontally.
Unfortunately, I'm unable to produce any sort of result using styling arguments such as resizeMode: 'contain' and the image disappears when following the advice of people who say to use the styling arguments width: undefined and height: undefined.
I'm a bit new to React Native so it's certainly possible that there's a blindingly obvious issue with how I'm approaching this problem.  I'm also new to posting on Stack Overflow so any pointers about how best to describe or show my problem would also be most welcome.
Here is the source code I am using which produces the result where the image is too big for the screen:
export default class ComponentIndex extends React.Component {
    render(){
        return(
            <ImageBackground
            source={require('./../../assets/images/background_placeholder.png')}
            style={{width: '100%', height: '100%'}}
            >
                <View style={styles.parentView}>
                    <View style={styles.elementSpacer}>
                        <Image
                            source={require('./../../assets/images/iview_learning_logo.png')}
                            style={styles.headerImage}
                        />
                    </View>
                    <View style={styles.elementContainer}>
                        <Text style={styles.subheadingText}>App for comprehensive tutorials</Text>
                    </View>
                    <View style={styles.elementContainer}>
                        <Button rounded style={styles.startButton}>
                            <Text style={styles.startButtonText}>LET'S GO</Text>
                        </Button>
                    </View>
                </View>
            </ImageBackground>
        );
    }
}

const styles = StyleSheet.create({
    parentView: {
        flex: 1,
        flexDirection: 'column',
        padding: 30,
        justifyContent: 'center',
    },
    headerImage: {
        resizeMode: 'contain',
    },
    elementSpacer: {
        flex: 1,
    },
    elementContainerHeader: {
        height: 60,
    },
    elementContainer: {
        margin: 10,
    },
    subheadingText: {
        fontSize: 18,
        textAlign: 'center',
        //fontFamily: 'Arial',
    },
    startButton: {
        alignItems: 'center',
        justifyContent: 'center',
        alignSelf: 'center',
        paddingRight: 25,
        paddingLeft: 25,
        backgroundColor: '#c00000',
    },
    startButtonText: {
        color: 'white',
        //fontWeight: 'bold',
        fontSize: 20,
        //fontFamily: 'Arial',
    },
});

Image going off the side of the screen
And here is the Source Code I am using where the image disappears off the screen:
export default class ComponentIndex extends React.Component {
    render(){
        return(
            <ImageBackground
            source={require('./../../assets/images/background_placeholder.png')}
            style={{width: '100%', height: '100%'}}
            >
                <View style={styles.parentView}>
                    <View style={styles.elementSpacer}>
                        <Image
                            source={require('./../../assets/images/iview_learning_logo.png')}
                            style={styles.headerImage}
                        />
                    </View>
                    <View style={styles.elementContainer}>
                        <Text style={styles.subheadingText}>App for comprehensive tutorials</Text>
                    </View>
                    <View style={styles.elementContainer}>
                        <Button rounded style={styles.startButton}>
                            <Text style={styles.startButtonText}>LET'S GO</Text>
                        </Button>
                    </View>
                </View>
            </ImageBackground>
        );
    }
}

const styles = StyleSheet.create({
    parentView: {
        flex: 1,
        flexDirection: 'column',
        padding: 30,
        justifyContent: 'center',
    },
    headerImage: {
        resizeMode: 'contain',
        height: undefined,
        width: undefined,
    },
    elementSpacer: {
        flex: 1,
    },
    elementContainerHeader: {
        height: 60,
    },
    elementContainer: {
        margin: 10,
    },
    subheadingText: {
        fontSize: 18,
        textAlign: 'center',
        //fontFamily: 'Arial',
    },
    startButton: {
        alignItems: 'center',
        justifyContent: 'center',
        alignSelf: 'center',
        paddingRight: 25,
        paddingLeft: 25,
        backgroundColor: '#c00000',
    },
    startButtonText: {
        color: 'white',
        //fontWeight: 'bold',
        fontSize: 20,
        //fontFamily: 'Arial',
    },
});

Image disappeared entirely

A: After viewing the related questions, I found a solution which worked for me.  Adding the following styling arguments did the trick:
width: null,
resizeMode: 'contain',
height: 220

The Stack Overflow question this solution was taken from


text:
Q: jQuery AJAX Success callback I'm using knockoutjs and have multiple ajax calls in my project in different script files.
I want to streamline the calls into one utility script and I have implemented the following:
Script File A:
function ABC(){
function myCallbackFunction(result){
///
}
$Callbacks.add(myCallbackFunction);

var UtilityObj = new ClsUtility();
UtilityObj .GetData(myJSONObj);
}

Script File B:
function ClsUtility(){
function GetData(myJSONObj){
$.ajax(
////
success: $.Callbacks.fire(result);
);

}
}

The callback function is not getting called.
Help me find out the solution.
Thanks,
Rahul Adwani

A: You may remove parenthesis like :
success: $.Callbacks.fire

that's equivalent to :
success: function(result){
    $.Callbacks.fire(result);
}

but you can't set a pointer function with parenthesis


text:
Q: RxJS5 operator similiar to .combineLatest but fire whenever a single observable emits I am looking for a way to combine multiple Observables into a flat tuple of scalar values - similar to .combineLatest() - but with the exception that it should emit a new value tuple even when no value has been emitted on one of the source observables - yieldung "undefined" in the tuple for those observables that did not yet emit.
Example:
const s1 = new Subject<string>();
const s2 = new Subject<string>();

Observable.combineWithUndefined(s1, s2).subscribe( ([t1, t2]) => {
    console.log(t1.toString() + " " + t2.toString());
});

s1.next("Hello");
s2.next("John");

// expected output:
// Hello undefined
// Hello John

A: Make the two subjects startWith the undefined value, so when one of then emits the first value, the combineLatest will emit as well and combine that with the start value of the other subject.


text:
Q: Selenium-webdriver. Браузер Opera не запускается (выдает ошибку) Подскажите пожалуйста, как запустить тест в Node.js через браузер Opera.Скачивал operadriver и прописывал в Path, не помогает. Может есть у кого пример запуска теста в Opera.

WebDriverError: unknown error: cannot find Opera binary
    (Driver info: OperaDriver=2.30,platform=Windows NT 6.1.7601 SP1 x86_64)

A: У драйвера Оперы есть давняя проблема (которую разработчики, похоже, проблемой не считают): требуется явно указать путь до исполняемого файла самой Оперы. О том, как это сделать, документации в явном виде не нашел. Похоже, работает следующий код:
const webdriver = require('selenium-webdriver');

const caps = webdriver.Capabilities.opera();
caps.set('chromeOptions', {
  binary: 'C:/Program Files (x86)/Opera/49.0.2725.34/opera.exe'
});

const driver = new webdriver.Builder()
  .forBrowser('opera')
  .withCapabilities(caps)
  .build();

driver.get('https://google.com/');
driver.sleep(5000);
driver.quit();

A: Ваша ошибка заключается в том, что у вас на машине, на которой вы пытаетесь запустить тесты, не установлен сам браузер Opera.
operadriver это всего лишь "прослойка" между кодом и самим браузером.
Установите на машину Opera.


text:
Q: Failed sending email with cakephp 3.1 | stream_socket_client() I have a problem with CakePHP 3.1 on my virtual server.
When I try to send e-mails on localhost, everything works perfect, no errors, no warnings.
However when I try to send e-mails on vserver, I receive the following error:
2016-01-06 11:07:33 Error: [Cake\Network\Exception\SocketException] stream_socket_client() [function.stream-socket-client]: Peer certificate CN=`smtp.gmail.com' did not match expected CN=`ssl://smtp.gmail.com'
stream_socket_client() [function.stream-socket-client]: Failed to enable crypto
stream_socket_client() [function.stream-socket-client]: unable to connect to ssl://sm
tp.gmail.com:465 (Unknown error)

I have already tried to change the email configuration in app.php by adding the following:
'ssl' => [
        'verify_peer'  => false,
        'verify_peer_name'  => false,
        'allow_self_signed' => true
],

This did not fix the problem.
Does anyone got a hint or solution for that problem?


text:
Q: iOS UITableView numberOfRowsInSection BAD ACCESS I'm calling the numberOfRowsInSection method of the UITableView delegate inside of the heightForRowAtIndexPath but it gives me a Bad Access Error:
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ...
    NSLog(@"number of rows in section: %i", [tableView numberOfRowsInSection:[indexPath section]]);
    ...
}

Can anybody tell me whats wrong here?

A: You are calling an delegate method.
When you call this method, it'll invoke the related delegates method like cellForRowAtIndexPath, heightForRowAtIndexPath etc.
It'll cause an infinite loop that's why it's crashing.

A: That's normal.. In that moment your UITableView is being created. You shouldn't call methods related to your UITableView, before it has been build. You should rely in other mechanism to get the height of your Cells.

A: You need to return an actual value here. So instead of calling [tableView numberOfRowsInSection:[indexPath section]] simply do the same thing again.
In order not to duplicate your code you could create a helper method which you can call in both places, namely, your heightForRowAtIndexPath method and the numberOfRowsInSection method:
- (int) myNumberOfRowsMethod{
    // Here you would usually have some underlying model
    return [self.myContactsOrWhateverArray count];
}

A: You are calling
[tableView numberOfRowsInSection:section];

You should be calling
[self numberOfRowsInSection:section];


text:
Q: How do i load div's besides each other Im working on a html newsletter for my company and encountered a problem here.
Now i wrote some code, to get articles from our page's rss feed to the newsletter like title, thumbnail and summary.

Thumbnail label

Lorem ipsum dolor sit amet, consectetur adipisicing elit.
            Facere, soluta, eligendi doloribus sunt minus amet sit debitis repellat.
            Consectetur, culpa itaque odio similique suscipit

Button Button

Now what happens. I load the rss, select the article and it perfectly aligns on the left thumbnail, title and summary downwards. Now when i select a new Article it appears below but i want it to show on the right site. I know the solution when writing them directly in one code but those are getting loaded seperately.
P.S. Im very new to html and css so sorry if i made some plain mistakes.

A: For email templates, it is better to use
 rather than
. Email templates always need inline css and some of the properties like float are not supported. So it is difficult to construct a structure using
 in email template. But it is easy with


text:
Q: alignment of basket in Shopify Mobile View I seem to be having an issue with aligning the basket on the top row when viewing my site on a mobile. For some reason, this sometimes appears at the top and sometimes appears at the bottom and I cant work out why this is and where I need to amend the code in order to fix this.
Would really appreciate if somebody could advise. I have attached an image to show this from a mobile and the site itself can be seen at:
[https://defineclothing.co/][]1

A: I wonder why it even works sometimes ;)
This div
 has a relative positioning and
 an absolute positioning.
Absolute positioned elements are positioned relative to the first positioned parent (which means relative, absolut or fixed). In order to achive the behaviour you want simply reset the relative positioning of
 to position: static

        ....


text:
Q: disable hyperthreading on a multi-core Dell PC I have a Dell desktop running Windows 7 Professional.  I think the processor is an Intel Core i7-2600
Recently a computer expert who specializes in Linux clusters was looking at my desktop PC and commented off-hand that my machine has 8 threads.  He said that meant the machine has 4 cores: 2 threads per core.  I had been unaware that the machine had more than one core.
Now that I know the machine apparently has four cores I am hoping to run maybe three models simultaneously, one model on each of three core.
Someone suggested that I "turn off the hyperthreading" so that I "can use the whole core per model".  Otherwise, he wrote "it runs at half speed".
I run many models using Program R and the computer gentleman who was helping me pointed out that one of my R script files displayed a message saying it was using 7 of 8 threads.  So, given that the R file was using 2 threads per core with three of the cores maybe turning off hyperthreading would not increase computation speed in my case?
If turning off hyperthreading would increase computation speed of the R scripts, how could I do that?
I searched the internet a little bit and found a discussion on the subject at this forum:
http://answers.microsoft.com/en-us/windows/forum/windows_7-performance/disable-hyperthreading-when-windows-7-already/80dd6c15-76b7-4534-b691-3e3a37ffad75
One comment at that forum that concerns me is the claim that:
"The biggest problem for those who want to shut down HT, is that a lot of computer manufacturers (HP, Dell) don't allow the people who buy their computers the BIOS option to shut down HT. And since windows looks at the HT setting in BIOS to determine whether to handle HT, it's a case of being stuck in low gear, and no ability to shift up."
Since my computer is a Dell, perhaps I am not able to turn off hyper-threading.
I also found this post on Superuser:
Disable Hyperthreading in the Windows 7 registry
One answer there seemed particularly helpful, but complex, dealing with hexadecimals, and the computer in question was an HP.  I do not know whether that matters.
There appear to be quite a few other posts here about hyperthreads, but the one immediately above comes closest to my situation of those I have read.
Sorry if this question is a duplicate.  If I need to provide additional information or clarify my concerns I will gladly do so.

A: Why is there no option inthe BIOS?
I assume the reason why Dell and friends often do not add an option to disable this is because it rarely is a good idea. On average it will make your computer slower (or from a different point of view, it will make competitors computers relative faster).
Having said,that, lets look at some imaginary examples:
What does HT do?
1 core, no hyper-threading

*

*1 CPU bound process is running, and can run and maximum speed. Lets call this speed 1, or 100%

*2 CPU bound processes running. The CPU will have to switch between both. Effective speed on both processes is roughly halved.  (The sum of both speeds is still equal to the first example.)

*3 CPU bound processes running. The CPU will have to switch between all three. Effective speed on both processes is roughly a a third.  (The sum of both speeds is still the same ( 3 x 0.33 = 1 ).

2 cores, no hyper-threading

*

*1 CPU bound process *0 is running, and can run and maximum speed for that core. (speed 100%) (The other core is idle).

*2 CPU bound processes running. Both can run at  maximum speed for their core. (speed 200%)

*3 CPU bound processes running. Usually you get 3 tasks running at about 2/3rd efficiency.  (The sum of the speeds is still '2'. Roughly 2 because you loose a bit due to extra overhead and cache misses). (speed 200%, or maybe 190%)

Now cores with hyper-threading . These act as two cores, but not two complete cores. What Intel defines as hyper-threading  has changed a bit over time, but usually it comes down to this. A CPU fetches data from memory and computes. If it does not need the memory bus then a second part of the CPU can do limited work. Since not all hardware is duplicated you do not get two full cores. However with limited extra hardware (10%?) you gain on average 30% speed. *1
1 core, with
 - 1 CPU bound process is running, and can run and maximum speed. (100%)
 - 2 CPU bound processes running. The CPU will have to switch between both. However it has some extra hardware. Net speed will be about 30% faster  (say speed 133% for a single core)
Etc.
So much for the introduction to HT.
Are these fictional %'s real?
No. First of all you will loose efficiency due to overhead. (10 tasks on one CPU will not run slower than just one task with no context switches and all of the cache for its data).
Secondly I totally ignored turbo boost since that would complicate the explanation.
What did my friend possibly mean to say?
Lets look at your 4 core 8 treads CPU like this:
Core 1, CPU 1 (real)
Core 1, CPU 2 (with HT)
Core 2, CPU 3 (real)
Core 2, CPU 4 (with HT)
Core 3, CPU 5 (real)
Core 3, CPU 6 (with HT)
Core 4, CPU 7 (real)
Core 4, CPU 8 (with HT)
If I run two tasks I do not want both of them on CPU1 and CPU2 (since they share an actual core) and the nett result is near half of the possible speed. This might be what your friend meant.
While true I think that you do not need to worry. The windows scheduler is smart enough to allocate processes first to CPUs 1,3,5,7 and only then to 2,4,6,8.

*0 A CPU bound process is a process which is limited by the CPU. If a process is waiting for diskIO and the CPU is idle then you get totally different results.
*1 Please take those numbers with a grain of salt. They are not precise. They will vary per CPU generation and even per CPU model. They will vary per program. And what Intel calls hyper-threading has changed since early CPU generations. However they do give a rough idea.


text:
Q: Node red error: npm ERR! Invalid tag name I have a problem.
When I install a library in node red, the following error appears:
npm ERR! code EINVALIDTAGNAME
npm ERR! Invalid tag name "" ~ "2.30.0": Tags may not have any characters that encodeURIComponent encodes.
So what I do is go look at the package.json file of my project and indeed, it has strange characters in the dependencies and it looks like this:
"dependencies": {
    "node-red-dashboard": "\"~\"2.30.0"
}

What I do at this point is delete the strange characters, looking like this:
"dependencies": {
    "node-red-dashboard": "2.30.0"
}

With this I reload the project and it works normally but, the problem is that I always have to do this in all my projects and it is very annoying.
I also clarify that it used to work for me, but one day the error simply began to appear. I tried reinstalling everything but the problem continues, how do I solve it?
i am using node-red:2.0.5 nodejs:16.6.2 npm:7.20.5


text:
Q: header file  missing in gcc 7.2 (Ubuntu) : how to solve it? few days ago I updated in my Ubuntu 16.04 Server Edition gcc to gcc 7.2 version:
gcc version 7.2.0 (Ubuntu 7.2.0-1ubuntu1~16.04)

which should be the most updated version of gcc available for Ubuntu
Now, compiling an example of a book,
g++ -std=c++17 auto_parallel.cpp -oauto_parallel

auto_parallel.cpp:5:10: fatal error: execution: No such file or directory
include <execution>

~~~~~~~~~~

compilation terminated.

How to solve the problem?
Thanks in advance. Marco

A: update your GUN compiler to version9, according to(https://en.cppreference.com/w/cpp/compiler_support
and https://www.bojankomazec.com/2020/03/upgrading-gnu-cc-compilers-on-ubuntu.html)
sudo apt install -y gcc-9 g++-9 -y
and remap your compiler to gcc-9
sudo rm /usr/bin/g++
sudo ln -s /usr/bin/g++-9 /usr/bin/g++
sudo rm /usr/bin/gcc
sudo ln -s /usr/bin/gcc-9 /usr/bin/gcc
Verify the compiler version
ls -la /usr/bin/gcc
ls -la /usr/bin/g++


text:
Q: MPI hello world is not reading processes correctly I'm having trouble getting the correct number of processes to output on a hello world program. I'm fairly certain this program should work since it was provided by the textbook that we are using. The code is as follows:
#include <stdio.h>
#include <string.h>
#include <mpi.h>

const int MAX_STRING = 100;

int main(int argc, char * argv[])
{
    char greeting[MAX_STRING];
    int comm_sz;
    int my_rank;

    MPI_Init(NULL, NULL);
    MPI_Comm_size(MPI_COMM_WORLD, &comm_sz);
    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);

   if (my_rank != 0)
   {
       sprintf(greeting, "Greetings from process %d of %d!\n", my_rank, comm_sz);
       MPI_Send(greeting, strlen(greeting)+1, MPI_CHAR, 0, 0, MPI_COMM_WORLD);
   }
   else
   {
       printf("Greetings from process %d of %d!\n", my_rank, comm_sz);
       for (int q = 1; q < comm_sz; q++)
       {
           MPI_Recv(greeting, MAX_STRING, MPI_CHAR, q, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
           printf("%s\n", greeting);
       }
    }
    MPI_Finalize();
    return 0;
}

I am compiling it by running
mpicxx hello_mpi.cpp -O3

Which compiles fine, then I execute it by
mpiexec -n 4 ./a.out

Using 4 as an example number of threads. I should be receiving an output as
Greetings from process 0 of 4!
Greetings from process 1 of 4!
Greetings from process 2 of 4!
Greetings from process 3 of 4!

But instead I am getting
Greetings from process 0 of 1!
Greetings from process 0 of 1!
Greetings from process 0 of 1!
Greetings from process 0 of 1!

I'm not sure why I'm getting this result instead of a rank from each thread. Again, this was the code provided by the textbook we are using (although originally written in C, I tried compiling an executing in C but ran into the same error).
Any ideas?


text:
Q: 22.04 does not include exfat-utils I'm getting the error unknown filesystem type 'exfat' and have seen all the posts and articles that reference installing exfat-utils and exfat-fuse.  However, exfat-utils is not available under 22.04 LTS.  I found exfat-progs and tried that but it still gives the error when attempting to mount an exFat formatted partition.
An attempt to locate exfat-utils confirms it is not in jammy repos:
$ rmadison exfat-utils
 exfat-utils | 1.0.1-1 | trusty/universe | source, amd64, arm64, armhf, i386, powerpc, ppc64el
 exfat-utils | 1.2.3-1 | xenial/universe | source, amd64, arm64, armhf, i386, powerpc, ppc64el, s390x
 exfat-utils | 1.2.8-1 | bionic/universe | source, amd64, arm64, armhf, i386, ppc64el, s390x
 exfat-utils | 1.3.0-1 | focal/universe  | source, amd64, arm64, armhf, ppc64el, riscv64, s390x
 exfat-utils | 1.3.0-2 | impish/universe | source, amd64, arm64, armhf, ppc64el, riscv64, s390x


text:
Q: Working with the "onclick" of a server side dynamically created TableRow I am dynamically creating a table which I want to have clickable rows.  When the user clicks on one of the rows I want to redirect to a page specific to the item of that row.  My question is how on the server side can I wire the "onclick" event to a routine that will then allow me to build a url based on some of the data included in the row they clicked?
for example I would want to do this on click:
Response.Redirect("SomePage.aspx?" itemType + "&" + COLUMN1VALUE);
where COLUMN1VALUE would be the first column in the row that was clicked.

A: It sounds like your actual goal is simply to display/edit the row on another page. If this is the case, you could simply add a javascript event handler to the table row when you create it.
<tr onclick="window.location='DetailPage.aspx?id=<%= IdFromDb %>'">
    <!-- etc......-->
</tr>

If you use a GridView to create the table you can inject this in the RowDataBound event:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

{

    string OnClickCmd = "window.location='DetailPage.aspx?id=";

    if (e.Row.RowType == DataControlRowType.DataRow)

    {

        OnClickCmd += DataBinder.Eval(e.Row.DataItem, "IdFromDb").ToString() + "'";

        e.Row.Attributes.Add("onclick", OnClickCmd);

    }
}

Unless you need to do something in the postback, there is no need to redirect. Further, you could just create a hyperlink when you create the row eliminating the need for javascript, you don't need the full row clicking experience.

A: I would build the link in the table as an actual anchor tag to your SomePage.aspx (while you're building your table, you should know what the query string would be for each table row), opposed to a server side control that redirects on postback

A: In your click event handler, you cast the sender as button, then get its parents until you get to the TableRow, then do a FindControl() to find the control with the value specific to that row and use it to build your URL!
Good luck!


text:
Q: Calendar server I need a simple (reliable) calendar server on my server that will preferable integrates with Mozilla Thunderbird email client that I already use.
Also a Android client?

A: You can install owncloud. https://owncloud.org/
Or:

*

*http://www.davical.org/

*http://radicale.org/

A: Radicale as a Simple, Reliable Calendar Server

Copied and abridged from https://github.com/Kozea/Radicale/wiki/Simple-installation

Simple to Install
##### Install dependencies for Radicale
ServerUSER@Server:~$ sudo apt-get install python3-pip
##### Install dependencies for bcrypt encryption method
ServerUSER@Server:~$ sudo python3 -m pip install --upgrade passlib bcrypt
##### -H flag uses root's home rather than USER's home
ServerUSER@Server:~$ sudo -H python3 -m pip install --upgrade radicale

Simple to Configure
##### Put user "fakeuser" in a new "users" file
ServerUSER@SERVER:~$ sudo htpasswd -B -c /etc/radicale/users fakeuser
New password:
Re-type new password:
##### Add another user
ServerUSER@SERVER:~$ sudo htpasswd -B /etc/radicale/users user2
New password:
Re-type new password:
##### Install dependencies for bcrypt encryption method
ServerUSER@SERVER:~$ sudo python3 -m pip install --upgrade passlib bcrypt

Edit the Configuration File
ServerUSER@SERVER:~$ sudo nano /etc/radicale/config

Tell Radicale where to find users
##### Add these lines under relevant portions of [auth] section
type = htpasswd
htpasswd_filename = /etc/radicale/users
# encryption method used in the htpasswd file
htpasswd_encryption = bcrypt

Add some safety limits
##### Add these lines under relevant portions of [server] section
max_connections = 20
# 1 Megabyte
max_content_length = 10000000
# 10 seconds
timeout = 10

##### Add these lines under relevant portions of [auth] section
# Average delay after failed login attempts in seconds
delay = 1

Edit files to allow SSL/TLS connections from other machines
##### Add these lines under relevant portions of [server] section
hosts = 0.0.0.0:5232
##### By setting ssl = True, Radicale no longer responds to HTTP requests.
ssl = True
certificate = /etc/ssl/radicale.cert.pem
key = /etc/ssl/radicale.key.pem

SSL/TLS keys
Make a Self-Signed SSL/TLS Certificate to allow HTTPS connection to your Radical Service on Server
##### You can hit enter as an answer to all the questions to set the default except this one:
##### "Common Name (eg, YOUR name) []:" where you will enter your domain name or dns record
##### used for your development server, or in case of wildcard certificates,
##### use an astrisk, like this: *.mycompany.com
##### By using a self-signed certificate, your browser should warn you of this fact.
##### Confirm exception as you wish, but this exception is necessary to visit page.
ServerUSER@Server:~$ openssl req -nodes -newkey rsa:2048 -keyout /etc/ssl/radicale.key.pem -out /etc/ssl/radicale.cert.pem -x509 -days 365

Common Name (eg, YOUR name) []: developmentserver12345

Radicale Service
Set Up Service on Server to allow Radicale to run in background all the time
##### Create "radicale" user and group for Radicale service
ServerUSER@Server:~$ sudo useradd --system --home-dir / --shell /sbin/nologin radicale
##### Make storage folder writable by user "radicale"
ServerUSER@Server:~$ sudo mkdir -p /var/lib/radicale/collections
ServerUSER@Server:~$ sudo chown -R radicale:radicale /var/lib/radicale/collections
##### Make storage folder non-readable by others
ServerUSER@Server:~$ sudo chmod -R o= /var/lib/radicale/collections

Create the file /etc/systemd/system/radicale.service
ServerUSER@Server:~$ sudo nano /etc/systemd/system/radicale.service

Cut and paste and save the following into the /etc/systemd/system/radicale.service blank nano screen
[Unit]
Description=A simple CalDAV (calendar) and CardDAV (contact) server
After=network.target
Requires=network.target

[Service]
ExecStart=/usr/bin/env python3 -m radicale
Restart=on-failure
User=radicale
# Deny other users access to the calendar data
UMask=0027
# Optional security settings
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
PrivateDevices=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
NoNewPrivileges=true
ReadWritePaths=/var/lib/radicale/collections

[Install]
WantedBy=multi-user.target

Start the Service Manually (Service will start automatically on failure and/or Server restart)
# Enable the service
ServerUSER@Server:~$ sudo systemctl enable radicale
# Start the service
ServerUSER@Server:~$ sudo systemctl start radicale
# Check the status of the service
ServerUSER@Server:~$ sudo systemctl status radicale
# View all log messages
ServerUSER@Server:~$ sudo journalctl --unit radicale.service

Connects to Thunderbird
Create New Calendar in Thunderbird (Public.IP.Address Server)

*

*Open Thunderbird

*

*Click "Events and Tasks > Calendar"

*Click "File > New > Calendar" [or right-click "Calendar Pane > Calendar List" area and select "New Calendar"]

*Select "On the Network" in the dialog box and click "Next"

*Select a Format and Location and click "Next"

*

*Format: CalDAV

*Location: Copy and paste fakeusercalDAV01's URL (all of it)

*

*i.e., https://Public.IP.Address:5232/fakeuser/775e38a1-32eg-9e0x-e3tn-fax92930uskl/

*Enter a Name, Color, and Thunderbird email account and click "Next"

*

*Name: TB to Server Real Radicale Calendar (TSRRC)

*Color: [color you would like to indicate an event on TSRRC]

*Email: [default]

*Click "Finish"

Connects to Android
Create New Calendar in Android (Public.IP.Address Server)

*

*Install DAVdroid

*Open Calendar

*

*Add Account in Calendar [not DAVdroid]

*Select DAVdroid as Account type

*Login with URL and user name

*

*Point Calendar at https://Public.IP.Address:5232/fakeuser/775e38a1-32eg-9e0x-e3tn-fax92930uskl/

*Username: fakeuser

*Password: [password you gave to htpasswd]

*Manually attempt to refresh your New Calendar a few times, check Radicale logs to troubleshoot


text:
Q: Create Calendar Event in outlook with NodeJS I need to create a calendar event in outlook using NodeJS script. I have searched every where and tried different npm packages but i didn't got the solution.
I have tried Node-Outlook NPM package but the documentation is not clear like how to create calendar event.
var outlook = require('node-outlook');

var newEvent = {
    "Subject": "Discuss the Calendar REST API",
    "Body": {
        "ContentType": "HTML",
        "Content": "I think it will meet our requirements!"
    }
};

let createEventParameters = {
    token: ['Access token'],
    event: newEvent,
    user : <user>
};
outlook.calendar.createEvents(createEventParameters, function (error, event) {
    if(error) {
        console.log(error);
    } else {
        console.log(event);
    }
});

This npm package return error :
REST request returned 401; body: {"error":{"code":"InvalidAudience","message":"The audience claim value is invalid 'aud'.

Please help me to solve this problem and also if you know any different way to create calendar event please suggest.
Thanks

A: try to set this permission
Calendars.ReadWrite
in API permissions in Azure configuration


text:
Q: Error when pushing to scratch org I have created a new sfdx project and pulled source from a managed package. When I try to push the source to a scratch org I get
ERROR:  Cannot read property 'getAggregateFullNameFromFilePath' of null.

I have never seen this error before and was not able to find anything while Googling around. Has anyone ever seen this error or know what that property is?

A: I got this error recently.
I found a corresponding failed deployment in the scratch org by a quick find for "Deployment status" in setup.
Please look there for details on failure.

A: We have the same error, and the reason was a syntax error in one of the lightning components. We are working with VS code and we had this error by pushing to scratch org. The reason was a simple syntax error: we wrote
<aura:attribute name"theName" type="something">
instead of
<aura:attribute name="theName" type="something">


text:
Q: running php command from the cli in parallel i have this shell command, i use it in the crontab
for i in {0..10};do /usr/bin/php5-cli -q /my/path/to/file.php --chunk $i;done  > /dev/null 2>&1

but each loop step is waiting the previous one to start, and each one takes 5 minutes so it will end after 25 minutes
is there any way to run all the 10 steps in one time? so the whole process will take just 5 minutes

I'm using http://php.net/manual/en/function.getopt.php for handling the command parameters

A: You can run a command in the background simply by putting & sign after it
/usr/bin/php5-cli -q /my/path/to/file.php --chunk $i &


text:
Q: Find root that will always make a complete Binary Search Tree I need to make a Complete Binary Search Tree.
If I have a method that looks like this:
public void createCompleteTree(Node n, int i)

And I for example use the number 9 as the i value, what do I do to find a root that will make a complete tree?
If I use 9 as the value, the numbers would be 1,2,3,4,5,6,7,8,9.
For a complete Binary search tree, the root must be 6, like below:

How can I make a method that knows this? It should work with any kind of number, so if I want to use number 14 it should be able to.
So far the only code I have is an insert method, which just checks if the number to be inserted is greater (goes to the right) or smaller (goes to the left) than the node we are currently at. x is the number to be inserted, t is the current node we are at in the tree:
 private BinaryNode<AnyType> insert( AnyType x, BinaryNode<AnyType> t )
{
    if( t == null )
        return new BinaryNode<>( x, null, null );

    int compareResult = x.compareTo( t.element );

    if( compareResult < 0 )
        t.left = insert( x, t.left );
    else if( compareResult > 0 )
        t.right = insert( x, t.right );
    else
        ;  // Duplicate; do nothing
    return t;
}

A: Binary tree with N levels may contain from 2^(N-1) to 2^N - 1 element.
Last (lowest) level of tree that you describe may contain from 1 to 2^(N-1) elements in the strict order.
Tree with K elements and N levels contains K - 2^(N-1) + 1 elements on its last level.
Left subtree of this tree contains C = min(K - 2^(N-1) + 1, 2^(N-2)) elements.
So root of tree will be 2^(N-2) + C -th element

A: This is the solution:
From what I can tell computing the offset done by incrementing the offset for each additional element in length until you get to 1/2 of the width of a level. So, a BST with height of 4 has 8 elements in the lowest level. Lists of size 8, 9, 10, … 15 create BST with height of 4. For those lists the root index into the list is then 4, 5, 6, 7, 7, 7, 7, 7.
Seems to work
private int calcMid(int length) {
    if ( length <= 4 )
        return length / 2;
    int levelSize = 1;
    int total = 1;
    while ( total < length ) {
        levelSize *= 2;
        total += levelSize;
    }
    int excess = length - (total - levelSize);
    int minMid = (total - levelSize + 1) / 2;
    if ( excess <= levelSize / 2 ) {
        return minMid + (excess - 1);
    } else {
        int midExcess = levelSize/2;
        return minMid + (midExcess - 1);
   }
}

Found as part of this code:
https://stackoverflow.com/a/52749727/9899617

A: Root of your binary tree does not have to be constant.
There exists self-balancing trees. Check this out: enter link description here


text:
Q: Using pointer graphs in constexpr functions I'm trying to wrap my head around constexpr rules as they relate to pointers, contained within constexpr data structures, which reference other parts of that constexpr data structure.
Consider the following code fragment:
struct selfref{
    selfref *next{nullptr};
};

struct exec{
    selfref mem[1] = {selfref{}};
    constexpr exec(){
    mem[0].next = &mem[0];
    }
};

If I attempt to instantiate exec as a constexpr local, I can follow pointers from it:
int main(){
    static constexpr exec ret;
    static constexpr selfref *ptr = ret.mem[0].next;
}

But if I instead return it from a trivial function and change nothing else:
constexpr exec do_thing(){
    return exec{};
}

int main(){
    static constexpr auto ret = do_thing();
    static constexpr selfref *ptr = ret.mem[0].next;
}

I suddenly get an error with g++-11 and g++-12:
minimal-interesting-example2.cpp: In function 'int main()':
minimal-interesting-example2.cpp:18:42: error: 'exec{selfref [1]{selfref{(&<anonymous>.exec::mem[0])}}}' is not a constant expression
   18 |     static constexpr auto ret = do_thing();
      |

But not with clang++-13. Demo
Which compiler is right? And regardless of that answer, what's going on here???
EDIT: It looks like GCC at least thinks that this code should work according to this bug report: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=64989#c8. I would still be very interested to hear if there's someone with the standard in their head who is able to confirm that this should work!


text:
Q: Add Layer Groups and Markers in a loop ( from json) I just started working with Leaflet. I want to create a map for a game, so this is a map created with L.CRS.Simple.
I have been able to set the map image, and add marker manually.
Now, I want to create markers and layers groups dynamicly from a json file that I generate in PHP from a sqlite database.
My json is this one for now : https://grounded.dubebenjamin.com/api/markers.json
My json is a list of type(layergroup) inside which I have put another object containing all the markers for the type(layergroup) :
Structure :
{
  "landmarks": {
    "id": 1,
    "slug": "landmark",
    "type": "Landmarks",
    "markers": [
      {"id": 1, "title": "Title of marker 1 of layergroup1"},
      {"id": 2, "title": "Title of marker 2 of layergroup1"}
    ]
  },
  "science": {
    "id": 2,
    "slug": "science",
    "type": "Science Points",
    "markers": [
      {"id": 1, "title": "Title of marker 1 of layergroup2"}
    ]
  }
}

*

*= Where landmarks and science are layergroup.

From this json, my plan was to have a first loop, where for each type I want to create a layer group, then create the markers for this layer group and assign the markers to the layer groups.
Manually, I understand the usage of L.marker and L.layerGroup, but where I am stuck, is how to do that in a loop, and defined the layoutgroup name from the json data.
From now, I have just been able to create the marker, but not the layer group. You can see my progress here: https://grounded.dubebenjamin.com/
If you need more precision, just ask me.

A: Use this code:
var layergroups = {};
fetch('https://grounded.dubebenjamin.com/api/markers.json').then(response => response.json())
    .then((data)=>{
        layergroups = {};
        for(type in data){
            var lg = L.layerGroup().addTo(map)
            layergroups[type] = lg;
            if(data[type].markers){
                var markers = data[type].markers;
                markers.forEach((marker)=>{
                    L.marker([marker.x,marker.y]).bindPopup(marker.desc).addTo(lg);
                })
            }
        }
    })

First fetch the data from the server, then loop through the layergroups and add them to the map and then to the Object/Array.
Then you create the markers and add them to the layergroup.
You can get the layergroups over the Object layergroups but keep in mind that the request is async.