text:
Q: How to change the colors of nodes in force directed graph in d3js using javascript? Current Behavior: All the nodes are in random colors.
Expected Behavior: All the parent nodes should be in same colors(blue for example) and all the child nodes should in same colors(light blue).
How to achieve this ?
Here is the working jsfiddle: Fiddle
  var color = d3.scaleOrdinal(d3.schemeCategory10);

grads = svg.append("defs").selectAll("radialGradient")
    .data(graph.nodes)
    .enter()
    .append("radialGradient")
    .attr("gradientUnits", "objectBoundingBox")
    .attr("cx", 0)
    .attr("fill", function(d) { return color(d.id); })
    .attr("cy", 0)
    .attr("r", "100%")
    .attr("id", function(d, i) { return "grad" + i; });

 grads.append("stop")
    .attr("offset", "0%")
    .style("stop-color", "white");

 grads.append("stop")
    .attr("offset", "100%")
    .style("stop-color",  function(d) { return color(d.id); });

nodeElements =  g.append("g")
  .attr("class", "nodes")
  .selectAll("circle")
  .data(graph.nodes)
  .enter().append("circle")
  .attr("r", 60)

  .attr("stroke", "#fff")
  .attr('stroke-width', 21)
  .attr("id", function(d) { return d.id })
   //.attr("fill", function(d) {return color(d.id)})
     .attr('fill', function(d, i) { return 'url(#grad' + i + ')'; })

A: Then you need to change the color based on the group. Change this line as follow:
.attr("fill", function(d) {return color(d.group)})
Please find the working code below:

var graph = {
  'nodes': [{
      'id': 'Material_Definition',
      'group': 0
    },
    {
      'id': 'Item1',
      'group': 1
    },
    {
      'id': 'Item2',
      'group': 1
    },
    {
      'id': 'Item3',
      'group': 1
    },
    {
      'id': 'Item4',
      'group': 1
    },
    {
      'id': 'Item5',
      'group': 1
    },
    {
      'id': 'SubItem1_Item1',
      'group': 2
    },
    {
      'id': 'SubItem2_Item1',
      'group': 2
    }
  ],
  'links': [
    /* Material Definition linked to Items */
    {
      'source': 'Material_Definition',
      'target': 'Item1',
      'value': 1,
      'type': 'A'
    },
    {
      'source': 'Material_Definition',
      'target': 'Item2',
      'value': 8,
      'type': 'A'
    },
    {
      'source': 'Material_Definition',
      'target': 'Item3',
      'value': 10,
      'type': 'A'
    },
    {
      'source': 'Material_Definition',
      'target': 'Item3',
      'value': 1,
      'type': 'A'
    },
    {
      'source': 'Material_Definition',
      'target': 'Item4',
      'value': 1,
      'type': 'A'
    },
    {
      'source': 'Material_Definition',
      'target': 'Item5',
      'value': 1,
      'type': 'A'
    },

    /* Item1 is linked to SubItems */
    {
      'source': 'Item1',
      'target': 'SubItem1_Item1',
      'value': 2,
      'type': 'A'
    },
    {
      'source': 'Item1',
      'target': 'SubItem2_Item1',
      'value': 1,
      'type': 'A'
    },

    /* Interconnected Items */
    {
      'source': 'Item5',
      'target': 'Item4',
      'value': 2,
      'type': 'A'
    },
    {
      'source': 'Item2',
      'target': 'Item3',
      'value': 1,
      'type': 'A'
    },
  ]
};

var svg = d3.select("svg"),
  width = +svg.attr("width"),
  height = +svg.attr("height")

var store = Object.assign({}, graph);
var color = d3.scaleOrdinal(d3.schemeCategory10);
var zoom_handler = d3.zoom().on("zoom", zoom_actions);
var linkElements, nodeElements, textElements, grads;

// zoom_handler(svg);

var simulation = d3.forceSimulation()
  .force("link", d3.forceLink().distance(700).id(function(d) {
    return d.id;
  }))
  .force("charge", d3.forceManyBody().strength(-1000))

  .force("center", d3.forceCenter(width / 2, height / 2));

var g = svg.append("g")
  .attr("class", "everything");

svg.call(zoom_handler)
  .call(zoom_handler.transform, d3.zoomIdentity.translate(200, 150).scale(0.2));
linkElements = svg.append("g").selectAll(".link"),
  nodeElements = svg.append("g").selectAll(".nodes");
grads = svg.append("g").selectAll(".grads");
textElements = svg.append("g").selectAll(".texts");
drawGraph();

function drawGraph() {

  // empty current Graph contents
  g.html('')

  grads = svg.append("defs").selectAll("radialGradient")
    .data(graph.nodes)
    .enter()
    .append("radialGradient")
    .attr("gradientUnits", "objectBoundingBox")
    .attr("cx", 0)
    .attr("fill", function(d) {
      return color(d.group);
    })
    .attr("cy", 0)
    .attr("r", "100%")
    .attr("id", function(d, i) {
      return "grad" + i;
    });

  grads.append("stop")
    .attr("offset", "0%")
    .style("stop-color", "white");

  grads.append("stop")
    .attr("offset", "100%")
    .style("stop-color", function(d) {
      return color(d.id);
    });

  linkElements = g.append("g")
    .attr("class", "links")
    .selectAll("line")
    .data(graph.links)
    .enter().append("line")
    .style("stroke-width", 5.5)
    .style("stroke", "grey")

  nodeElements = g.append("g")
    .attr("class", "nodes")
    .selectAll("circle")
    .data(graph.nodes)
    .enter().append("circle")
    .attr("r", 60)

    .attr("stroke", "#fff")
    .attr('stroke-width', 21)
    .attr("id", function(d) {
      return d.id
    })
    .attr("fill", function(d) {
      return color(d.group)
    })
    /*      .attr('fill', function(d, i) { return 'url(#grad' + i + ')'; }) */
    .on('contextmenu', function(d) {
      d3.event.preventDefault();
      menu(d3.mouse(svg.node())[0], d3.mouse(svg.node())[1]);
    })
    .on('mouseover', selectNode)
    .on('mouseout', releaseNode)
    .call(d3.drag()
      .on("start", dragstarted)
      .on("drag", dragged)
      .on("end", dragended));

  textElements = g.append("g") // use g.append instead of svg.append to enable zoom
    .attr("class", "texts")
    .selectAll("text")
    .data(graph.nodes)
    .enter().append("text")
    .attr("text-anchor", "end")
    .text(function(node) {
      return node.id
    })
    .attr("font-size", 55)
    .attr("font-family", "sans-serif")
    .attr("fill", "black")
    .attr("style", "font-weight:bold;")
    .attr("dx", 30)
    .attr("dy", 80)

}

function ticked() {
  linkElements
    .attr("x1", function(d) {
      return d.source.x;
    })
    .attr("y1", function(d) {
      return d.source.y;
    })
    .attr("x2", function(d) {
      return d.target.x;
    })
    .attr("y2", function(d) {
      return d.target.y;
    });
  nodeElements
    .attr("cx", function(d) {
      return d.x;
    })
    .attr("cy", function(d) {
      return d.y;
    })
    .each(d => {
      d3.select('#t_' + d.id).attr('x', d.x + 10).attr('y', d.y + 3);
    });
  textElements
    .attr('x', function(d) {
      return d.x
    })
    .attr('y', function(d) {
      return d.y
    });
}

simulation
  .nodes(graph.nodes)
  .on("tick", ticked);

simulation.force("link")
  .links(graph.links);

function zoom_actions() {
  g.attr("transform", d3.event.transform)
}

function dragstarted(d) {
  if (!d3.event.active) simulation.alphaTarget(0.3).restart();
  d.fx = d.x;
  d.fy = d.y;
}

function dragged(d) {
  d.fx = d3.event.x;
  d.fy = d3.event.y;
}

function dragended(d) {
  if (!d3.event.active) simulation.alphaTarget(0);
  d.fx = null;
  d.fy = null;
}

function selectNode(selectedNode) {
  var neighbors = getNeighbors(selectedNode)

  nodeElements.transition().duration(500)
    .attr('r', function(node) {
      return getNodeRadius(node, neighbors);
    });

  nodeElements.attr('fill', function(node) {
    return getNodeColor(node, neighbors, selectedNode);
  })

  textElements.transition().duration(500).style('font-size', function(node) {
    return getTextColor(node, neighbors)
  })
}

function releaseNode() {
  nodeElements.transition().duration(500)
    .attr('r', 60);
  nodeElements.attr('fill', function(d, i) {
    return 'url(#grad' + i + ')';
  })

  linkElements.style('stroke', 'grey');
}

function getNeighbors(node) {
  return graph.links.reduce(function(neighbors, link) {
    if (link.target.id === node.id) {
      neighbors.push(link.source.id)
    } else if (link.source.id === node.id) {
      neighbors.push(link.target.id)
    }
    return neighbors
  }, [node.id])
}

function getNodeColor(node, neighbors, selectedNode) {
  // If is neighbor
  if (Array.isArray(neighbors) && neighbors.indexOf(node.id) > -1) {
    return 'url(#grad' + selectedNode.index + ')'
    // return node.level === 1 ? '#9C4A9C' : 'rgba(251, 130, 30, 1)'
  } else {
    return 'url(#grad' + node.index + ')'
  }
  //return node.level === 0 ? '#91007B' : '#D8ABD8'
}

function getNodeRadius(node, neighbors) {
  // If is neighbor
  if (neighbors.indexOf(node.id) > -1) {
    return '100'
  } else {
    return '60'
  }
}

function isNeighborLink(node, link) {
  return link.target.id === node.id || link.source.id === node.id
}

function getTextColor(node, neighbors) {
  return Array.isArray(neighbors) && neighbors.indexOf(node.id) > -1 ? '40px' : '25px'
}

var filter = document.querySelector('#filter');
filter.addEventListener('change', function(event) {
  filterData(event.target.value);
  drawGraph();
})

var resetFilter = document.querySelector('#reset');
resetFilter.addEventListener('click', function(event) {
  drawGraph();
})

function filterData(id) {
  graph = Object.assign({}, store);
  graph.nodes = [];
  graph.links = [];
  dummyStore = [id];
  store.links.forEach(function(link) {
    if (link.source.id === id) {
      graph.links.push(link);
      dummyStore.push(link.target.id);
    } else if (link.target.id === id) {
      graph.links.push(link);
      dummyStore.push(link.source.id)
    }
  });
  store.nodes.forEach(function(node) {
    if (dummyStore.includes(node.id)) {
      graph.nodes.push(node);
    }
  })
}
.links line {
  stroke: #999;
  stroke-opacity: 0.6;
}

.nodes circle {
  stroke: #000;
  stroke-width: 1.5px;
}

text {
  font-size: 10px;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
Filter: <input type="text" name="filter" id="filter" />
<button id='reset'>Reset Filter</button>
<svg width="798" height="400"></svg>


text:
Q: no root file system defined error in ubuntu 13.10 installation I have installed ubuntu 13.10 along with windows 7 without creating any new partition. I am using a bootable pendrive to do so and the installation completes succesfully in the same drive in which windows is installed. But when the pc restarts to complete the installation this error shows up !! This same thing is successfully completed in another pc but in my pc it is showing an error. Pls help as i dont want to create a new partition and dont want to run it as a live cd.

A: First of all, digest this fact -- ubuntu works on an ext4 partition while, on the otherhand, Windows runs on an NTFS partition. If you decide to run Ubuntu and Windows on same partition, you might want to consider using Wubi.exe(Windows Ubuntu Installer).
[This installs Ubuntu and Windows on the same partition, but i would suggest you have two different partitions for the sake of performance. I believe that the system becomes slow in course of time due to fragmentation -- SUMMARY: use different partitions for Ubuntu and Windows].
Otherwise, if you decide to remove Windows (ofcourse after backing up all the important data) and shift to Ubuntu, while installing Ubuntu, go for the option "Other", and go for creating a new partition table, then define the root for your file system, and then install ubuntu.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to append the list in Python for certain index? I have a list like this;
list1 = [1, 1, 1, 1, 1, 1, 1, 1, 1] # list of 9 elements

I want to have another list2 like this..
list2 = [1, 2, 2, 2, 2, 2, 2, 2, 2, 1] # list of 10 elements

list2 is formed by keeping 0th element & the 8th element from list1 & adding adjacent elements next to each other in list1.
This is what I did;
list2 = [None] * 10
list2[0] = list2[9] = 1

for idx, i in enumerate(list1):
    try:
        add = list1[idx] + list1[idx+1]
        #print(add)
        list2[1:9].append(add)
    except:
        pass

print(list2)

But I am not getting the desired output... actually the list2 is not updating, I am getting:
[1, None, None, None, None, None, None, None, None, 1]

A: An alternate way to achieve your desired result is to effectively shift list1 by prepending a list with one entry of 0 to it, and then add it to itself (extended by an entry of 0 to match lengths), by using zip to create a list of tuples that can be iterated over:
list1 = [1, 1, 1, 1, 1, 1, 1, 1, 1]

list2 = [x + y for x, y in zip([0] + list1, list1 + [0])]
print(list2)

Output
[1, 2, 2, 2, 2, 2, 2, 2, 2, 1]

A: Similar to the other answers but I would do it in two lines of code using an intermediate list (or just modify the original list if you won't need it anymore) to make the padding easier to see:
list1 = [1, 1, 1, 1, 1, 1, 1, 1, 1]

lyst = [0, *list1, 0]
list2 = [prev + cur for prev, cur in zip(lyst, lyst[1:])]

print(list2)

A: What about something like:
list2 = list1[:1] + [x + y for x, y in zip(list1[0:], list1[1:])] + list1[-1:]


text:
Q: Get latest post for category I'm trying to get the latest post for each of the category in my forum app. I've been trying things like Category.objects.order_by('catID').annotate(latestpost=Post.objects.order_by('-pub_date')[:1])
I want to be able to do use the values: postID, title, user and pub_date in my template.
models.py:
class Category(models.Model):
    catID = models.CharField(max_length=20, primary_key=True)
    title = models.CharField(max_length=200)
    description = models.CharField(max_length=200)

class Post(models.Model):
    postID = models.CharField(max_length=10, primary_key=True)
    catID = models.ForeignKey(Category)
    user = models.CharField(max_length=100)
    title = models.CharField(max_length=200)
    content = models.TextField()
    pub_date = models.DateTimeField(auto_now=True)

views.py:
def index(request):
    cats = Category.objects.order_by('catID').annotate(latestpost=Post.objects.order_by('-pub_date')[:1])
    context = {'forum_cats': cats}
    return render(request, 'forums/index.html', context)

A: One way is
class Category(models.Model):
    catID = models.CharField(max_length=20, primary_key=True)
    title = models.CharField(max_length=200)
    description = models.CharField(max_length=200)

    def latest_post(self):
        post = self.post_set.order_by('-pub_date')
        if post:
            return post[0]
        return None

and in the template,
{% for cat in forum_cats %}
    {% if cat.latest_post %}
        {{cat.latest_post.title}}
    {% endif %}
{% endfor %}


text:
Q: Building JSON using mysql php and nested while cause Memory Allocation exhausted error I am trying to build the nested json using below code from the database values. This has already worked with smaller data, but now the same code is giving Memory issue. The error is "Allowed memory size of 268435456 bytes exhausted (tried to allocate 4194312 bytes)"
I tried to research and strongly feel that it is about some loop issue. can someone please help.
{
$conn = mysqli_connect(dbhost, dbuser, dbpass, db);
  mysqli_set_charset($conn,"utf8");
  //$Article_Info= array();
  $article_array = array();
  $seller_array = array();
  $company_id = Get_Company();
  error_log($company_id);

               $query_article = "SELECT B.SC_PRODUCT_NAME,A.SC_CUST_PROD_CODE, A.SC_ASIN_CD,A.SC_ARTICLE_ID,A.SC_COMPANY_ID,A.SC_PROD_GIVEN_NAME,A.SC_LAST_CHECKED,A.SC_LAST_UPDATED,A.SC_DEFAULT_SELLER,A.SC_BUY_BOX_SELLER,A.SC_CURRENCY,A.SC_LAST_PRICE,A.SC_CONV_PRICE,A.SC_NET_PRICE,A.SC_CONV_NET,A.SC_PRICE_INC,A.SC_PRICE_DEC,A.SC_COUNTRY_CODE,A.SC_DOMAIN,A.SC_AVAILABLE,A.SC_AVAIL_DESCR,A.SC_PRICE_TIME,A.SC_FAULT_FLAG,A.SC_FAULT_TIME,A.SC_FAULT_MSG FROM `SC_PRICE_HIST_TBL` A INNER JOIN `SC_PRODUCT_TBL` B ON A.SC_CUST_PROD_CODE = B.SC_CUST_PROD_CODE WHERE `SC_PRICE_HIST_STATUS` = '1' AND `SC_PRICE_HIST_INSERT` = '1' AND A.SC_COMPANY_ID = '$company_id' ORDER BY B.SC_PRODUCT_NAME,`SC_ARTICLE_ID`";
               //error_log($query_article);
              $result_article = mysqli_query($conn,$query_article);

              while ($row = mysqli_fetch_assoc($result_article))

              {
                $query_seller = "SELECT `SC_SELLER_NAME`, `SC_SELLER_COUNT`, `SC_GROSS_PRICE`,`SC_NET_PRICE`, `SC_CONV_GROSS`, `SC_CONV_NET`, `SC_DELIVERY_PRICE`, `SC_CURRENCY`, `SC_LAST_UPDATED` FROM `SC_SELLER_TBL` WHERE `SC_SELLER_INSERT` = '1' AND SC_AMA_ASIN = '" .$row['SC_ASIN_CD']. "' AND SC_CUST_PROD_CODE = '" .$row['SC_CUST_PROD_CODE']. "' ORDER BY `SC_SELLER_NAME`";
                //error_log($query_seller);
                //echo $query_seller;
                $result_seller = mysqli_query($conn,$query_seller);

                while ($row1 = mysqli_fetch_assoc($result_seller))
                {
                  $seller_arr = array ("seller_name" =>$row1['SC_SELLER_NAME'],"gross_price_seller" =>$row1['SC_GROSS_PRICE'], "net_price_seller" =>$row1['SC_NET_PRICE'], "conv_gross_price_seller" =>$row1['SC_CONV_GROSS'], "conv_net_price_seller" =>$row1['SC_CONV_NET'], "delivery_price" =>$row1['SC_DELIVERY_PRICE'], "currency" =>$row1['SC_CURRENCY'], "last_updated" =>$row1['SC_LAST_UPDATED']);
                  array_push($seller_array, $seller_arr);
                }

                $Article_Info=array("product_name" => $row['SC_PRODUCT_NAME'],"product_code"=>$row['SC_CUST_PROD_CODE'],"ASIN"=>$row['SC_ASIN_CD'],"article_id"=>$row['SC_ARTICLE_ID'],"URL"=>$row['SC_DEFAULT_SELLER'],"default_seller"=>$row['SC_DEFAULT_SELLER'], "gross_price"=>$row['SC_LAST_PRICE'], "net_price"=>$row['SC_NET_PRICE'], "conv_gross_price"=>$row['SC_CONV_PRICE'], "conv_net_price"=>$row['SC_CONV_NET'], "currency"=>$row['SC_CURRENCY'], "domain"=>$row['SC_DOMAIN'], "country"=>$row['SC_COUNTRY_CODE'], "buy_box_seller"=>$row['SC_BUY_BOX_SELLER'], "total_num_seller"=>"5", "seller_info"=>$seller_array);
                array_push($article_array, $Article_Info);
              }
              $jsonDataEncoded1 = json_encode($article_array,JSON_UNESCAPED_UNICODE|JSON_INVALID_UTF8_IGNORE);
              echo $jsonDataEncoded1;
die();
}

A: You are bringing a lot of data and that is causing PHP to allocate more memory than is allocated to it.
You can increase this number by changing your php.ini configuration or use
ini_set('memory_limit', '512M');
as your first line in PHP


text:
Q: Why I was able to fix a broken package with aptitude but I could not with either apt-get or synaptic? Yesterday I upgraded my Debian Testing and Audacious stopped to work. Troubleshooting I found that the problem was that it was updated to a recent version but the needed plugins were not. I tried to manually install the plugins from its website but I couldn't, missing a lot of packages, and every time I installed one it requires other and so on.
So my solution was to change my repositories to wheezy and go back to the old version. After this, audacious was broken and I couldn't fix it. I tried apt-get clean, apt-get install -f and the Fix broken packages at Synaptic. Neither worked. However, I installed it using aptitude and it was installed after automatically fix the dependencies.
My question is, why neither apt-get nor Synaptic weren't able to fix the dependencies, and aptitude was?

A: Aptitude is more aggressive at the time of solving dependencies, in fact it creates several recipes to solve the dependencies. What you probably did, you tried to install/remove/upgrade, aptitude detected some broken dependencies and asked you if you accept the proposed fix.
You didn't noticed (pressing YYYY) but aptitude did asked you and you accepted the fix.

A: In this "similar" question What is the real difference between "apt-get" and "aptitude"? (How about "wajig"?) there is a point that basically explains this situation.
"If the actions (installing, removing, updating packages) that you want to take cause conflicts, aptitude can suggest several potential resolutions. apt-get will just say "I'm sorry Dave, I can't allow you to do that"


text:
Q: Accumulation points in metric space Let $M$ a metric space, $A \subset M$, $a_0$ is an accumulation point of $A$ if  and only if for every neighborhood $V$ de $a_0$, $V \cap A$ contains a point $a \ne a_0$ such that $a \in A$
I do not how can I begin this prove with metric space, I stuck in this excessive, can someone help me please?...

A: If $a_0$ is an accumulation, we have that for every open ball with center on $a_0$ e radiuns $r >0$ $B_r$, $B_r\cap (A - \{a_0\}) \neq \emptyset$, therefore how for every neighborhood $V$ of $a_0$, there is $r>0$ such that $B_r(a_0)\subset  V$, then $V\cap (A - \{a_0\}) \neq \emptyset$.
If for every neighborhood $V$ of $a_0$, we have that $V\cap (A - \{a_0\}) \neq \emptyset$, particularly $B_r(a_0) \cap (A - \{a_0\}) \neq \emptyset$ for every $r>0$.


text:
Q: XML: content is not allowed in trailing section I'm getting these errors

Multiple annotations found at this line:
    - error: Error parsing XML: not well-formed
     (invalid token)
    - Content is not allowed in trailing section.

on this XML file...
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
    android:state_enabled="false"
        android:drawable="@drawable/btn_red" />
    <item
        android:state_pressed="true"
        android:state_enabled="true"
        android:drawable="@drawable/btn_orange" />
    <item
        android:state_focused="true"
        android:state_enabled="true"
        android:drawable="@drawable/btn_orange" />
    <item
        android:state_enabled="true"
        android:drawable="@drawable/btn_black" />
</selector>

Probably quite simple for you people who know XML. Any idea?

A: <resources>
    <string name="app_name">Test App</string>
</resources>
testData("test");

If in any xml file unfortunately this type of line is remaining then this error is occur.

A: Do you have any extraneous characters after the closing tag (I'm assuming what you posted is just an excerpt from the file, since it obviously won't work without at least a closing  tag)?

A: If you pasted it from the site you link to, there are two little hyphens you don't want.  One after the close of </selector> and one just before the first <item>.  Get rid of those, and all will be well.

A: This happened to me as well after multiple modifications on the file, I just cut out the content and pasted to Notepad++ (to remove any formatting). Saved my empty .xml file and closed the project. Reopened the project and put back the data from Notepad++. It helped me.

A: Some end tag character like '>' should be there in your xml. Remove this and error will be gone.


text:
Q: Java Fx displayed Exception in Application start method I am a beginner of JavaFX. When I create a JavaFX project with Scene Builder. I just run and check the default user interface and got an error. The full stack trace is attached below. I don't know how to solve this problem.
Exception in Application start method
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
    at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$1(LauncherImpl.java:182)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NullPointerException: Location is required.
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3207)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
    at javafxapplication9.JavaFXApplication9.start(JavaFXApplication9.java:22)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$7(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$5(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$6(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$4(WinApplication.java:186)
    ... 1 more
Exception running application javafxapplication9.JavaFXApplication9
C:\Users\kobinath\Documents\NetBeansProjects\JavaFXApplication9\nbproject\build-impl.xml:1052: The following error occurred while executing this line:
C:\Users\kobinath\Documents\NetBeansProjects\JavaFXApplication9\nbproject\build-impl.xml:806: Java returned: 1
BUILD FAILED (total time: 1 second)

i don't know why. what i tried so far i attached below
public class JavaFXApplication9 extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));

        Scene scene = new Scene(root);

        stage.setScene(scene);
        stage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

FXMLDocumentController
public class FXMLDocumentController implements Initializable {

    @FXML
    private Label label;

    @FXML
    private void handleButtonAction(ActionEvent event) {
        System.out.println("You clicked me!");
        label.setText("Hello World!");
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
    }

}


text:
Q: How to use Fixed family bitmap fonts in fbterm I work in a text terminal a lot on my Debian 12 box, and I like the bitmap font family it uses, which IIRC is called Fixed. I use vim for pretty much everything, and it works well in this environment.
However, for some programming tasks, I need a language server, and for this, I use neovim. The only way I've gotten neovim to play nicely in the TTY is to run it in 256color mode from within fbterm. The problem is, I cannot get the nice bitmap fonts to work in fbterm.
In particular, if I try the obvious thing, passing fbterm --font-names=fixed, it is definitely not the same look-and-feel as the raw TTY.

How can I get fbterm to look the same, font-wise, as the raw text terminal?


text:
Q: Javascript count how many selected from multiple selects This is HTML:

<select class="form-control selectVitrat" name="PVSuperior" id="PVSuperior">
      <option value="NO">NU</option>
      <option value="YES">DA</option>
    </select>
<select class="form-control selectVitrat" name="PVIntermediar9" id="PVIntermediar9">
      <option value="NO">NU</option>
      <option value="YES">DA</option>
    </select>
<select class="form-control selectVitrat" name="PVIntermediar8" id="PVIntermediar8">
      <option value="NO">NU</option>
      <option value="YES">DA</option>
    </select>

How can I count how many Yes I selected from these multiple selections?

A: In JavaScript, you can use getElementsByTagName to get all the select. And using for loop, you can check how many select have YES values:

function checkTotalYes() {
  var selectElements = document.getElementsByTagName("select");
  var count = 0;
  for (var i = 0; i < selectElements.length; i++) {
    if (selectElements[i].value == 'YES')
      count++;
  }
  console.log('Total Yes: ' + count);
}

checkTotalYes();
<select class="form-control selectVitrat" name="PVSuperior" id="PVSuperior" onchange="checkTotalYes()">
  <option value="NO">NU</option>
  <option value="YES">DA</option>
</select>
<select class="form-control selectVitrat" name="PVIntermediar9" id="PVIntermediar9" onchange="checkTotalYes()">
  <option value="NO">NU</option>
  <option value="YES">DA</option>
</select>
<select class="form-control selectVitrat" name="PVIntermediar8" id="PVIntermediar8" onchange="checkTotalYes()">
  <option value="NO">NU</option>
  <option value="YES">DA</option>
</select>


text:
Q: Angular check if user logged in is admin I have this line to check if the current user is admin or normal user
if (this.responseData.user.appUserRole === 'ADMIN') {
        //.......
      } else {
        //......
      }

it's safe to store value like isAdmin in local storage?
or there is another way to put in variable to use it another place?

A: Depends... for example is the site vulnerable to XSS attack local storage is a not safe place to save user credentials in general.
The other reason is that people can clear their cache.
In some cases in my opinion is better to save this information directly using cookie.
I hope that my explanation is clear


text:
Q: cardview overflow menu in fragment i have achieved cardview overflow menu in cardviewactivity but dont know how do i use the same in fragment
i have tab views and tab fragments, now each fragment is accessing cardview-list view-activity.
here's the screen shot where i am trying to achieve:

Problem: i cant able to get the overflow menu for each cardview listitem. app has stopped.
card view xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/white">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_gravity="center"
        android:layout_width="fill_parent"
        android:layout_height="80dp"
        android:layout_margin="5dp"
        card_view:cardCornerRadius="2dp"
        card_view:contentPadding="10dp"
        android:foreground="?android:attr/selectableItemBackground">

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">

            <TextView
                android:id="@+id/textView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:layout_alignParentTop="true"/>

            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:layout_below="@+id/textView"/>
   ----->         <ImageButton
                android:id="@+id/img_menu"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                 android:background="@drawable/ic_action_navigation_more_vert"
                android:layout_alignParentRight="true"
                android:layout_marginTop="12dp"
               android:onClick="showPopup"/>

        </RelativeLayout>
    </android.support.v7.widget.CardView>

</LinearLayout>

MY RECYCLER VIEW ADAPTER
public class MyRecyclerViewAdapter extends RecyclerView
        .Adapter<MyRecyclerViewAdapter
        .DataObjectHolder> {
    private static String LOG_TAG = "MyRecyclerViewAdapter";
    private ArrayList<DataObject> mDataset;
    private static MyClickListener myClickListener;
    Context mContext = null;
    public static class DataObjectHolder extends RecyclerView.ViewHolder{
          /*  implements View
            .OnClickListener {*/
        TextView label;
        TextView dateTime;
        ImageButton overflowMenu;
        public View overflow;

        public DataObjectHolder(View itemView) {
            super(itemView);
            label = (TextView) itemView.findViewById(R.id.textView);
            dateTime = (TextView) itemView.findViewById(R.id.textView2);
          overflowMenu = (ImageButton) itemView.findViewById(R.id.img_menu);
            Log.i(LOG_TAG, "Adding Listener");
          // itemView.setOnClickListener(this);
           // overflowMenu.setOnClickListener(this);
        }

      /*  @Override
        public void onClick(View v) {
           *//* myClickListener.onItemClick(getAdapterPosition(), v);
            Toast.makeText(getAdapterPosition(), "STRING MESSAGE", Toast.LENGTH_LONG).show();*//*
        }*/
    }

    public void setOnItemClickListener(MyClickListener myClickListener) {
        this.myClickListener = myClickListener;
    }

    public MyRecyclerViewAdapter(ArrayList<DataObject> myDataset) {
        mDataset = myDataset;
    }

    @Override
    public DataObjectHolder onCreateViewHolder(ViewGroup parent,
                                               int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_view_row, parent, false);

        DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
        return dataObjectHolder;
    }

    @Override
    public void onBindViewHolder(DataObjectHolder holder, int position) {

        holder.label.setText(mDataset.get(position).getmText1());
        holder.dateTime.setText(mDataset.get(position).getmText2());

        holder.overflowMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                PopupMenu popup = new PopupMenu(mContext, view);
                MenuInflater inflater = popup.getMenuInflater();
                inflater.inflate(R.menu.card_overflow_menu, popup.getMenu());
                popup.setOnMenuItemClickListener(new MyMenuItemClickListener());
                popup.show();
            }
        });

    }

    public void addItem(DataObject dataObj, int index) {
        mDataset.add(index, dataObj);
        notifyItemInserted(index);
    }

    public void deleteItem(int index) {
        mDataset.remove(index);
        notifyItemRemoved(index);
    }

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

    public interface MyClickListener {
        public void onItemClick(int position, View v);
    }

    private class MyMenuItemClickListener implements PopupMenu.OnMenuItemClickListener {
        public MyMenuItemClickListener() {
        }

        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            switch (menuItem.getItemId()) {
                case R.id.one:
                    Toast.makeText(mContext, "Action 1", Toast.LENGTH_SHORT).show();
                    return true;
                case R.id.two:
                    Toast.makeText(mContext, "Action 2", Toast.LENGTH_SHORT).show();
                    return true;
                default:
            }
            return false;
        }

    }
}

fragment in which i am calling overflow menu
 private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private static String LOG_TAG = "CardViewActivity";
    ImageButton overflowMenu;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // return inflater.inflate(R.layout.activity_card_view, null);
        View rootView = inflater.inflate(R.layout.activity_card_view, container, false);
        overflowMenu = (ImageButton) rootView.findViewById(R.id.img_menu);
        mRecyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(mLayoutManager);
        mAdapter = new MyRecyclerViewAdapter(getDataSet());
        mRecyclerView.setAdapter(mAdapter);

        return rootView;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.card_overflow_menu, menu);

    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.one:
                Toast.makeText(getContext(), " Clicked 1 ", Toast.LENGTH_LONG).show();
                return true;

            case R.id.two:
                Toast.makeText(getContext(), "Clicked 2 ", Toast.LENGTH_LONG).show();
                return true;

            default:
                break;
        }

        return false;
    }

 /*   public void showPopup(View v) {
        PopupMenu popup = new PopupMenu(getActivity(), v);
        MenuInflater inflater = popup.getMenuInflater();
        inflater.inflate(R.menu.card_overflow_menu, popup.getMenu());
        popup.show();

        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.one:
                        //Or Some other code you want to put here.. This is just an example.
                        Toast.makeText(getActivity(), " Clicked 1 " + " : ", Toast.LENGTH_LONG).show();
                        break;
                    case R.id.two:

                        Toast.makeText(getActivity(), "Clicked 2 " + " : ", Toast.LENGTH_LONG).show();

                        break;

                    default:
                        break;
                }

                return true;
            }
        });

    }*/

    private ArrayList<DataObject> getDataSet() {
        ArrayList results = new ArrayList<DataObject>();
        for (int index = 0; index < 20; index++) {
            DataObject obj = new DataObject("Test " + index,
                    "Doc number " + index);
            results.add(index, obj);
        }
        return results;
    }
}

Error i am facing:
java.lang.IllegalStateException: Could not find method showPopup(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatImageButton with id 'img_menu'
                                                                          at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:325)
                                                                          at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
                                                                          at android.view.View.performClick(View.java:4802)
                                                                          at android.view.View$PerformClick.run(View.java:20101)
                                                                          at android.os.Handler.handleCallback(Handler.java:810)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                          at android.os.Looper.loop(Looper.java:189)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:5532)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at java.lang.reflect.Method.invoke(Method.java:372)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:950)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)

A: If you want to create overflow menu for CardView in your list, you should create it in RecyclerView adapter itself.
Here is code
 viewHolder.overflow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            PopupMenu popup = new PopupMenu(mContext, view);
            MenuInflater inflater = popup.getMenuInflater();
            inflater.inflate(R.menu.menu_action, popup.getMenu());
            popup.setOnMenuItemClickListener(new MyMenuItemClickListener());
            popup.show();
        }
    });

Where overflow is image icon inside CardView and viewHolder is object of ViewHolder class. Now create click event for context or overflow menu.
class MyMenuItemClickListener implements PopupMenu.OnMenuItemClickListener {

    public MyMenuItemClickListener() {
    }

    @Override
    public boolean onMenuItemClick(MenuItem menuItem) {
        switch (menuItem.getItemId()) {
            case R.id.action_first:
                Toast.makeText(mContext, "Action 1", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.action_second:
                Toast.makeText(mContext, "Action 2", Toast.LENGTH_SHORT).show();
                return true;
            default:
        }
        return false;
    }
}

And you have to create a separate Menu resource file for context menu.
Change this
public MyRecyclerViewAdapter(ArrayList<DataObject> myDataset) {
    mDataset = myDataset;
}

To
public MyRecyclerViewAdapter(Context context, ArrayList<DataObject> myDataset) {
    mContext = context;
    mDataset = myDataset;
}

A: Your question is not clear , can you show your code here.
I think you may doing onClick in wrong way.
just follow that link
java.lang.illegalstateexception could not find a method (view) in the activity class android fragment


text:
Q: How to remove Favicon in Springboot application? I want to remove favicon in my spring boot application. I tried to include below property in application.properties file. but still not able to achieve it.
spring.mvc.favicon.enabled

I followed the below link also but it is not working. http://www.baeldung.com/spring-boot-favicon


text:
Q: packaging rails applications in a gem i am thinking of releasing a rails application as a gem. it's sort of a wiki application which also stores user data in the db directory. what would be a good way to go to avoid the user data being overwritten, when a gem update is done?
example:
1) user gets version 1 of the gem/application. the data is stored in the gem directory.
2) user performs a gem update and gets version 1.1 -> the data is lost! (because there is a second directory now)
my questions are:

*

*does it make sense to package rails applications in gems?

*are there example for other rails applications that are packaged as a gem?

*how would the problem with the user data be solved?

thanks!
z

A: I guess using SVN or Git is the best way to distribute and update your application.

A: Gem is a bad idea for an application.
I would look into Warbler: http://caldersphere.rubyforge.org/warbler/


text:
Q: How to set a reference row and let other rows to divide its values? Here is a big data frame with different cells and their mRNA expression data:

A
Gene 1
Gene 2
Gene 3
Gene 4
…

Cell 1
9
12
24
42
30

Cell 2
3
6
12
21
15

Cell 3
6
42
48
84
45

…

Now I want the second column to be the standard and get this:

A
Gene 1
Gene 2
Gene 3
Gene 4
…

Cell 1
3
2
2
2
2

Cell 2
1
1
1
1
1

Cell 3
2
7
4
4
3

…

A: I think you can try rep like below
df/df[rep(2,nrow(df)),]

A: Here is one possible way to solve your problem (assuming that your data is named df):
df[] = Map("/", df, df[2,])


text:
Q: UDP communication is not working. Using the WinSock2 library I wrote two simple programs, both using UDP. One of them sends packets of data and the other receives them.
I ran both of these programs in the following circumstances:

*

*The firewall was turned off.

*I forwarded the corresponding port, even though I tested it on my LAN.

I tested it while using localhost, ran both programs on the same computer.  But it does not work.
The sender program:
#include <iostream>

#include <WinSock2.h>
#include <WS2tcpip.h>

#pragma comment(lib, "Ws2_32.lib")

#define PORT 1243
#define PORTSTR "1243"
#define IPSTR "127.0.0.1"

#define CYCLECOUNT 100

#define MESS "Hello world!"

int main()
{
    /// True if the socket is initialized.
    bool bSockInit = false;

    /// Initialization.
    WSADATA wsaData;
    if (int err; (err = WSAStartup(MAKEWORD(2, 2), &wsaData)) != 0)
    {
        std::cout << "Failed the startup with error: " << err << '\n';
        goto END;
    }

    /// Creating the socket.
    SOCKET sock;
    if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET)
    {
        std::cout << "Failed the socket with error: " << WSAGetLastError() << '\n';
        goto END;
    }
    bSockInit = true;

    /// Creating the address, to which data is sent.
    sockaddr_in remoteAddr;
    ZeroMemory((PVOID) &remoteAddr, sizeof(remoteAddr));

    // Setting the address familiy to ipv4.
    remoteAddr.sin_family = AF_INET;

    // Setting the port in network byte order.
    remoteAddr.sin_port = htons(PORT);

    // Setting the address from a c-style string.
    InetPton(AF_INET, TEXT(IPSTR), (PVOID) &remoteAddr.sin_addr);

    /// Sending the messages.
    while (std::cin.get() == '\n')
    {
        int byteCount = 0;
        for (int i = 0; i < CYCLECOUNT; ++i)
        {
            byteCount += sendto(sock, MESS, sizeof(MESS), 0, (sockaddr*) &remoteAddr, sizeof(remoteAddr));
        }

        /// Print the number of bytes sent.
        std::cout << "Sent " << byteCount << " bytes times to " IPSTR ":" PORTSTR << ".";
    }

END:
    // If the socket was initialized successfully then dispose of it.
    if (bSockInit)
    {
        std::cout << "closesocket finished with code: " << closesocket(sock) << '\n';
    }

    std::cout << "WSACleanup finished with code: " << WSACleanup() << '\n';

    std::cin.get();
    return 0;
}

The receiver program:
#include <iostream>

#include <WinSock2.h>

#pragma comment(lib, "Ws2_32.lib")

// The port where data is to be received.
#define PORT 1243

int main(int argc, char** argv)
{
    /// True if the socket is initialized.
    bool bSockInit = false;

    /// Initialization.
    WSADATA wsaData;
    if (int err; (err = WSAStartup(MAKEWORD(2, 2), &wsaData)) != 0)
    {
        std::cout << "Failed the startup with error: " << err << '\n';
        goto END;
    }

    /// Creating the socket.
    SOCKET sock;
    if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET)
    {
        std::cout << "Failed the socket with error: " << WSAGetLastError() << '\n';
        goto END;
    }
    bSockInit = true;

    /// Creating the address.
    sockaddr_in thisAddr;
    ZeroMemory((PVOID) &thisAddr, sizeof(thisAddr));

    // Setting the address familiy to ipv4.
    thisAddr.sin_family = AF_INET;

    // Setting the port in network byte order.
    thisAddr.sin_port = htons(PORT);

    // Setting the address to any, so that incoming data, whichever the ipv4-address is, is accepted.
    thisAddr.sin_addr.S_un.S_addr = htonl(ADDR_ANY);

    if (bind(sock, (sockaddr*)&thisAddr, sizeof(thisAddr)) == SOCKET_ERROR)
    {
        std::cout << "Failed the bind with error: " << WSAGetLastError() << '\n';
        goto END;
    }

    // Buffer to store incoming bytes.
    char buf[1024];

    // The number of bytes that were received.
    int len;

    // Data about the sender.
    sockaddr from;
    int fromlen;
    fromlen = 0;
    // ~Data about the sender.

    // Waiting for a message, containing at least one byte to arrive.
    while ((len = recvfrom(sock, buf, sizeof(buf), NULL, &from, &fromlen)) <= 0);

    // Printing the message that was just received and placed into the buffer.
    for (int i = 0; i < len; ++i)
    {
        std::cout << buf[i];
    }

END:
    // If the socket was initialized successfully then dispose of it.
    if (bSockInit)
    {
        std::cout << "closesocket finished with code: " << closesocket(sock) << '\n';
    }

    std::cout << "WSACleanup finished with code: " << WSACleanup() << '\n';

    std::cin.get();
    return 0;
}

If you have some spare time, run both of the programs and see what happens.
To send data with the sender program you you need to press the ENTER/RETURN key.
I would also appreciate examples of such programs that work.

A: On the sender, you are not doing any error handling on sendto() at all.
On the receiver, your reading loop is not setting fromlen correctly on each call to recvfrom(), which is likely to make recvfrom() fail with a WSAEFAULT error, which you are not handling or reporting.  If recvfrom() fails, you get stuck in an endless loop.  Also, your std::cout output should be inside the reading loop, writing the data to the console only when recvfrom() is successful.  Also, recvfrom() returning 0 is not an error condition, since UDP allows 0-byte messages, unlike TCP.
Try this instead:
#include <iostream>

#include <WinSock2.h>
#include <WS2tcpip.h>

#pragma comment(lib, "Ws2_32.lib")

#define PORT 1243
#define PORTSTR "1243"
#define IPSTR "127.0.0.1"

#define CYCLECOUNT 100

#define MESS "Hello world!"

int main()
{
    SOCKET sock = INVALID_SOCKET;

    /// Initialization.
    WSADATA wsaData;
    if (int err; (err = WSAStartup(MAKEWORD(2, 2), &wsaData)) != 0)
    {
        std::cerr << "Failed the startup with error: " << err << '\n';
        goto FINISHED;
    }

    /// Creating the socket.
    if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET)
    {
        std::cerr << "Failed the socket with error: " << WSAGetLastError() << '\n';
        goto CLEANUPWSA;
    }

    /// Creating the address, to which data is sent.
    sockaddr_in remoteAddr;
    ZeroMemory(&remoteAddr, sizeof(remoteAddr));

    // Setting the address familiy to ipv4.
    remoteAddr.sin_family = AF_INET;

    // Setting the port in network byte order.
    remoteAddr.sin_port = htons(PORT);

    // Setting the address from a c-style string.
    inet_pton(AF_INET, IPSTR, &remoteAddr.sin_addr);

    /// Sending the messages.
    while (std::cin.get() == '\n')
    {
        int byteCount = 0;
        for (int i = 0; i < CYCLECOUNT; ++i)
        {
            int sent = sendto(sock, MESS, sizeof(MESS), 0, (sockaddr*) &remoteAddr, sizeof(remoteAddr));
            if (sent == SOCKET_ERROR)
            {
                std::cerr << "Failed the send with error: " << WSAGetLastError() << '\n';
                goto CLEANUPSCKT;
            }
            byteCount += sent;
        }

        /// Print the number of bytes sent.
        std::cout << "Sent " << byteCount << " bytes to " << IPSTR << ":" << PORTSTR << ".";
    }

CLEANUPSCKT:
    // If the socket was initialized successfully then dispose of it.
    std::cout << "closesocket finished with code: " << closesocket(sock) << '\n';

CLEANUPWSA:
    std::cout << "WSACleanup finished with code: " << WSACleanup() << '\n';

FINISHED:
    std::cin.get();
    return 0;
}

#include <iostream>

#include <WinSock2.h>

#pragma comment(lib, "Ws2_32.lib")

// The port where data is to be received.
#define PORT 1243

int main(int argc, char** argv)
{
    SOCKET sock = INVALID_SOCKET;

    /// Initialization.
    WSADATA wsaData;
    if (int err; (err = WSAStartup(MAKEWORD(2, 2), &wsaData)) != 0)
    {
        std::cerr << "Failed the startup with error: " << err << '\n';
        goto FINISHED;
    }

    /// Creating the socket.
    if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET)
    {
        std::cerr << "Failed the socket with error: " << WSAGetLastError() << '\n';
        goto CLEANUPWSA;
    }

    /// Creating the address.
    sockaddr_in thisAddr;
    ZeroMemory(&thisAddr, sizeof(thisAddr));

    // Setting the address familiy to ipv4.
    thisAddr.sin_family = AF_INET;

    // Setting the port in network byte order.
    thisAddr.sin_port = htons(PORT);

    // Setting the address to any, so that incoming data, whichever the ipv4-address is, is accepted.
    thisAddr.sin_addr.s_addr = htonl(ADDR_ANY);

    if (bind(sock, (sockaddr*)&thisAddr, sizeof(thisAddr)) == SOCKET_ERROR)
    {
        std::cerr << "Failed the bind with error: " << WSAGetLastError() << '\n';
        goto CLEANUPSCKT;
    }

    // Buffer to store incoming bytes.
    char buf[1024];

    // The number of bytes that were received.
    int len;

    // Data about the sender.
    sockaddr_in from;
    int fromlen;

    // Waiting for a message, containing at least one byte to arrive.
    do
    {
        fromlen = sizeof(from);
        len = recvfrom(sock, buf, sizeof(buf), NULL, (sockaddr*)&from, &fromlen);
        if (len == SOCKET_ERROR)
        {
            std::cerr << "Failed the recv with error: " << WSAGetLastError() << '\n';
            goto CLEANUPSCKT;
        }

        std::cout << "Received " << len << " byte(s) from " << inet_ntoa(from.sin_addr.s_addr) << ":" << ntohs(from.sin_port);

        if (len > 0)
        {
            // Printing the message that was just received and placed into the buffer.
            std::cout << ": ";
            std::cout.write(buf, len);
            std::cout << '\n';
            break;
        }

        std::cout << ", still waiting" << '\n';
    }
    while (true);

CLEANUPSCKT:
    // If the socket was initialized successfully then dispose of it.
    std::cout << "closesocket finished with code: " << closesocket(sock) << '\n';

CLEANUPWSA:
    std::cout << "WSACleanup finished with code: " << WSACleanup() << '\n';

FINISHED:
    std::cin.get();
    return 0;
}


text:
Q: Format jinja template as INT in operator parameter in Airflow I'm trying to format a jinja template parameter as an integer so I can pass it to an operator which expects INT (could be custom or PythonOperator) and I'm not able to.
See sample DAG below. I'm using the built-in Jinja filter | int but that's not working - the type remains <class 'str'>
I'm still new with Airflow but I don't think this is possible based on what I've read about Jinja/Airflow works. I see two main workarounds:

*

*Change the operator parameter to expect string and handle the conversion underneath.

*Handle this conversion in a separate PythonOperator which converts the string to an int and export that using xcom/task context. (I think this will work but not sure)
Please let me know of any other workarounds
def greet(mystr):
    print (mystr)
    print(type(mystr))

default_args = {
    'owner': 'airflow',
    'start_date': days_ago(2)
}

dag = DAG(
    'template_dag',
    default_args=default_args,
    description='template',
    schedule_interval='0 13 * * *'
)

with dag:

    # foo = "{{ var.value.my_custom_var | int }}"  # from variable
    foo = "{{ execution_date.int_timestamp | int }}"  # built in macro

    # could be MyCustomOperator
    opr_greet = PythonOperator(task_id='greet',
                               python_callable=greet,
                               op_kwargs={'mystr': foo}
                               )

    opr_greet

Airflow 1.10.11

A: Updated answer:
As of Airflow 2.1, you can pass render_template_as_native_obj=True to the dag and Airflow will return the Python type (dict, int, etc) instead of string. See this pull request
dag = DAG(
    dag_id="example_template_as_python_object",
    schedule_interval=None,
    start_date=days_ago(2),
    render_template_as_native_obj=True,
)

Old answer for prior versions:
I found a related question that provides the best workaround, IMO.
Airflow xcom pull only returns string
The trick is to use a PythonOperator, do the datatype conversion there and then call the main operator with the parameter. Below is an example in converting a json string to a dict object. Same can apply for converting string to int, etc.
def my_func(ds, **kwargs):
    ti = kwargs['ti']
    body = ti.xcom_pull(task_ids='privious_task_id')
    import_body= json.loads(body)
    op = CloudSqlInstanceImportOperator(
            project_id=GCP_PROJECT_ID,
            body= import_body,
            instance=INSTANCE_NAME,
            gcp_conn_id='postgres_default',
            task_id='sql_import_task',
            validate_body=True,
        )
    op.execute()

p = PythonOperator(task_id='python_task', python_callable=my_func)

A: I believe Jinja is going always to return you a string: the template is a string and replacing values inside the template will return you a string.
If you are sure that foo is always an integer, you can do
opr_greet = PythonOperator(task_id='greet',
                           python_callable=greet,
                           op_kwargs={'mystr': int(foo)}
                           )

Update: it looks like Airflow uses the render method from Jinja2, which returns a Unicode string.
At this point, if you can modify greet, it is easier to manage the input parameter in that function.


text:
Q: How to get few words from the long string in non sequential order Hi I have a custom setting which will contain the some part of "Subject", now when I will receive an email I need to compare this custom setting value from the "Subject" of the email. below is the code but Contains function is not working as it works only for Sequencing string.
In below code consider str2 is the custom setting value and str1 is the subject value from the inbound email
string str1= 'As Oy Viherlaaksonranta 9 osoitteenmuutos';
string str2= 'As Oy osoitteenmuutos';

if(str2.contains(str1)){
   system.debug('inside if');
}

In the above code Contains is returning false. Can someone please help me, please let me know if any inputs from my side

A: Try utilising split and Set from Apex Class. Once you've set of subject defined in custom setting and email received. Iterate over them and check if keywords match or not.
Refer below example:
string str1= 'As Oy Viherlaaksonranta 9 osoitteenmuutos';
string str2= 'As Oy osoitteenmuutos';
Set<String> subjectKeywordsSet = new Set<String>(str2.split(' '));
Set<String> receivedEmailSubject =  new Set<String>(str1.split(' '));

Boolean isSubjectMatches = true;
for (String subjectKey : subjectKeywordsSet) {
  if (!receivedEmailSubject.contains(subjectKey))
    isSubjectMatches = false;
}
if(isSubjectMatches){
   system.debug('inside if');
}

Alternate way would be to use Regex.

A: Based on your two strings, You're gonna need a custom setting that has a comma separated string of keywords. You may also want to consider a match threshhold. For instance if the subject contains 80% of the keywords, you may want to take action (as subjects are unpredictable usually).
Below is a sample of what you can try. As written, this could cause false positives if the keywords are out of order so you may have to update the code if that is something you care about.
Map<String, SubjectKeywords__c> settings = SubjectKeywords__c.getAll();

for (Email email : emails) {
    Set<String> subject = new Set<String>(email.subject.split(' '));

    for (SubjectKeywords__c setting : settings) {
        Set<String> keywords = new Set<String>(setting.keywords__c.split(','));
        integer matchCount = 0;

        for (String keyword : keywords) {
            if (subject.contains(keyword)) {
                matchCount += 1;
            }
        }

        // Check to see if match count is above a set threshold (say, 80%)
        // if (matchCount / keywords.size() >= settings.threshhold__c / 100) {
        // }

        // Check to see if match count is exact if you do not want to use a threshold
        // if (matchCount == keywords.size()) {
        // }
    }
}

I'm not super familiar with your language. According to google it's finnish and "osoitteenmuutos" appears to translate to "address change". If that is the case, than maybe you don't want to include the "As Oy" in your search as these seem to be words that may appear in emails related to other topics as well. If you're looking for anything related to address change then your custom setting should only include the keyword "osoitteenmuutos".
This is mostly an uneducated guess though so I apologize if I made any mistakes during translation but the principal remains, you should try to keep your keywords to a minimum for best possible matches.


text:
Q: Need OpenGL ES 2.0 Emulator I'm getting into Android development and am looking for a good OpenGL ES emulator other than the AVD (doesn't have full opengl es 2.0 support yet)
Suggestions welcome!
Must be free.
Preferably easy to use
thanks!

A: You can use Leapdroid emulator which fully supports opengl es 2.0. http://www.leapdroid.com

A: You may be able to convince Mesa to act as such.


text:
Q: UPDATE STATEMENT with WHERE clause I want to update table sheet and set column value of hproject to 'yes' where customer having hproject='yes'
UPDATE `sheet` SET `hproject` =  'yes' WHERE (
SELECT `customer`
FROM `sheet`
WHERE `hproject` =  'yes'
)

Above query is not working, i'll be grateful for any help or guidance.
Regards

A: try that :
  UPDATE `sheet` SET `hproject` =  'yes' WHERE `customer` in (
  select * from(
  SELECT `customer`
  FROM `sheet`
  WHERE `hproject` =  'yes'
 )t
 )


text:
Q: Can i use $store.commit() in mounted() vuejs? I have a simple question.
Can I use vuex .commit() in mounted() vuejs?
I can use getters but somehow commit doesn't work...
Edit
I have found an issue.
I'm making a leaflet-draw wrapper.
I'm using mounted() hoook to get the wrapper component(child component) in parent component. I've added leaflat-draw vanilla js code in mounted() hook and here's a problem.

*

*in vanilla js event in mounted() hook, 'this' keyword doesn't work. (=undefined)
e.g.
 objectLayer.on("layeradd", function(e) {

          let layer = e.layer;
          layer.on("click", onClickFeatureSelct, layer);
  }

I didn't have enough time to test cases for other event, so I've posted a question to vue forum:
https://forum.vuejs.org/t/commit-of-undefined-in-mounted-valina-js-event-function/98431
Thanks for the comments guys! :)

A: Yes, you can use this.$store.commit('YOURCOMMITNAME', payload) in the created, beforeMount & mounted lifecycle hook of any component.

EDIT: I am not sure about your use case but if you need to use this, you should try fat arrow function. Something like
objectLayer.on("layeradd", e => {
    console.log(e, this.$store.getters.test);
    this.$store.commit('setData', payload);
});

OR may be define the function first OR try .bind(this)


text:
Q: Failed to find 'ANDROID_HOME' environment variable I recently went in to app development and I am using WebStorm for my IDE on Windows 7.
I created a skeleton Phonegap/Cordova project and replaced all the css/js/html files from a project that was made on Visual Studios 15.
Assuming that only the appearance of the program would change, however I started getting this error:

ERROR: Error: Failed to find 'ANDROID_HOME' environment variable. Try
  setting setting it manually. Failed to find 'android' command in your
  'PATH'. Try update your 'PATH' to include path to valid SDK directory.

I tryed some of the solutions i found online, like actually installing the android SDK and then adding ANDROID_HOME with a path to where i installed my sdk and adding %PATH%;%ANDROID_HOME%\tools;%ANDROID_HOME%\platform-tools to PATH.
However this didn't work ether.
I am new to the website, so sorry if I am being to vague or my bad English, any help will be appreciated

A: In your system environment variable add like this,In value give complete path to your JAVA sdk.It can work and also try this command in cmd
cordova platform update android


text:
Q: Send object from Java backend to JavaScript frontend via model I am trying to pass some objects from Java backend to the JavaScript frontend as following:
WeightController:
String jsonString = new JSONObject()
   .put("weightEntry", weightEntry).toString();

model.addAttribute("weightEntry", jsonString);

using the following library to create a json:
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20220320</version>
</dependency>

@Entity
@Table(name = "WeightEntry")
public class WeightEntry {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne()
    private User user;

    @OneToMany(mappedBy = "weightEntry")
    private Set<Image> imageSet = new HashSet<>();

    private double weight;
    private Date date;

    public WeightEntry() {}
}

<script>
    var obj = eval('('+'${weightEntry}'+')'); //this is not working
    var obj2 = [[${weightEntry}]] //this shows blank??
</script>

I found this on stackoverflow which is outdated (it seems)
How to access model attribute in Javascript


text:
Q: Does row sum and column sums equal for binary normal matrices? Given a matrix $A = (a_{ij})_{m \times m}$ we denote the $i$-th row as $a_{i*} = (a_{i,1}, a_{i,2}, \dots a_{i,m})$ and $i$-th column as $a_{*i} = (a_{1,i}, a_{2,i}, \dots, a_{m,i})^t$. We denote the $i$-th row, and column sum as $\sum a_{i*}$, and $\sum a_{*i}$, respectiely. A matrix $A$ is called a normal matrix if $A^t A = A A^t$, where $A^t$ denotes transpose of the matrix $A$. I am looking for a binary $(0,1)$ normal matrix such that $\sum a_{i*} \neq \sum a_{*i}$ for at lest one $i$. I didnot get any such matrix yet.
If you can construct such a matrix please share it with me.
If there exists no binary $(0,1)$ normal matrix $A = (a_{i,j})_{m \times m}$, such that $\sum a_{i*} \neq \sum a_{*i}$ holds, please give me a proof.
Thank you in advance.

A: For a binary matrix, the row sums are the diagonal elements $(AA^t)_{ii}=\sum_{j}a_{ij}a_{ij}=\sum_{j}a_{ij},$ while the column sums are the diagonal elements $(A^tA)_{ii}=\sum_{j}a_{ji}a_{ji}=\sum_{j}a_{ji}.$ For a normal matrix these must be equal.


text:
Q: Determine Version of .NET Software Running This may be a stupid question and/or a futile effort -- you've been warned...
I have a ASP .NET application (with the VB parts compiled to a DLL). This application has been around a while and the person who wrote it apparently messed up the old source code repository system. He is no longer around and I'm not clear on whether the source code I was given was a re-write or an older version (or by some strange luck the actual version of the website running).
Being that part of this website is running as a DLL, what is the best way I can go about in determining if the version of the source code I have matches what is running? I'm unable to setup an IIS server to throw this on (licensing/server cost/time/etc).
Is there a better way than compiling the project and then finding some disassembler and doing a comparison?

A:
Is there a better way than compiling the project and then finding some disassembler and doing a comparison?

That's what I've done in the past in your situation.

*

*Open each compiled assembly using ILSpy, and use the option "File / Save Code" to generate source files.

*Build the source code from your source code repository, and use ILSpy to generate source files.

*Compare the results of 1 and 2.
Obviously this won't give you the whole picture - you'll also need to compare aspx files, config files, ..., but it's the only approach I know.


text:
Q: WPF Checkboxes in Combobox Как достать Content только тех checkbox'ов (в C#), которые нажаты на данный момент?
  <ComboBox Name="LeagueClub" ItemsSource="{Binding Leagues}" Width="370">
     <ComboBox.ItemTemplate>
        <DataTemplate>
           <StackPanel>
              <CheckBox Content="{Binding}"></CheckBox>
           </StackPanel>
        </DataTemplate>
     </ComboBox.ItemTemplate>
  </ComboBox>

A: если, КМК, вы не используете MVVM, то простой путь мог бы выглядеть так:
1) поименовать StackPanel;
2) в коде C# выбрать из перечисления его дочерних элементов (они все только чекбоксы?) с помощью предикатов только (isCheked=true), т.е. например для:
XAML:
    <ComboBox x:Name="comboBox" HorizontalAlignment="Left" VerticalAlignment="Top">
        <ComboBoxItem>
            <StackPanel>
                <CheckBox Content="Aa" IsChecked="True"></CheckBox>
            </StackPanel>
        </ComboBoxItem>
        <ComboBoxItem>
            <StackPanel>
                <CheckBox Content="Bb" IsChecked="False"></CheckBox>
            </StackPanel>
        </ComboBoxItem>
        <ComboBoxItem>
            <StackPanel>
                <CheckBox Content="Cc" IsChecked="True"></CheckBox>
            </StackPanel>
        </ComboBoxItem>
    </ComboBox>

C#
var chekedContents = comboBox.Items.OfType<ComboBoxItem>().Where(cbi => ((((StackPanel)cbi.Content).Children[0].GetType() == typeof(CheckBox)) &
                                                                        (((CheckBox)((StackPanel)cbi.Content).Children[0]).IsChecked == true)
                                                                        )
                                                                )
                                                            .Select(cbi => new { ((CheckBox)((StackPanel)cbi.Content).Children[0]).Content }.ToString());

таким громоздким и немного корявым образом мы получим множество объектов с единственным свойством (string)Content


text:
Q: Discord Bot isn't responding For some reason, the basic ping pong command isn't working. I copied and pasted it from a website, but I am not sure what is wrong with it.
const { Client, Intents } = require('discord.js');
    const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
    client.login('hidden')

client.once('ready', () => {
    console.log('Ready!');
});

client.on('interactionCreate', interaction => {
    if (!interaction.isCommand()) return;

    const { commandName } = interaction;

    if (commandName === 'ping') {
        interaction.reply('Pong.');
    }

});

There is no log error which makes it weirder. I know it is connecting because the bot appears online when I do a node index.js in the cmd panel.

A: Firstly, I recommend that you fix the indentation at the beginning and move the client.login call to the end, as that's how the discord.js docs do it.
Additionally, are you sure you're using Discord.js v13? These events were added in v13, so if you run it with Discord.js v12, your bot will run, but your functions will never be called.
Otherwise, your code looks good (to me), but I'm not an expert.


text:
Q: Ambari error during installation yarn i'm trying to install IBM Open Platform 4.1 on Linux RedHat6; i created local repository for IOP and IOP-UTILS, because of proxy that block connection to ibm.
I installed ambari correctly but during installation of all packages i get this error:
1
 File "/usr/lib/python2.6/site-packages/resource_management/core/shell.py", line 70, in inner
    result = function(command, **kwargs)
  File "/usr/lib/python2.6/site-packages/resource_management/core/shell.py", line 92, in checked_call
    tries=tries, try_sleep=try_sleep)
  File "/usr/lib/python2.6/site-packages/resource_management/core/shell.py", line 140, in _call_wrapper
    result = _call(command, **kwargs_copy)
  File "/usr/lib/python2.6/site-packages/resource_management/core/shell.py", line 291, in _call
    raise Fail(err_msg)
resource_management.core.exceptions.Fail: Execution of '/usr/bin/yum -d 0 -e 0 -y install 'hadoop_4_1_*-yarn'' returned 1.

Error: Nothing to do


text:
Q: Adding ggsignif to plot with numeric x axis results in the error "Can only handle data with groups that are plotted on the x-axis" I would like to add a significance layer to a plot using the ggsignif package. However, when trying to add this layer to a plot with a numeric x-axis, I get the message:

Error in f(...) :
Can only handle data with groups that are plotted on the x-axis

Here is a reprex:
library(tidyverse)
library(ggsignif)

dat <-
  structure(list(
    SOA = c(50, 150, 300, 900),
    y = c(119, 121, 132, 209)),
  row.names = c(NA,-4L),
  class = c("tbl_df", "tbl", "data.frame")
)

dat %>%
ggplot(aes(SOA, y)) +
  geom_point() +
  geom_signif(
    annotations = "*",
    y_position = 150,
    xmin = 50,
    xmax = 300)

When I plot exactly the same data but transform the x-axis to factor, the significance layer is added successfully. Like so:
dat %>%
ggplot(aes(as.factor(SOA), y)) +
  geom_point() +
  geom_signif(
    annotations = "*",
    y_position = 150,
    xmin = "50",
    xmax = "300")

Note that this is not what I want, since the distances between the points do not reflect the real distance between them.
How can I make ggsignif work with a numeric x-axis?

A: While fixing an unrelated problem, I found out that adding group = 1 to aes() seems to fix the problem:
dat %>%
ggplot(aes(SOA, y, group = 1)) +
  geom_point() +
  geom_signif(
    annotations = "*",
    y_position = 150,
    xmin = 50,
    xmax = 300,
  )

I do not know why it works, but it does.


text:
Q: How to deal a deck of cards? I'm trying to create a application to deal a deck of cards. I have already made the deck and also shuffled the deck but I am having trouble dealing it to x number if players
Here is what I have so far.
class Dealer
{
    private string[] suffeledDeck = new string[52];
    private static string[] playerOne = new string[26];
    private static string[] playerTwo = new string[26];
    private static string[] playerThree = new string[26];
    private static string[] playerFour = new string[26];
    private static string[] playerFive = new string[26];
    private static string[] playerSix = new string[26];
    private static string[][] allplayers = new string[][] { playerOne, playerTwo,playerThree,playerFour,playerFive,playerSix };

    private int counter = 0;
    private int playerCount = 6;

    public Dealer(string[] deck)
    {
        suffeledDeck = deck;
    }

    private void deal()
    {
        for (int i = 0; i < suffeledDeck.Length; i++)
        {
            allplayers[counter][0] = suffeledDeck[i];
            counter++;
            if (counter == playerCount)
            {
                counter = 0;
            }
        }
    }
}

}

A: Use a List<string[]>  instead of string[][]

A: Here's one approach, but I would likely use List<T>, as Selman22 advises.
var sourceIndex = 0;
var handCount = 0;
while (sourceIndex < shuffledDeck.Length)
{
    for (var playerIndex = 0; playerIndex < allplayers.Length; playerIndex++)
    {
        allplayers[playerIndex][handCount] = shuffledDeck[sourceIndex++];
        if (sourceIndex == shuffledDeck.Length)
            break;
    }
    handCount++;
}

Example with lists:
class Dealer
{
    private List<string> shuffledDeck= new List<string>();
    private static List<string> playerOne = new List<string>();
    private static List<string> playerTwo = new List<string>();
    private static List<string> playerThree = new List<string>();
    private static List<string> playerFour = new List<string>();
    private static List<string> playerFive = new List<string>();
    private static List<string> playerSix = new List<string>();
    private static List<List<string>> allplayers = new List<List<string>> { playerOne, playerTwo,playerThree,playerFour,playerFive,playerSix };

    private int counter = 0;
    private int playerCount = allplayers.Count;
    public Dealer(string[] deck)
    {
        shuffledDeck= deck;
    }
    private void deal()
    {
        while (shuffledDeck.Count > 0)
        {
            foreach (var player in allplayers)
            {
                player.Add(shuffledDeck[shuffledDeck.Length - 1];
                shuffledDeck.RemoveAt(shuffledDeck.Length - 1];
                if (shuffledDeck.Length == 0)
                    break;
            }
        }
    }
}

This approach has the advantage of removing cards that have been dealt from the deck.  Deal from the end because RemoveAt(0) copies all of the remaining cards to fill in the gap.
Better initialization, unless you actually need the playerOne ... playerSix variables:
private static int playerCount = 6;
private static List<List<string>> allplayers =
    Enumerable.Range(0, playerCount).Select(i => new List<string());


text:
Q: Where to download Sql Server 2008 R2? I need to do a fresh install in a lab environment. Where's a good place to download it?

A: If you want it for a lab environment you can get a preconfigured VHD with an evaluation edition of 2008 R2 installed. It is valid for 180 days:
SQL Server 2008 R2 Standard on Windows Server 2008 R2 SP1 Standard (x64)
Also, you can get it if you or one of your colleagues have a MSDN subscription. If the subscription is not yours you can download it from there and use it for the 180 day evaluation period.

A: My favorite link for SQL server verisons is
https://sqlserverbuilds.blogspot.com/
It shows the current versions and links to the install files.


text:
Q: Choosing OS X version for a mid 2011 Macbook Air 4GB As I understand the matter, it is generally better to use a later version, however, I realize that the newer versions are really designed for more powerful hardware.  The MacBookAir4,1 in question is a dual core I5 1.6 Ghz CPU with 4GB of RAM.  It is currently running El Capitan.
The choices include:

*

*Mojave (latest, requires 2012 or later Macbook Air)

*High Sierra

*Sierra

What is an appropriate quantitative test to determine which of the three will run on the MacBookAir4,1 with a comparable performance to El Capitan?  While anecdotal reports are fine, any benchmarks to support a position should alleviate the issue of being 'opinion based'.

A: I have a 2010 iMac and I'm running High Sierra. It has been running smoothly but my machine gets very sluggish sometimes when running Xcode. I can't compare it to El Capitan because it has been too long to recall. It has been as stable as Sierra though. I think the only issues you'd have would be due to having 4 GB of RAM. The size of the system would be very important, I'd think, for a 4 GB machine. I don't know the relative size of your system but there are many apps that will tell you the amount of free RAM you have. iStats, Monity, and SystemPal from the app store are 3 such apps that will display how much RAM you are using and how much is free.


text:
Q: What did the crew do for 533 days without use of most of the living quarters in the Martian movie? In the movie, they caused a deliberate breach in the airlock so the Hermes can decelerate. We see that the living quarters and the kitchen werer depressurized and exposed to the cold vacuum of space. And I'm guessing most of the ship became uninhabitable. What did they do for 533 days, stay in the bridge? Was repairing the damage possible?

A: The ship repressurized
It has spare air
In the book, we see that Hermes was capable of recovering from being depressurized:

Once Beck and I got to his quarters, we waited for the ship to
repressurize. Hermes had enough spare air to refill the ship two more
times if needed.
—The Martian

The crew  had additional air on hand, which they were able to use to recover their losses.
They only blew up one door
As this answer on Quora notes, there were two parts to the airlock, only one of which was breached. The other was still intact, and could continue to protect the ship from the vacuum.

"We're going to have to literally blow up one of the doors, " Lewis
explained. "I'd rather we kill the inner one. I want the outer door
unharmed so we keep our smooth aerobraking shape."
—The Martian

Here we see the bomb attached to the inner door of the airlock. The outer door is open to space.
Note that they only blew up one of the doors. They could still seal the outer one, and then repressurize the ship with the spare air on hand.
The same is true in the film. The outer door is left intact, while only the inner one is damaged:

INT. HERMES - FLIGHT DECK - SPACE
LEWIS: Beck -- leave your suit on.
Meet Johanssen at Airlock 1. We'll open the outer door. I need you to
place the charge on the inner door....
INT. HERMES - AIRLOCK 2 - SPACE
LEWIS (OVER COMMS) ...and climb back to Airlock 2 along the hull.
BECK:
Copy. On my way.

Indeed, we see that the crew took particular effort to avoid damaging the outer door:

"One problem, " Lewis said. "I want the outer door locked in the fully
open position with the mechanical stopper in place to keep it from
being trashed by the decompress."
—The Martian

And they closed it once they were finished. Both in the novel:

They floated in to the airlock, and Vogel grabbed them. Beck and
Watney both reached for handholds on the wall as Vogel worked his way
around them and closed the outer door.
—The Martian

And in the film:

MARTINEZ, JOHANSSEN, and VOGEL race down from the bridge to meet them.
They're not in suits -- they have to wait for the outer airlock to
close. THROUGH THE OBSERVATION WINDOWS: they see Lewis and Mark touch
down in the airlock. The outer airlock closes -- WHOOSH -- Mark
collapses, exhausted. The inner airlock opens. Martinez, Johanssen,
and Vogel race into the room, grab Mark. Supporting him. Holding him.


text:
Q: Area of Two Inequalities in the $XY$ Plane This was question B1 on the 2014 CMI (Chennai Mathematical Institute) Entrance Examination for Undergraduate Courses. We were asked to find the area of the region in the $XY$ plane consisting of all points in the set $S=\{(x,y):x^2+y^2\leq144 \text{ and} \sin(2x+3y)\leq0\}.$ While this question is interesting, I do not know how to even begin. To me, it isn't readily obvious why this set has to have an area at all. What if only finitely many values of $x$ and $y$ satisfy the above conditions? I mean, given that the question is asking for the area, I can guess that there are infinitely many such pairs $(x,y),$ but apart from that, I don't know what to do. I suppose we could begin by writing $S=S_1\cap S_2,$ where $S_1=\{(x,y):x^2+y^2\leq144\},$ and $S_2=\{(x,y):\sin(2x+3y)\leq0\}.$ What if we look for a more general answer by putting $S_1=\{(x,y):x^2+y^2=r^2,r\in\mathbb{R}\setminus\{0\}\},$ and $S_2=\{(x,y):\sin(ax+by),a,b\in\mathbb{R}\setminus\{0\}\}?$

A: As mentioned in the comments, $\sin(2x+3y)\le 0$ means $$(2k-1)\pi\le 2x+3y\le 2k\pi$$
Let's take a look at $k=0$. This is a diameter of the circle of radius $12$, centered in origin, $x^2+y^2=(12)^2$. All the lines $2x+3y=k\pi$ are parallel to this one. You can calculate the distance between lines, but it's not necessary. All you need is to notice that all the distances are the same. For that, draw a straight line (say $x=0$) that intersects the set of parallel lines. Notice that the $y$ intersections are equidistant.
Now notice that if you select an area between $k\pi\le 2x+3y\le (k+1)\pi$, if the value of $\sin$ is positive, then the same expression for $-k$ will be negative. And vice versa. So for example, you are keeping the area between $k=-1$ and $k=0$, and you are throwing away the area between $k=0$ and $k=1$. But, due to symmetry, these areas are the same. And this continues for all $k$ values, until $|k|\pi>12$. Then you disregard the rest.


text:
Q: direct inclusion of lammps commands in PyIron I want to impose reflecting BCs at the non-periodic direction of my simulation box.  To this end I need to use fix wall/reflect
Is there any way for direct inclusion of this command in PyIron?
Best regards

A: wall/reflect is currently not natively supported by pyiron, but if you know the LAMMPS command, you can include it for example via:
job.input.control['fix___fixname'] = 'all wall/reflect xlo EDGE xhi EDGE'

(I took the first example on the LAMMPS page you shared). If your LAMMPS input is not too complicated, this pyiron should be able to place this command in the appropriate position.

A: Sams's solution is definitely the easiest way if you just want to insert one fix. But you can even load full LAMMPS scripts inside pyiron, here is an example:
https://github.com/jan-janssen/pyiron-free-energy/blob/master/free_energy.ipynb
The important part is to keep the read_data structure.inp and the include          potential.inp to use the structure and interatomic potential defined by pyiron. Finally if you also copy the dump, dump_modify and thermo part you can use the pyiron parsers, otherwise you can always parse the output yourself, like I demonstrated in the above example.


text:
Q: VC++ 2008 Error Map/set iterator is incompatible I have a project well running on VC++ 2003 .Net. But I have upgraded it to VC++ 2008 then it is compiled successfully. Now, I executed it & it crashes in the following code:
CString szDCode(_T("E007"), _T("****"));
map<CString, CString>::iterator itr;
itr = m_ECodes.find(szDCode);
if(itr != m_ECodes.end())
{
  szDCode = (*itr).second;
  itr = m_LineComponents.find(szDCode);
  if(itr != m_ECodes.end()) // This line is creating Error, While I have 4-5 items in it.
    szDCode = (*itr).second;
}

Here the Error being generated is:
Expression: map/set iterators incompatible.
Plz help me.
Abhishek

A: You get an iterator from the m_LineComponents container:
itr = m_LineComponents.find(szDCode);

You try to compare this iterator against an iterator from the m_ECodes container:
itr != m_ECodes.end()

You can only compare two iterators from the same container.  Newer versions of Visual C++ include checks in the Standard Library that help you to find this sort of error.  The code was never correct.


text:
Q: Facing an issue with code using javascript I have 10 checkboxes, if I select 5 checkboxes the rest should be disabled and if I select less than 5 remaining should be enabled. How to do it using JavaScript?
This is my code:
var count = 1;

function myfun(obj) {
    debugger; /*var x = req.body.checkbox; if (x == undefined) { x = false;}*/
    if ((obj.checked) == true) {
        count++;
    } else if ((obj.checked) == false) {
        count--;
    }
    if (count > 5) {
        c1.disabled = true;
        c2.disabled = true;
        c3.disabled = true;
        c4.disabled = true;
        c5.disabled = true;
        c6.disabled = true;
        c7.disabled = true;
    }
}

A: from the problem described i have derived a solution. See it it works for you
https://jsfiddle.net/oL48u5ew/1/
HTML
<div class="parent">
<input type="checkbox" class="visit"/>
<input type="checkbox" class="visit"/>
<input type="checkbox" class="visit"/>
<input type="checkbox" class="visit"/>
<input type="checkbox" class="visit"/>
<input type="checkbox" class="visit"/>
<input type="checkbox" class="visit"/>
<input type="checkbox" class="visit"/>
<input type="checkbox" class="visit"/>
</div>

JS
var count = 0
$('.visit').change(function(){
    if(this.checked)
    count++
  else
    count --
  if(count > 4)
  {
  $('.parent').find('.visit').each(function(){
    if(!this.checked){
        $(this).attr("disabled", true);
    }
  })
  }
});


text:
Q: Oracle SQL sum sometimes return double value I met an interesting result when using TOAD on Oracle 11. The same query sometimes return the correct value, sometimes not. There is no group by. There is no join. Am I missing something?
The query is converting all digits to numeric value, then multiple 3 or multiple 1 depends on their location and then sum up.
The field is defined as "device_id VARCHAR2(25);"
Following query return 182, which is double the correct value 91. If change the condition as ii.device_id = '20637320050504', then it is correct value as 67.
select sum(to_number(substr( ii. device_id, 1, 1 ))*3 +
               to_number(substr(ii. device_id, 13, 1 ))*3 + to_number(substr(ii. device_id, 12, 1 )) +
               to_number(substr(ii. device_id, 11, 1 ))*3 + to_number(substr(ii. device_id, 10, 1 )) +
               to_number(substr(ii. device_id, 9, 1 ))*3 + to_number(substr(ii. device_id, 8, 1 )) +
               to_number(substr(ii. device_id, 7, 1 ))*3 + to_number(substr(ii. device_id, 6, 1 )) +
               to_number(substr(ii. device_id, 5, 1 ))*3 + to_number(substr(ii. device_id, 4, 1 )) +
               to_number(substr(ii. device_id, 3, 1 ))*3 + to_number(substr(ii. device_id, 2, 1 )) ) as total
from identifier ii
where ii. device_id = '55019315060289'

I tried to modify the query out of my table definition as following, then the result is correct.
select sum(to_number(substr( '55019315060289', 1, 1 ))*3 +
           to_number(substr('55019315060289', 13, 1 ))*3 +  to_number(substr('55019315060289', 12, 1 )) +
           to_number(substr('55019315060289', 11, 1 ))*3 +  to_number(substr('55019315060289', 10, 1 )) +
           to_number(substr('55019315060289', 9, 1 ))*3 +   to_number(substr('55019315060289', 8, 1 )) +
           to_number(substr('55019315060289', 7, 1 ))*3 +   to_number(substr('55019315060289', 6, 1 )) +
           to_number(substr('55019315060289', 5, 1 ))*3 +   to_number(substr('55019315060289', 4, 1 )) +
           to_number(substr('55019315060289', 3, 1 ))*3 +   to_number(substr('55019315060289', 2, 1 )) ) as total
from dual;

Looks like it is not TOAD or Oracle issue, but I could not figure out what I did wrong. Thanks.

A: Make a note of "range of values that a datatype may support". The unsigned integer cannot hold the value 55019315060289,The max value that unsigned integer can hold is 2147483647


text:
Q: Check if json is valid in power query iam parsing values from json formats from a MySQL table:
the json looks like this: "{"de":"Ja","en":"Yes"}"
and my power query :
let
Source = MySQL.Database("ip", "db", [ReturnSingleDatabase=true]),
mapassess_maps = Source{[Schema="",Item=""]}[Data],
#"Filtered Rows" = Table.SelectRows(mapassess_maps, each not Text.StartsWith([title], "Is Root for Project")),
#"Replaced Value" = Table.ReplaceValue(#"Filtered Rows","\t"," ",Replacer.ReplaceText,{"title"}),
#"Parsed all JSON columns" = Table.TransformColumns(#"Replaced Value",{{"title", Json.Document}, {"description", Json.Document}, {"question", Json.Document}, {"answer_pos", Json.Document}, {"answer_neg", Json.Document}, {"answer_neu", Json.Document}, {"relevance_pos", Json.Document}, {"relevance_neu", Json.Document}, {"relevance_neg", Json.Document}}),

#"Expanded relevance_neg" = Table.ExpandRecordColumn(#"Parsed all JSON columns", "relevance_neg", {"de", "en", "sp", "it", "ru" }, {"relevance_neg.de", "relevance_neg.en", "relevance_neg.sp", "relevance_neg.it", "relevance_neg.ru"}) in #"Expanded relevance_neg"

the problem is: some values in the mysql table dont have a json format, only a hard value like: yes.
what i want is: if the value in the table is NOT in json format it must be interpreted as a value for the expanded column "relevance_neg.de".

A: You can use try/otherwise. The format for it would look something like this:
try Json.Document(value) otherwise replacementValue


text:
Q: MySQL auto increment column increases after insertion error occurs I was doing some insertion tests in my database and I realized that when the INSERT statement fails, due error 1452, causes the auto_increment value increase by 1. Even though, there wasn't any row inserted in this statement.
Thereby, this behavior causes the next valid insertion skip an available and possible value for the auto_increment.
Example:
1st Insert | Result: Success | id(auto_increment_column): 1       |
2nd Insert | Result: Failure | -------- No rows were recorded---- |
3nd Insert | Result: Success | id(auto_increment_column): 3       |

I want to know if someone had this problem before and if this is really a problem.
Cheers.
P.S.:
Errno: 1452 - fk constraint fails. This means that I'm trying to reference some column value in another table and this value doesn't exists there.

*

*Database: MySQL Ver 14.14 Distrib 5.6.13, for Windows 64-bit

*Storage Engine: InnoDB

A: Last Sentence of MySQL Documentation on Traditional InnoDB Auto-Increment Locking says

You may see gaps in the sequence of values assigned to the AUTO_INCREMENT column if you roll back transactions that have generated numbers using the counter.

Therefore, if the second INSERT had failed and rolled back, it makes the gap.
You may have to set innodb_autoinc_lock_mode to 0 or 2. Please read the MySQL Documentation on Configurable InnoDB Auto-Increment Locking to understand what changing innodb_autoinc_lock_mode can do for you.

A: Where your table design is
id     int auto_increment primary key,
field1 int,
field2 int,
unique u_f1_f2 ( field1, field2 )

You can try insert like :
insert ignore into table select (select max(id)+1 from table), "value1", "value2" ;

This will try

*

*insert new data with last unused id (not autoincrement)

*if in unique fields duplicate entry found ignore it

*else insert new data normally
( but this method not support to update fields if  duplicate entry found )


text:
Q: ReadLine() vs Read() to Get CR and LF Efficiently? I am working on a C# program to determine the line length for each row in multiple large text files with 100,000+ rows before importing using an SSIS package. I will also be checking other values on each line to verify they are correct befor importing them into my database using SSIS.
For example, I am expecting a line length of 3000 characters and then a CR at 3001 and LF at 3002, so overall a total of 3002 characters.
When using ReadLine() it reads a CR or LF as and end of line so that I can't check the CR or LF characters. I had been just checking the length of the line at 3000 to determine if the length was correct. I have just encountered an issue where the file has a LF at position 3001 but was missing the CR. So ReadLine() says it is 3000 char witch is correct but it will fail in my SSIS package because it is missing a CR.
I have verified that Read() will reach each char 1 at a time and I can determine if each line has a CR and LF but this seems rather unproductive, and when some files I will encounter with have upwards of 5,000,000+ rows this seems very inefficient. I will also need to then add each char into a string or use ReadBlock() and convert a char array into a string so that I can check other values in the line.
Does anyone have any ideas on an efficient way to check the line for CR and LF and other values on a given line without wasting unnecessary resources and to finish in a relatively timely manner.

A:
have verified that Read() will reach each char 1 at a time and I can determine if each line has a CR and LF but this seems rather unproductive

Think about this. Do you think ReadLine() has a magic wand and does not have to read each char?
Just create your own ReadMyLine(). Something has to read the chars, it doesn't matter if that's your code or the lib. I/O will be buffered by the Stream and Windows.

A: I may be missing something here, but if the data in each line is always exactly 3000 characters (excluding CR and LF)?
Why not just read each line and then take the first 3000 characters only, using string.Substring(). This way you don't have to worry about exactly how the string is terminated.
ie
 using (StreamReader sr = new StreamReader("TestFile.txt"))
    {
       String line;
       while ((line = sr.ReadLine()) != null)
          {
            // string data = line.subString(0,3000);
            // edit, if data is sometimes < 3000 ....
            string data = line.subString(0,line.length < 3000 ? line.length : 3000);
            // do something with data
          }
     }

A: Can you use an override of StreamReader.Read  OR an override of TextReader.Read which accepts 3 parameters - string buffer (in your case a 3002 character array), startint index (you will handle this in a loop each time incrementing the index by 3002), number of characters to read (3002). From the read buffer, you can check the last two characters for your conditional evaluation of CR and LF.

A: I believe you will find this version to be efficient:
    static bool CheckFile(string filename)
    {
        const int BUFFER_SIZE = 3002;

        var Reader = new StreamReader(filename, Encoding.ASCII, false, BUFFER_SIZE);

        var buffer = new char[BUFFER_SIZE];

        int offset = 0;
        int bytesRead = 0;

        while((bytesRead = Reader.Read(buffer, offset, BUFFER_SIZE)) > 0)
        {
            if(bytesRead != BUFFER_SIZE
                || buffer[BUFFER_SIZE - 2] != '\r'
                || buffer[BUFFER_SIZE - 1] != '\n')
            {
                //the file does not conform
                return false;
            }

            offset += bytesRead;
        }

        return true;
    }

The reason I'm optimistic about this is that according to the docs, efficiency is increased if the size of the underlying buffer is matched to the buffer that is used for reading. Caveat: this code has not been tested or timed.

A: I think I have finally figured out the code to get exactly what I want, thoughts? The main issue I was encountering was that I am not guaranteed my line length is going to correct. Other wise the method mentioned by @Paul Keister would have worked great, and did as I tested it. Thanks for the help!
int asciiValue = 0;

while (asciiValue != -1)
{

Boolean endOfRow = false;
Boolean endOfRowValid = true;

string currentLine = "";

while (endOfRow == false)
{
    asciiValue = file.Read();

    if (asciiValue == 10 || asciiValue == 13)
    {
        int asciiValueTemp = file.Peek();

        if (asciiValue == 13 && asciiValueTemp == 10)
        {
            endOfRow = true;
            asciiValue = file.Read();
        }
        else
        {
            endOfRowValid = false;
            endOfRow = true;
        }
    }
    else if (asciiValue != -1)
        currentLine += char.ConvertFromUtf32(asciiValue);
    else
        endOfRow = true;
}

Edit: I forgot to mention that this seems to be just as efficient as using ReadLine(). I was really afraid this wouldn't have worked as well. It appears I was wrong.


text:
Q: Django adminlte3 can't load Bootstrap I have a Django app and I want to use AdminLTE3.
But I have a problem with Bootstrap loading.
My settings.py
STATIC_URL = "/static/"
STATIC_ROOT = '/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"), )

What is the problem?
Logs are:
2023-02-22 07:41:01,830 WARNING django.request [/usr/local/lib/python3.10/site-packages/django/utils/log.py:224] Not Found: /static/admin-lte/dist/js/adminlte.min.js