text:
Q: How do I create a Perl regex that matches non-alphanumeric characters except spaces? I have a Perl regex /\W/i which matches all non-alphanumeric characters, but it also matches spaces which I want to ignore. How do I get it to match non-alphanumeric characters except spaces?

A: For most purposes, [^\w\s] should suffice. That matches just one character which is neither an "alphanumunder" nor a PerlSpace.
That's almost but not quite like saying it matches anything that is neither \p{Alphabetic} nor \p{Digit} nor the underscore (LOW LINE) nor \p{WhiteSpace}, except for the weaseling regarding chr 11, vertical tab, since that is not considered \s, although it is considered \p{WhiteSpace}.
The little \s shorthand really menas \p{PerlSpace}, not \p{WhiteSpace}.  And \p{Space} is the same as \p{WhiteSpace}.  The only \S character (meaning, not \s) which is also \p{Space} is that pesky vertical tab.  Note that vertical tab is included in \v, so that means [\v\h], for any vertical or horizontal white space, is the same as \p{Space}, not \s.
I'm now going to get more precise regarding alphanumerics.  For simplicity, I'm going to talk about positive matches.  It should be easy to invert the logic to get negative matches.
If by "alphanumeric", you mean either letters or numbers, you should probably use properties that mean precisely that. \pL is short for \p{Letter}, which probably covers those.  All letters are alphabetic, but there are  characters that are \p{Alphabetic} yet not \p{Letter}, like Roman numerals, the circled letters, and various diacritics.
For numbers, the question if whether you mean to include digits only, or if other numbers are ok.   \pN is short for \p{Number}, but that includes a lot of non-digits.  \d is short for \p{Nd}, and that in turn is short for \p{Decimal_Number}, although \p{Digit} works fine, too. Numbers that aren't digits include Roman numerals, vulgar fractions, superscripted numbers, and circled digits.
Beginning sometime after Perl 5.11, you can use properties like \p{POSIX_Digit} for nothing but [0-9], \p{POSIX_Alpha} for only the letters, and \p{POSIX_Alnum} for both. There's also a \p{POSIX_Space} with that release or better, covering characters 9-13 plus 32 only, completely ignoring twenty other whitespace characters that come later.
Before then, you can still restrict your matches to the ASCII range by using a lookahead assertion that constrains the match to be ASCII only, using /(?=\p{ASCII})[\p{Alpha}\p{Digit}]/, although restricting characters to 7 bits is awfully last-millennium.
I'd probably let them use Roman numerals but not exotic diacritics, so would just use /[\p{Letter}\p{Digit}]/, which you can shorten up to /[\pL\d]/ if you'd prefer.
Now you add white space to that with \s or the slightly broader \p{Space}, giving /[\p{Letter}\p{Digit}\p{Space}]/.  I would leave it in that form, too, because I think it's clearer what you mean.
To negate that, you might think to prefix it with !, but that isn't quite the same since an empty string would match. So you should put a caret at the start of the character class to complement the set, making it /[^\p{Letter}\p{Digit}\p{Space}]/.
You could not just flip the sense the \p into \P instead the way you could with a single property, since /[\P{Letter}\P{Digit}\P{Space}]/ would get letter characters that are nondigits, (white)space characters that are nondigits, digit characters that are nonspaces, etc.
There's still no reason to use /i, though.

A: [^\p{Alnum}\d ] # NOT alnum or space

A: You could use
/[^\w\s]/

This matches all non-word characters (\w) and non-whitespace (\s).
EDIT:
/[^\w ]/

If you want only to ignore spaces (not all whitespace).
UPDATE:
Removed i as it's not needed (see several comments).


text:
Q: How can I install python3 by yum in AWS EC2 I want to install pip3, python in my AWS EC2.
What I found how to install is
yum update
yum install gcc
yum install wget
yum install zlib-devel
cd _____
wget https://www.python.org/ftp/python/3.6.1/Python-3.6.1.tgz
tar xzf Python-3.6.1.tgz
....

but when I write the first line It doesn't work.
# yum update
Traceback (most recent call last):
  File "/usr/bin/yum", line 57, in <module>
    from dnf.cli import main
ModuleNotFoundError: No module named 'dnf'

I don't know why the 'yum' doesn't work. how can i fix it?

A: sudo yum install python36 (for python3.6)
sudo yum install python37 (for python3.7) and so on.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Need help clarifying TCP ports Researching about ports online, I have found it being described in many different ways. The main way is that a port is a like a door on your computer used by a specific process. A second way it is commonly explained is that it is just a tag, an extra identifier on top of the IP address for a specific process.
What I'm having trouble understanding is that if ports are actually "physical" in some way like a door. Does data actually go through a port? If so, then can data both be sent and received through the same port simultaneously?
If a port is more like just a tag, then what does it mean to "open" ports through a firewall?
Last question is, are ports needed to send data from the sending process? I understand that it has to send data to a specific port on the receiving end, and that it has to specify its local port used to receive data back, but when it does the actual sending, does it need to use a port (and is it the same as the port it already uses to receive)?
Any help is greatly appreciated!

A:
Researching about ports online, I have found it being described in many different ways. The main way is that a port is a like a door on your computer used by a specific process. A second way it is commonly explained is that it is just a tag, an extra identifier on top of the IP address for a specific process.

The "door" explanation is just a metaphor. The tag example is more accurate. The destination and source ports are simply fields in the TCP and UDP headers that differentiate one TCP/UDP connection (combination of IP address and port) from another.

What I'm having trouble understanding is that if ports are actually "physical" in some way like a door. Does data actually go through a port? If so, then can data both be sent and received through the same port simultaneously?

Ports are not literally physical, but it's a useful methaphor to help understand.

If a port is more like just a tag, then what does it mean to "open" ports through a firewall?

A firewall that blocks specific ports simply inspects all traffic passing through it and checks the destination and/or source ports of TCP/UDP traffic. If there is a rule to block all incoming connections on port 80, then it will drop that traffic, otherwise it will forward it to the destination.

Last question is, are ports needed to send data from the sending process? I understand that it has to send data to a specific port on the receiving end, and that it has to specify its local port used to receive data back, but when it does the actual sending, does it need to use a port (and is it the same as the port it already uses to receive)?

Ports are only needed if you want to send data over TCP or UDP. For instance, a web server binds a socket to an IP address and port (usually 80 for HTTP). It listens for incoming connections with a destination port of 80. Once it establishes a connection (usually through the TCP handshake) it will open a new connection listening on a different port and tell the client which port to now connect to. To answer your question, the port is needed from the sending process so the receiver's kernel knows where to send the incoming traffic. It associates the (address, port) pair with a process.


text:
Q: eclipse-cdt Problems I have got a weird problem. I installed eclipse for c/c++ Development using the following:
sudo apt-get install eclipse eclipse-cdt g++

after i opened eclipse, i tried to make a new project, but i didn't get an option to choose between types of projects (c project/ c++ project/ Java project) but just the option "project". this project did not generate a src folder. i didn't see an option to create a src folder as well. how do i fix that?
i tried installing it manually with the download from their site, but the program didn't even launch.

A: This answer is for the packages that you installed in Ubuntu 14.04 by running: sudo apt install eclipse eclipse-cdt g++

*

*Open Eclipse and select Help -> Welcome.

*The Welcome screen will appear. In the Welcome screen click Tutorials.

*The Tutorials screen will appear. In the Tutorials screen click C/C++ Development.

*A Help - Eclipse Platform window will open. Click Create a simple application.

*The Help - Eclipse Platform window will jump to the Tutorial: Creating a simple application section. In this tutorial, you will use the CDT to create a simple 'Hello World' application. The tutorial has screenshots to make it easy to follow.
After you have finished following the Creating a simple application tutorial, don't delete the 'Hello World' project that you made so you can use it as reference material for making your next C++ project.

A: That's how I was able to get eclipse-cdt to start:
First open you shell and type sudo -s and start eclipse as root. After this you should be able to run it as normal user.
But this has to be done for the first as root.


text:
Q: How to clear data stored in a socket in python I am designing a turn-based game that uses connection.recv() to read from the socket and store the data of a 'move' in a buffer (which the server reads from). The problem is, the player can send data outside of their turn to be queued in the socket buffer, which means the server potentially reads from moves they made outside of their turn, instead of blocking until they make a turn. Is there any way to flush the data stored in the socket, and if not, is there any other workaround to this problem?

A: From Steffen's suggestion, I am using recv calls to clear the buffer. Currently, I'm setting the socket to non-blocking and calling recv until a BlockingIOError. It would be much appreciated if anyone could point out a more graceful solution (that doesn't use exceptions).
connection.setblocking(False)
while True:
try:
  chunk = connection.recv(4096)
except BlockingIOError as b:
  break
connection.setblocking(True)


text:
Q: Executing only the code of a page? Hi guys consider I have a .php page that I need to include somewhere else.
page.php:
<?php
 dosomecmd();
 doothercmd();
 //etc
?><html>pagehtml</html>

Is there a way to include this page but not printing the html inside? (I just need to execute those command)
I could do with ob
ob_start();
include('page.php');
ob_discard();

But i would prefer a faster way.
Thanks
Edit: i know i can sepearate html and php (and i already do) but that page.php is non else than a "static" cache I make, but sometimes I need to execute some command inside that cache instead to printing automatically it out
Edit2: of course i don't need everyime to not output the html (otherwise I could just delete all html) I need to return; only based on the results of my cmds up there
Thanks all i find a solution (add return;)

A: Would it be easier to have a common page with only the php that you need to share, and include it in both page.php and your other page?

A: you can try to seperate with
$_SERVER['REQUEST_URI']
also I wouldn't recommend that

A: Try to separate the PHP logic at the start of your current script into another file, then include that into both of your scripts.


text:
Q: User input for integers only using type() == int a = False
while a == False:
    quant = int(input("Input the size:\n"))
    if type(quant) == int:
        a = True
    else:
        print('Please use numbers:\n')
        a = False

I'm trying to make it so that the user can't input characters, but if they do, it prints out the second message. However, when I try to input characters, this message appears:
Traceback (most recent call last):
  File "C:/Users/user/Desktop/pythonproject1/Actual Projects/password
generator/Password_generator.py", line 34, in <module>
    quant = int(input("Input the:\n"))
ValueError: invalid literal for int() with base 10: 'thisiswhatIwrote'

It works fine when inputing integers.
I have tried isinstance() and is_integer(), but couldn't get them to work, so just tried to make it simple.

A: There are a number of ways you can tackle this issue. Firstly your error comes because you are trying to convert the string to an int. when the string has chars those cannot be converted to an int so you get a ValueError. You could utilise this behaviour to validate the input
while True:
    try:
        quant = int(input("Input the size:\n"))
        break
    except ValueError as ve:
        print('Please use numbers:\n')

So try to convert to an int, if it works break the loop, if you get a value error tell them to use numbers.
Alternativly you can capture the input as a string then use the strings method isnumeric to see if its a number. If it is then convert it to a number and break the loop, else tell them to use a number.
while True:
    quant = input("Input the size: ")
    if quant.isnumeric():
        quant = int(quant)
        break
    else:
        print("Please use numbers")


text:
Q: iPhone: Layering a transparent openGL view on top of a UIView? I am working on iPhone app and I have an openGL view rendering on top of a regular UIView.  It's working, but I can't seem to get the openGL view to have a transparent background that shows the UIView underneath.  Instead, I get a big black box.
I have tried setting the background color to UIColor clearColor, I've set opaque to NO, I've set glClearColor to 0.0,0.0,0.0,0.0.
I think I'm misunderstanding/misusing something related to blend modes, but I'm not sure.  Can anyone give me a bit of sample code which shows how to do this?
Thanks in advance.

A: Add those in EAGLView.m
-(id)initWithCoder:(NSCoder*)coder

self.opaque = NO;
self.backgroundColor = [UIColor clearColor];

CAEAGLLayer *eaglLayer = (CAEAGLLayer *)self.layer;
eaglLayer.opaque = NO;

CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
const CGFloat myColor[] = {0.0, 0.0, 0.0, 0.0};
eaglLayer.backgroundColor = CGColorCreate(rgb, myColor);
CGColorSpaceRelease(rgb);

A: Check the color format of your view. If you've set it to kEAGLColorFormatRGB565 via the drawableProperties dictionary, the alpha channel of the view's contents will be implicitly treated as 1.0, regardless of what you draw into it.

A: Here's what I had to do to get this to work:
eaglLayer.opaque = NO;
eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:
                                kEAGLColorFormatRGBA8, kEAGLDrawablePropertyColorFormat, nil];
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

And incase you're doing what I was doing and are trying to test it with the GLGravity demo, there's another call to glClearColor(0.0f, 0.0f, 0.0f, 1.0f); every time drawView is called -- so make sure you change that one to glClearColor(0.0f, 0.0f, 0.0f, 0.0f); too!  :)


text:
Q: What are the differences between application/json and application/x-www-form-urlencoded? What is the difference between

request.ContentType = "application/json; charset=utf-8";

and

webRequest.ContentType = "application/x-www-form-urlencoded";

A: One of the biggest differences between the two is that JSON-encoding the post usually preserves the data types of the values that are sent in (as long as they are valid JSON datatypes), whereas application/x-www-form-urlencoded will usually have all properties converted to strings.
For example, in the JSON-encoded post of:
{"Name": "John Smith", "Age": 23}

the server will most likely parse the Age property as the integer 23.
Whereas in
Name=John+Smith&Age=23

the server will most likely parse Age as the string "23".
Of course, if you are using other layers to parse these values and convert them to the appropriate types, this may not be an issue.

A:
webRequest.ContentType = "application/x-www-form-urlencoded";

*

*Where does application/x-www-form-urlencoded's name come from?
If you send HTTP GET request, you can use query parameters as follows:
http://example.com/path/to/page?name=ferret&color=purple
The content of the fields is encoded as a query string. The application/x-www-form-
urlencoded's name come from the previous url query parameter but the query parameters is
in where the body of request instead of url.
The whole form data is sent as a long query string.The query string contains name-
value pairs separated by & character
e.g. field1=value1&field2=value2

*It can be simple request called simple - don't trigger a preflight check
Simple request must have some properties. You can look here for more info. One of
them is that there are only three values allowed for Content-Type header for simple
requests

*

*application/x-www-form-urlencoded

*multipart/form-data

*text/plain

3.For mostly flat param trees, application/x-www-form-urlencoded is tried and tested.

request.ContentType = "application/json; charset=utf-8";

*

*The data will be json format.

axios and superagent, two of the more popular npm HTTP libraries, work with JSON bodies by default.

{
  "id": 1,
  "name": "Foo",
  "price": 123,
  "tags": [
    "Bar",
    "Eek"
  ],
  "stock": {
    "warehouse": 300,
    "retail": 20
  }
}

*"application/json" Content-Type is one of the  Preflighted requests.

Now, if the request isn't simple request, the browser automatically sends a HTTP request before the original one by OPTIONS method to check whether it is safe to send the original request. If itis ok, Then send actual request. You can look here for more info.

*application/json is beginner-friendly. URL encoded arrays can be a nightmare!

A: The first case is telling the web server that you are posting JSON data as in:
{"Name": "John Smith", "Age": 23}

The second case is telling the web server that you will be encoding the parameters in the URL:
Name=John+Smith&Age=23


text:
Q: How can i make divs with numbers change background colors I would like to know if I can change the background colour of the divs with numbers in a sequence so 1 goes first and then 2 then 3 with a function that will load automatically?
Here is the code that I have at the moment:

    Test

    &nbsp
    &nbsp
    &nbsp
    &nbsp

    &nbsp
    &nbsp
    &nbsp
    &nbsp

    &nbsp
    &nbsp
    &nbsp
    &nbsp

    &nbsp
    &nbsp
    &nbsp
    &nbsp

A: You need setTimeout and a counter to call a function and apply the background to each cell. You should also remove !important from the css if possible, as that makes it harder to override the background colour - it's a bit hacky and should be used as a last resort.
(function() {

    var i = 1;
    // put colours in an array, we don;t need anything in position 0, because there is no
    var colours = [null, 'yellow', 'green', 'blue', 'white', 'orange'];

    // the function to set the background
    function setColour() {
        // reset previous cell if there was one
        var previousTd = document.getElementById(i-1);
        if(previousTd != null) {
            previousTd.style.backgroundColor = '';
        }

        var td = document.getElementById(i);
        if(td != null) {
            td.style.backgroundColor = colours[i];
            i++;
            // wait half a second and call the function again
            window.setTimeout(setColour, 500);
        }
    }

    window.addEventListener('load', setColour);

})();

Fiddle

A: You can use setTimeout .
If you don't want to use jQuery.
   setTimeout(function() {

    document.getElementById("1").style.color = "yellow"

    },3000); // here 3000 is the timeinterval in milliseconds(1000 = 1sec)

and..

A: Here is my solution, it may be a little simpler and jquery is better for cross-browser support:
$(document).ready(function () {
    setInterval(changeColor, 500);
});
var a = 1;
var colors = ["red", "green", "yellow", "blue"];
function changeColor() {
    $( "div" ).each(function() {
        $(this).css("background-color", "");
    });
    if (a > 4) { a = 1; }
    $("#" + a).css("background-color", colors[a - 1]);
    a++;
}

http://jsfiddle.net/cdj87t9e/
Just change $( "div" ).each to $( "td" ).each

A:  Updated Codepen with CSS animation
You can do this with css using flexbox.  Check it out on codepen here
HTML

&nbsp

&nbsp

THREE

&nbsp

&nbsp

ONE

&nbsp

FIVE

&nbsp

&nbsp

TWO

&nbsp

FOUR

&nbsp

&nbsp

&nbsp

CSS
body{
    background-color: #000000 ;
}
table, th, td {
    border: 1px solid #000000 ;
    background-color: #000000 ;
}
th,td{
    background-color: #303030 !important;
    width: 218;
    height: 72;
  font-weight: bold;
}
#table{
    width: 100%;
    height: 100%;

}
tr{
  display:flex;
  flex-direction:row;

}
td,th {
  order:2;
  flex-grow:1;
  text-align:center;
}
#three {
  order:1;
  color:#fff;
  background:blue !important;
}
#one {
  order:1;
  color:#333;
  background:yellow !important;
}
#two {
  order:1;
  color:#fff;
  background:green !important;
}
#five{
  order:1;
  color:#333;
  background:orange !important;
}
#four {
  order:1;
  color:#333;
  background:#fff !important;
}

A: you can use setTimeout to do this. You could use .css() to just change the background color but I would suggest adding a class in the event that you ever wanted to add more CSS rules (also I would suggest changing your id's to words instead of numbers, ex: #one instead of #1):
FIDDLE
JS
setTimeout(function(){

    $("#one").addClass("yellow");

}, 1000);

setTimeout(function(){

    $("#two").addClass("green");

}, 2000);

setTimeout(function(){

    $("#three").addClass("blue");

}, 3000);

setTimeout(function(){

    $("#four").addClass("white");

}, 4000);

setTimeout(function(){

    $("#five").addClass("orange");

}, 5000);

CSS
.yellow{
    background-color: yellow;
}

.green{
    background-color: green;
}

.blue{
    background-color: blue;
}

.white{
    background-color: white;
}

.orange{
    background-color: orange;
}

UPDATE
I noticed your comment about wanting them to fade in and out after I posted my anwser. To do this a lot simpler with jQuery (plain javascript can be very wordy) here is another solution using setInterval:
var counter = 0;
var colorArray = ["yellow","green", "blue", "white", "orange"];

setInterval(function(){

 $("#color"+(counter+1)).css({"background-color":colorArray[counter]});
 $('td,th').not("#color"+(counter+1)).attr("style", "");

 counter++;

}, 500);

NEW FIDDLE


text:
Q: Share Netty NioEventLoopGroup between Lettuce & AsyncHttpClient My application is using Netty 4.1.6.Final and Lettuce 4.3.0, Async Http Client 2.1.0
Lettuce 4.3.0 also relies on netty 4.1.6.Final.
Async Http Client 4.3.0 also relies on netty 4.1.4.Final.
Now I see Lettuce creates its thread pool.  Async Http Client also creates its thread pool. And my application creates another thread pool for Netty.
Is it possible to share the same NioEventLoopGroup cross all the component to reduce thread number?

A: Async Http Client
AsyncHttpClient httpClient = new DefaultAsyncHttpClient(new DefaultAsyncHttpClientConfig.Builder().setEventLoopGroup(myEventGroup).build())

Lettuce
Add RedisEventLoopGroupProvider class
public class RedisEventLoopGroupProvider extends DefaultEventLoopGroupProvider {

    public RedisEventLoopGroupProvider() {
        super(3);
        // TODO Auto-generated constructor stub
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T extends EventLoopGroup> T allocate(Class<T> type) {
        if (NioEventLoopGroup.class.equals(type)) {
            return (T)myEventGroup;
        }
        return super.allocate((Class<T>)type);
    }

}

Initialize in this way
RedisClient redisClient = RedisClient.create( DefaultClientResources.builder()
            .eventLoopGroupProvider(new RedisEventLoopGroupProvider())
            .ioThreadPoolSize(1)
            .computationThreadPoolSize(3)
            .build(), Environment.REDIS_CONNECTION);


text:
Q: How to add a OnClick listener spefic to this table? I am setting up a quality-control for my internship and for that I need a table filled with buttons with ClickListeners.
Now here is the Problem:
How do I add a OnClick Listener for each of the buttons?
The onClick method does not have to do anything really.
I have played with this table all day now.

A: When you create your button:
var button = document.createElement("
button.innerHTML = "";
td.appendChild(button);

Just add
button.addEventListener("click", myFunction);

before td.appendChild(button)

A: There are two ways you can do this.
The first is to provide an event listener for every button:

var abc = [
  'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
  'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
  'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA',
  'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI',
  'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ',
  'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ'
];

function clickHandler(evt) {
  var btn = evt.target;
  var col = btn.getAttribute('col');
  var row = btn.getAttribute('row');
  alert('clicked on cell '+col+row);
}

function addTable() {
  var X_Length = 10;//localStorage.getItem("XWert");
  var Y_Length = 10;//parseInt(localStorage.getItem("YWert")) + 1;
  var myTableDiv = document.getElementById("Table");
  var table = document.createElement('TABLE');
  var tableBody = document.createElement('TBODY');
  table.appendChild(tableBody);

  for (var i = 0; i < Y_Length; i++) {
    var tr = document.createElement('TR');
    tableBody.appendChild(tr);
    for (var j = 0; j < X_Length; j++) {
      var td = document.createElement('TD');

      if (j == 0 && i != 0) {
        td.innerHTML = i;
      }
      else if (i == 0 && j != 0) {
        td.innerHTML = abc[j - 1];
      }
      else {
        var button = document.createElement("button");
        button.setAttribute('col', abc[j - 1]);
        button.setAttribute('row', i);
        button.addEventListener('click', clickHandler); // <--- Event listener for each button
        button.innerHTML = "";
        td.appendChild(button);
      }

      tr.appendChild(td);
    }
  }

  myTableDiv.appendChild(table);
}

addTable();
th, td {
  border: 1px solid #999;
  margin: 0;
  padding: 5px;
  width: 75px;
}

table {
  border-collapse: collapse;
}

And the second is to provide one for the entire table and filter on the event to make sure it was the button that was clicked. This way uses a little less memory and a lot fewer event listeners. It also does works in additional rows or columns are added after initial render

var abc = [
  'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
  'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
  'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA',
  'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI',
  'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ',
  'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ'
];

function clickHandler(evt) {
  var btn = evt.target;
  if (btn.nodeName === 'BUTTON') {
    var col = btn.getAttribute('col');
    var row = btn.getAttribute('row');
    alert('clicked on cell '+col+row);
  }
}

function addTable() {
  var X_Length = 10;//localStorage.getItem("XWert");
  var Y_Length = 10;//parseInt(localStorage.getItem("YWert")) + 1;
  var myTableDiv = document.getElementById("Table");
  var table = document.createElement('TABLE');
  table.addEventListener('click', clickHandler); // <--- One event listener for the entire table.
  var tableBody = document.createElement('TBODY');
  table.appendChild(tableBody);

  for (var i = 0; i < Y_Length; i++) {
    var tr = document.createElement('TR');
    tableBody.appendChild(tr);
    for (var j = 0; j < X_Length; j++) {
      var td = document.createElement('TD');

      if (j == 0 && i != 0) {
        td.innerHTML = i;
      }
      else if (i == 0 && j != 0) {
        td.innerHTML = abc[j - 1];
      }
      else {
        var button = document.createElement("button");
        button.setAttribute('col', abc[j - 1]);
        button.setAttribute('row', i);
        button.innerHTML = "";
        td.appendChild(button);
      }

      tr.appendChild(td);
    }
  }

  myTableDiv.appendChild(table);
}

addTable();
th, td {
  border: 1px solid #999;
  margin: 0;
  padding: 5px;
  width: 75px;
}

table {
  border-collapse: collapse;
}

Also, conciser moving code that only needs to run once outside of your function so it does not have to run each time the function is called.


text:
Q: How to fix still reachable error in valgrind? -----update-----
I managed to fix the issue by not exiting mid-function but returning to main and exiting there.
Can you explain why it worked?
tnx

I keep getting still reachable valgrind error on my code.
Already tried:

*

*close file before exit, and before function readCSV ends

*declare iss once, and using iss.str, iss.clear
(all destructors are default)
I think this function is causing me problems. I's called from the main function, and reads the csv file into a deque:
static std::deque<Fractal *> readCSV(const std::string &path)
{
    std::deque<Fractal *> fractals;
    std::ifstream ifs(path);
    if (ifs.fail())
    {
        std::cerr << INV_INPUT << std::endl;
        exit(1);
    }
    std::string line;
    while (getline(ifs, line))
    {
        std::istringstream iss(line);
        std::string arg;
        int type, height;
        getline(iss, arg, ',');
        type = strToN(arg);//parse int from string, -1 if not a valid integer
        getline(iss, arg, ',');
        height = strToN(arg);
        if (height <= 0 || height > MAX_HEIGHT)
        {
            std::cerr << INV_INPUT << std::endl;
            deleteFractalArr(fractals);
            exit(1);
        }
        if (getline(iss, arg, ','))
        {
            std::cerr << INV_INPUT << std::endl;
            deleteFractalArr(fractals);
            exit(1);
        }

        switch (type)
        {
            case 1:
                fractals.push_front(new SCarpet(height));
                break;
            case 2:
                fractals.push_front(new SSieve(height));
                break;
            case 3:
                fractals.push_front(new CDust(height));
                break;
            default:
                std::cerr << INV_INPUT << std::endl;
                deleteFractalArr(fractals);
                exit(1);
        }
    }
    return fractals;
}

the deleteFractalArr is as follows:
static void deleteFractalArr(const std::deque<Fractal *> &fractals)
{
    for (Fractal *f:fractals)
    {
        delete f;
        f = nullptr;
    }
}


text:
Q: Converting from Timeline to Thread I am trying to create a program that runs off of a thread instead of a timeline.  Here is my modified program down below.  I am not sure why it will not work.  Any tips would be appreciated.  The thread uses a task in order to start the animation.  Thanks for your help.
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Arc;
import javafx.scene.shape.ArcType;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;

public class ch30 extends Application {
  @Override // Override the start method in the Application class
  public void start(Stage primaryStage) {
    FanPane fan = new FanPane();

    HBox hBox = new HBox(5);
    Button btPause = new Button("Pause");
    Button btResume = new Button("Resume");
    Button btReverse = new Button("Reverse");
    hBox.setAlignment(Pos.CENTER);
    hBox.getChildren().addAll(btPause, btResume, btReverse);

    BorderPane pane = new BorderPane();
    pane.setCenter(fan);
    pane.setBottom(hBox);

    // Create a scene and place it in the stage
    Scene scene = new Scene(pane, 200, 200);
    primaryStage.setTitle("Exercise15_28"); // Set the stage title
    primaryStage.setScene(scene); // Place the scene in the stage
    primaryStage.show(); // Display the stage

     Runnable first = new Begin();

     Thread t1 = new Thread(first);

     t1.start();

   //Timeline animation = new Timeline(
      //new KeyFrame(Duration.millis(100), e -> fan.move()));
    //animation.setCycleCount(Timeline.INDEFINITE);
    //animation.play(); // Start animation

    scene.widthProperty().addListener(e -> fan.setW(fan.getWidth()));
    scene.heightProperty().addListener(e -> fan.setH(fan.getHeight()));

    //btPause.setOnAction(e -> first.wait());
    btResume.setOnAction(e -> first.run());
    btReverse.setOnAction(e -> fan.reverse());
  }

  /**
   * The main method is only needed for the IDE with limited
   * JavaFX support. Not needed for running from the command line.
   */
  public static void main(String[] args) {
    launch(args);

  }
}

class FanPane extends Pane {
  private double w = 200;
  private double h = 200;
  private double radius = Math.min(w, h) * 0.45;
  private Arc arc[] = new Arc[4];
  private double startAngle = 30;
  private Circle circle = new Circle(w / 2, h / 2, radius);

  public FanPane() {
    circle.setStroke(Color.BLACK);
    circle.setFill(Color.WHITE);
    getChildren().add(circle);

    for (int i = 0; i < 4; i++) {
      arc[i] = new Arc(w / 2, h / 2, radius * 0.9, radius * 0.9, startAngle + i * 90, 35);
      arc[i].setFill(Color.RED); // Set fill color
      arc[i].setType(ArcType.ROUND);
      getChildren().addAll(arc[i]);
    }
  }

  private double increment = 5;

  public void reverse() {
    increment = -increment;
  }

  public void move() {
    setStartAngle(startAngle + increment);
  }

  public void setStartAngle(double angle) {
    startAngle = angle;
    setValues();
  }

  public void setValues() {
    radius = Math.min(w, h) * 0.45;
    circle.setRadius(radius);
    circle.setCenterX(w / 2);
    circle.setCenterY(h / 2);

    for (int i = 0; i < 4; i++) {
      arc[i].setRadiusX(radius * 0.9);
      arc[i].setRadiusY(radius * 0.9);
      arc[i].setCenterX(w / 2);
      arc[i].setCenterY(h / 2);
      arc[i].setStartAngle(startAngle + i * 90);
    }
  }

  public void setW(double w) {
    this.w = w;
    setValues();
  }

  public void setH(double h) {
    this.h = h;
    setValues();
  }
}

   class Begin implements Runnable {
        private int times = 1000;
        FanPane fan = new FanPane();

        public Begin(){
           // times = t;
       }

        @Override
        public void run(){
            //for (int i = 0; i < times; i++)
            //{
                fan.move();
            }
        }

A: Your thread needs a loop, that repeatedly pauses and then updates the UI. If you want to use an explicit thread instead of the more obvious Timeline, you need to write the code for that loop yourself.
The update of the UI cannot be called from the background thread you are creating: to update the UI on the FX Application thread you must wrap the call to the method(s) that update the UI in Platform.runLater(...).


text:
Q: Caret: Error in switch(tolower(trControl$method), oob = NULL, alt_cv = , cv = createFolds(y, I'm using caret package to tune alpha and lambda parameters for glmnet model. My features are in X (dataframe, 47 obs. of 14474 variables, a p>>N problem) and the dependent variable, y is a dataframe of 47 obs. of 1 variable.
When I try
   trC = trainControl(method=cv, number=10)
   fitModel = train(X, y, trControl=trC, method="glmnet")

I get
 Error en switch(tolower(trControl$method), oob = NULL, alt_cv = , cv = createFolds(y,:
   EXPR must be a length 1 vector
 Además: Mensajes de aviso perdidos
 In if (trControl$method == "oob" & !(method %in% c("rf", "treebag",  :
 la condición tiene longitud > 1 y sólo el primer elemento será usado

I've tried transposing y, and also changing to class(y) = "numeric", instead of "data.frame" but I get the same error, that I don't understand. Any clue?

A: Use method = "cv" not method = cv.
Max


text:
Q: how do I use getTheadThProps in react table? I have this on my table render function:
...
const getTheadThProps = (state, rowInfo, column, instance) => {
 return {
    onClick: (e) => {
         // do your thing
         // call old handler, HOW ?
       }
    }
}

return (
<reactTable
...
getTheadThProps={getTheadThProps}
...
/>)

The documentation talks about onClick: (e, handleOriginal), tried that, but handleOriginal was always being undefined, so the example on documentation doesn't work.
When I replace the click event in this way, the "normal" sorting mechanism gets broken (toggleSort - the method that toggles the sorting status of the column header never gets called). That's the reason of why I need to call the original function.

A: I was having the same issue. It looks like you can recover the column sorting with the following:
getTheadThProps={(state, rowInfo, column, instance) => ({
  onClick: () => {
    // Do whatever else you need to
    if (column.sortable !== false) {
      instance.sortColumn(column)
    }
  },
})


text:
Q: Count how many students if their average score is known If score is integer 1-100.
score -> student(s)
60 -> 1 student [60]
50.5 -> 2 students with total score 101
50.5 -> 10 students with total score 505 -> false, because minimum is 2 students.
32.5 -> 2 students [60, 5]
32.5 -> 10 students with total score 325 -> false, because minimum is 2 students.

How to find the minimum students?

A: Call $n$ the minimum number of students and $s$ the score. I think $n$ is just:  $n = min\{ k \ \vert \ sk \in \mathbb N\}$ for some integer $k$. That is, if you write $s$ in its reduced rational number form $s = \frac{p}{q} $ for coprime integers $p$ and $q$, then $n = q$ (this question is not valid for the irrationals).
Examples:
$$
\begin{split}
s=60 = \frac{60}{1} \qquad ------> \qquad \text{students} = 1 \\
s=50.5 = \frac{505}{10} = \frac{101}{2} \qquad  ------> \qquad \text{students} = 2 \\
s=32.5 = \frac{325}{10} = \frac{65}{2} \qquad ------> \qquad \text{students} = 2 \\
s=32.222\ldots = \frac{290}{9} \qquad------> \qquad \text{students} = 9 \\
\end{split}
$$
Feel free to correct me on this.


text:
Q: How to change Android Studio default gradle JDK to 11 Getting this message when I click run:
> Failed to apply plugin 'com.android.internal.application'.
   > Android Gradle plugin requires Java 11 to run. You are currently using Java 1.8.
     You can try some of the following options:
       - changing the IDE settings.
       - changing the JAVA_HOME environment variable.
       - changing `org.gradle.java.home` in `gradle.properties`.

The answers from Error message "Android Gradle plugin requires Java 11 to run. You are currently using Java 1.8" to change the Gradle JDK in settings work. but only for that one project. When I create a new project, Android Studio automatically uses default 1.8 again.
I have 11 available, AS just doesn't automatically use it.
Things I tried: changed the JAVA_HOME env to the location for JDK 11 here, but still get the same error.
Invalid cache /restart a bunch of time does nothing
How to set it once and apply it to all future new projects?

Attaching app/build.gradle
plugins {
    id 'com.android.application'
    id 'kotlin-android'
}

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.example.grid"
        minSdk 22
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.0'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.2'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    implementation 'com.github.bumptech.glide:glide:4.12.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0'
}

top level build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:7.0.3"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.31"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

A: Might seem late, but I fixed mine by just installing the java jdk needed, installed jdk 17 by the way. That's after downloading it from my browser and installing it.
then you could check your java version on your device using; "java --version" command on cmd, then you could just restart your pc and open android studio. then check the jvm of gradlew --version command on terminal in android studio and if it's updated you are good to go

A: Multiple Android Studio Installed?
Short Answer:
Just delete the other version and it should fix the problem.
Long answer:
I had two versions of Android Studio installed Android 4.2 and Android Arctic Fox. Both Android Studio had different Gradle JDK version installed.
This is what I was seeing in Arctic Fox Gradle Settings. (Default selection was 1.8)

My theory:
If you notice Gradle JDK is installed under Applications/Android Studio/Content/
It's my assumption that Gradle Settings page pulls up all the installed Gradle JDK versions. And there is no option to set the default version in Settings page. So the first Gradle version becomes the default.
I don't know if it is alphabetically sorted or based on Download timestamp.
But I believe it is based on the timestamp. The oldest installed version gets to the top in the list.
Here is a supporting observation. When I deleted Android Studio 4.2 and ctrl+z (Undo) it the list order changed.

Disclaimer:
I could be completely wrong as I don't have any official doc, link that support this claim. It is just a theory.
And I also understand that it is not an ideal solution. As deleting old Android Studio may not be the option for everyone.

A: 2023 Update
I was trying to update from VERSION 1.8 to VERSION 11. Every time I close the Studio and open it again, it resets. Went through the solutions on the web and found none working. I couldn't find the file that held JDK information. The file has been changed in the newer releases.
New Solution:
Step 1: Open the Android Studio and keep it open.
Step 2:
Go to the location given below:
C:\Users\{username}\AppData\Roaming\Google\AndroidStudio2022.1\options

or press Win + R and enter the following:
%userprofile%\AppData\Roaming\Google\AndroidStudio2022.1\options

Your latest version of Android Studio might be different.
Step 3: Delete the file jdk.table.xml from the options folder.
Step 4: Change the Gradle JDK to the new JDK in the settings, so that the Studio can save the new path in the file. (Important: Else Studio assigns JDK from it's memory)
Step 5: Restart Android Studio.
This fixed the issue for me. The newly created jdk.table.xml will have the updated JDK values.

A: Here is what I was able to do to fix this after a bunch of googling and SO-ing:
Find the folder for your current version of AS. On Mac it was ~/<username>/Library/Application Support/Google/AndroidStudio<version>
Note: I kept messing in version4.1 stuff until I realized that I needed 2022.1 because the text wrapped and my brain kept seeing 202 2.1 instead of 2022.1.
in that folder is an options folder with a file named jdk.table.xml
I opened that in a file editor and after some messing around found this out.
my XML had all my JDKs in here. at the top was 1.8 with some other xml entries for defaults like this
<application>
  <component name="ProjectJdkTable">
    <jdk version="2">
      <name value="Kotlin SDK" />
      <type value="KotlinSDK" />
      <homePath value="$KOTLIN_BUNDLED$" />
      <roots>
        <annotationsPath>
          <root type="composite" />
        </annotationsPath>
        <classPath>
          <root type="composite" />
        </classPath>
        <javadocPath>
          <root type="composite" />
        </javadocPath>
        <sourcePath>
          <root type="composite" />
        </sourcePath>
      </roots>
      <additional />
    </jdk>
    <jdk version="2">
      <name value="Android API 31 Platform" />
      <type value="Android SDK" />
      <version value="AdoptOpenJDK (OpenJ9) version 11.0.11" />
      <homePath value="$USER_HOME$/Library/Android/sdk" />
      <roots>
        <annotationsPath>
          <root type="composite">
            <root url="jar://$USER_HOME$/Library/Android/sdk/platforms/android-31/data/annotations.zip!/" type="simple" />
          </root>
        </annotationsPath>
        <classPath>
          <root type="composite">
            <root url="jar://$USER_HOME$/Library/Android/sdk/platforms/android-31/android.jar!/" type="simple" />
            <root url="file://$USER_HOME$/Library/Android/sdk/platforms/android-31/data/res" type="simple" />
          </root>
        </classPath>
        <javadocPath>
          <root type="composite" />
        </javadocPath>
        <sourcePath>
          <root type="composite">
            <root url="file://$USER_HOME$/Library/Android/sdk/sources/android-31" type="simple" />
          </root>
        </sourcePath>
      </roots>
      <additional jdk="1.8" sdk="android-31" />
    </jdk>
    <jdk version="2">
      <name value="1.8" />
      <type value="JavaSDK" />
      <version value="AdoptOpenJDK (HotSpot) version 1.8.0_292" />
      <homePath value="/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home" />
      <roots>
    ......

I changed the info in the Android 31 Platform entry to match what I wanted, in this case Java 11. It now looks like this
<jdk version="2">
      <name value="Android API 31 Platform" />
      <type value="Android SDK" />
      <version value="AdoptOpenJDK (OpenJ9) version 11.0.11" />
      <homePath value="$USER_HOME$/Library/Android/sdk" />
      <roots>
        <annotationsPath>
          <root type="composite">
            <root url="jar://$USER_HOME$/Library/Android/sdk/platforms/android-31/data/annotations.zip!/" type="simple" />
          </root>
        </annotationsPath>
        <classPath>
          <root type="composite">
            <root url="jar://$USER_HOME$/Library/Android/sdk/platforms/android-31/android.jar!/" type="simple" />
            <root url="file://$USER_HOME$/Library/Android/sdk/platforms/android-31/data/res" type="simple" />
          </root>
        </classPath>
        <javadocPath>
          <root type="composite" />
        </javadocPath>
        <sourcePath>
          <root type="composite">
            <root url="file://$USER_HOME$/Library/Android/sdk/sources/android-31" type="simple" />
          </root>
        </sourcePath>
      </roots>
      <additional jdk="11.0.11" sdk="android-31" />
    </jdk>

make sure to change the version tag, as well as the additional tag at the bottom to match your JDK of choice
I then cut the 1.8 jdk tag and moved it to the bottom in case something needed it.
I repeated this for all the entries in the file that defaulted to 8, I think there were four--one each for android 29, 30, 31, and 32.
I restarted AS and created a new project and it worked.
I have not run into build or run issues yet.

A: i meet the same problem. i solved the problem now.
i reset my android studio by delete C:\Users\<UserName>\AppData\Local\Google\AndroidStudio<Version>, C:\Users\<UserName>\AppData\Roaming\Google\AndroidStudio<Version>. (you'd better close android studio before), then restart android studio.you will see the gradle sdk is default set as android studio default sdk.
as you can see, the solution will delete your android studio configuration. if you have important configuration in android studio, you should back up the configuration to restore.

A: Have you tried:
app module build.gradle file.
android {
    // ...
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_11
        targetCompatibility JavaVersion.VERSION_11
    }
    kotlinOptions {
        jvmTarget = '11'
    }
}

Also try to select the default provided Android Studio SDK

A: Remove any older sdk platforms you have installed via the SDK manager

Restart Android Studio, create a new project. Voila!


text:
Q: Traversing subgroups and group layers with PyQGIS I am trying to find the name of subgroups using PyQGIS. I have been trying to use Playing with subgroups
I am however unable to traverse and get the names of the subgroup. I have tried the code on this article.
for child in root.children():
  if isinstance(child, QgsLayerTreeGroup):
    print "- group: " + child.name()
    if child.name() == "test": #to check subgroups within test group
        for child in root.children(): #which I think i am making a mistake here because the root is supposed to contain all nodes

A: Since you want to start reading children from your main group (not from root anymore), try this (pay attention to the last 3 lines):
for child in root.children():
  if isinstance(child, QgsLayerTreeGroup):
    print "- group: " + child.name()
    if child.name() == "test": #to check subgroups within test group
        for subChild in child.children():
            if isinstance(subChild, QgsLayerTreeGroup):
                subChild.name()


text:
Q: how to align two input field and div inline html:

   <input style="margin: 2px;" type="button" name="delete"  class="delete_types" id="delete_name"/>

{{type.title}}  {{ type.is_active|yesno:"On,Off" }} >

<input style="margin: 2px;" type="button" name="delete"  value="Delete" id="{{ type.id }}" class="type_delete"/>

I want to keep the two input button and middle div into same line.Now it looks in below screen shot.I am working in django framework.I tried with display:inline and display:block not making any sense.Please help

A: Use float:left; to show them inline.
For Instance,
<input type="button" id="delete_name" class="delete_types" name="delete" style="margin: 2px; float: left;">

A: Your code should look like this

<input style="margin: 2px;" type="button" name="delete"  class="delete_types" id="delete_name"/>

{{type.title}}  {{ type.is_active|yesno:"On,Off" }} >

<input style="margin: 2px;" type="button" name="delete"  value="Delete" id="{{ type.id }}" class="type_delete"/>


text:
Q: Listen for wakeonlan request I would like to know how to listen for wakeonlan paquets on a running system.
I know that my question might seem a little bit useless, because, if a system is running, there is no need to wake up it!

A: The other answer only works for "Wake-Up!"-packets coming in via UDP:9 (like from wakeonlan, and not for packets of the dedicated ethertype 0x0842 (AMD magic packet format) (e.g. etherwake).
To grab the relevant part of the payload for both of those wake-up methods:
tcpdump -UlnXi eth0 ether proto 0x0842 or udp port 9 2>/dev/null |
sed -nE 's/^.*20:  (ffff|.... ....) (..)(..) (..)(..) (..)(..).*$/\2:\3:\4:\5:\6:\7/p'

Output is one mac-address per line, line-buffered.

A: With nc you can listen on an udp port. The magic packet usually is sent to port 9 via broadcast. So, the command would be:
nc -ul 9

Depending on the nc implementation, you may also need to provide the -p flag:
nc -ul -p 9

To test it use the wakeonlan command...
wakeonlan <your-mac>

...and see in the nc terminal the output.


text:
Q: Adding will-change: transform to css causes images to disappear I have been running into some weird issues with will-change: transform while I add this property to the img and div tags. Basically, I have a div as a container that contains an img element as its child and I am scrolling through these images in webkit. Adding will-change-tranform greatly improves the scrolling performance, but as you scroll you intermittently see images disappear(or hidden). Any answers to fix this problem would be great as I have exhausted most of the solutions I have tried from online resources.
I am attaching the code snippet for the CSS:
".cell" and ".pagNum" are class name attributes for the div.
".pageNum" is a page number div on top of the img div(.cell). ".cell" div contains the img element.
img {
    position: relative;
    -webkit-user-drag: none;
    will-change: transform;
}

.cell {
    position: absolute;
    -webkit-border-radius: 0px;
    -moz-border-radius: 0px;
    will-change: transform;
}

.pageNum {
    display: inline-block;
    position: absolute;
    top: 273px;
    background-position: center;
    text-align: center;
    line-height: 36px;
    min-width: 36px;
    padding-left: 6px;
    padding-right: 6px;
    -webkit-border-radius: 3px;
    background-color: rgba(0, 0, 0, .50);
    color: white;
    font-size: medium;
    font-weight: bold;
    text-shadow: 0px 1px 0px #000000;
    left: 50%;
    margin: 0px 0 0 -32px;
    will-change: transform;

}


text:
Q: PDF Link coordinate not correct? Please refer to Get PDF hyperlinks on iOS with Quartz
It explained an algorithm to find the the pdf hyperlink and its coordinate.I followed this post and write my own pdf reader. It works well for most of the pdf files but not for one pdf file. The problem is the coordinate of the hyperlink is not correct.
Here is the pdf I created the hyperlink:

I created a hyperlink from Adobe acrobat 10.0. The origin of this hyperlink is almost at (0,0).Then I use the algorithm to parse my pdf file. To my surprise the result rect is:
link rect = {{63, 123}, {173, -158}}
So when I render this rect in screen, it's something like this:

What could be reason? Can anybody advise? Thanks
By the way, if there is a way to upload my sample pdf file here?

A: Have you allowed for a cropbox?


text:
Q: How to get internal Id from the Sasvedsearch of Netsuite soap API I am fetching Vendor payment data from Netsuite via SOAP API in .Net. Unable to get the Internal Id in the result. My code as below
    TransactionSearchAdvanced TSA = new TransactionSearchAdvanced();
        TSA.savedSearchId = "2218";
        TransactionSearch TS = new TransactionSearch();
        TransactionSearchBasic TSB = new TransactionSearchBasic();

        #region Setting From & To Period
        DateTime theSearchStartDate = System.DateTime.Today.AddDays(-365);
        DateTime theSearchFinishDate = System.DateTime.Today;
        SearchDateField theDTSearch = new SearchDateField();
        theDTSearch.operatorSpecified = true;
        theDTSearch.@operator = SearchDateFieldOperator.within;
        theDTSearch.searchValue2Specified = true;
        theDTSearch.searchValueSpecified = true;
        theDTSearch.searchValue = theSearchStartDate;
        theDTSearch.searchValue2 = theSearchFinishDate;
        #endregion

        TSB.tranDate = theDTSearch;

        TS.basic = TSB;
        TSA.criteria = TS;

        SearchResult SR = NService.search(TSA);


text:
Q: Is it possible to emulate an ftp server? We have devices that can sync their data with an ftp server.
Each device should contain their own set of data (video files).
We do not want to duplicate this data for each device.
I was thinking along the lines of faking the ftp file list repsonse and rerouting each file request to another location using something similar to an httphandler. This way we only have to host our video files on one location and each device will still be able to get their own "set".
sftp is a "should have" for this scenario.
I tried searching anything along the lines of "ftp handler" but have not come up with any helpful results.

A: SUSE used to have a product (not written in C# though, and only for Linux) that does exactly what you want, the now abandoned Proxy Suite.  I can confirm it works but I was never satisfied with its performance.  Check it out, it might at least give you some ideas to work with should you want to develop such a contraption yourself.

A:
Is it possible to emulate an ftp server?

No, it is not.

I was thinking along the lines of faking the ftp file list repsonse and rerouting each file request to another
  location using something similar to an httphandler.

Do it.
Te problem is that this is not "faking", your server IS a FTP server implementing the FTP protocol. A "Fake" is impossible logically - either you implement the protocol, then you are a FTP server, or you do not, then you are not.

I tried searching anything along the lines of "ftp handler" but have not come up with any helpful results.

Google for "rfc ftp" and take it from there. That is RFC 959 and likely a dozen other ones. http://de.wikipedia.org/wiki/File_Transfer_Protocol lists 5 relevant RFC - 959, 1579, 2228, 2428 and 2640.
Alternatively looking for a programmable proxy may work - it is not that common, though, people seem to use HTTP more these days for file transfer, or system intrinsic protocols that have other features.


text:
Q: Summarize data from fileInput to use in updateCurrencyInput / updateNumericInput Currently creating a sales report generating site in R using Shiny. I have been struggling to pull the data from a CSV file the user imports into the dashboard itself. I need to use the data from my fileInput to run a calculation and then actively display these results in my shiny window. Ideally this would be initiated by the action of selecting the CSV file for the fileInput by the user and the calculations would occur.
Let's say this is the CSV that the user inputs

ID
DATE
GROSS

000001
5/22/22
75000

000002
5/25/22
100000

Here is an abridged version of the related code
# Load packages
library(shiny)
library(bslib)
library(shinyWidgets)
library(dplyr)

# Define static variables
mayquota <- 135000

# UI
ui <- navbarPage(title = "Example",
                 tabPanel(title = "Page 1",
                          fluidPage(inputPanel(textInput("key", "KEY")),
                                    fixedRow(column(12, fileInput("salesdata", "SALES DATA",
                                                    width = 100%, buttonLabel = "SELECT"))),
                                    inputPanel(currencyInput("profits", "PROFITS", format = "dollar",
                                                             value = 0, align = "right"),
                                               currencyInput("quota", "QUOTA", format = "dollar",
                                                             value = 0, align = "right"),
                                               currencyInput("difference", "DIFFERENCE",
                                                             format = "dollar", value = 0,
                                                             align = "right")))))

# Server
server <- function(input, output, session) {
  prof <- reactive({read_csv(input$profits)})
  toListen <- reactive({input$key})
  observeEvent(toListen(),
               {if(input$key == "test123")
                {updateCurrencyInput(session, "quota", value = mayquota)
                 updateCurrencyInput(session, "difference", value = profits() - mayquota}})
}

# Run application
shinyApp(ui = ui, server = server)

I need to pull the sum of the GROSS column in the CSV and use it to updateCurrencyInput in the form of:
updateCurrencyInput(session, "profits", value = profits())

I was hoping that something like this would work:
toListenFile() <- reactive({input$salesdata})
observeEvent(toListenFile(), {profits <- reactive({prof() %>% summarize(sum(`GROSS`))})})

But I was given the error that summarize from dplyr could not be used on reactive data. So that is where I stand. Any help would be appreciated to achieve a similar function to dplyr in a reactive environment where the CSV data is inputted by the user.

A: It appears as though I have a solution to my issue, just wanted to share since I already opened the question.
server <- function(input, output, session) {
  abcInput <- reactive({
    req(input$salesdata)
    tibble(read_csv(input$salesdata$datapath))
  })
  sumprof <- reactive({sum(abcInput()$`GROSS`)})
  observeEvent(input$rdata, {updateCurrencyInput(session, "profits", value = sumprof())
  })

There might be a more elegant way to achieve this, but this appears to work thus far.


text:
Q: Video uploading not working in laravel 5 I am working on uploading the videos for my website. But i unable to do it. I have search many documents but i am fail to solve it. Can any one help me out to solve this problem?
I am getting an error "Call to a member function getClientOriginalName() on null"
//Form code for video upload..
{!! Form::open(array('url' => 'video' , 'files' => true)) !!}

    {!! Form::label('video_name', 'Video Name : ') !!}
    {!! Form::text('name',null, ['class' => 'form-control']) !!}

        {!! Form::label('video_path', 'Select Video : ') !!}
        {!! Form::file('path', ['class' => 'form-control'])!!}

        {!! Form::submit('Upload Video')  !!}

    {!! Form::close() !!}

//Controller Code
public function store(Request $request){
    $data = $request->all();
    if ( $request->hasFile( 'path' ) ) {
        $file = $request->file( 'path' );
        $name = $file->getClientOriginalName();
        $data[ 'path' ] = $name;
        $destination = '/public/videos';
        $request->file( 'path' )->move( base_path() . $destination, $name );
        return $name;
    }
    else {
        return '';
    }
}

//The above code is working for images, doucments and audio but not working for videos.
Thanks in advance

A: If your uploaded video is larger than the upload setting in your php.ini then you get this problem.
I suggest check your php.ini file and increase these directives as needed

php.ini
Example
post_max_size=200M
upload_max_filesize=200M


text:
Q: Include an OR condition in a COUNTIF? This question has been asked before and the answer always seems to be to add together two COUNTIFs. This is fine for most applications, but won't work for me.
I have a column that can contain 0, 1 or more valid tokens as well as 0, 1 or more invalid tokens. For example, if A, B and C are valid tokens and D, E and F are invalid, I might have data that looks like in the "Token" column in the table below. I've added the "ValidCount" and "Valid" columns to show the different interpretations.
    ╔══════╦═══════╦════════════╦═══════╗
    ║ Row# ║ Tokens║ ValidCount ║ Valid ║
    ╠══════╬═══════╬════════════╬═══════╣
    ║   1  ║ A, E  ║        1   ║ True  ║
    ║   2  ║       ║        0   ║ False ║
    ║   3  ║ B     ║        1   ║ True  ║
    ║   4  ║ F, G  ║        0   ║ False ║
    ║   5  ║ A,B,C ║        3   ║ True  ║
    ║   6  ║ C     ║        1   ║ True  ║
    ╚══════╩═══════╩════════════╩═══════╝
I can count instances of valid tokens with the following (where the raw data is on a sheet called "Raw", the tokens are in column AD and the token in question is in cell A30 on the sheet called "Summary":
=COUNTIF(Raw!$AD$2:$AD$79,CONCATENATE("*",Summary!$A30,"*"))

The trouble is that if I do this for each valid token and sum them, I end up counting the total number of valid tokens. What I want to do is get the number of cells with at least one valid token. Using the example above, the correct answer is 4, not 6.
What I want to do is use an OR function like this:
=COUNTIF(Raw!$AD$2:$AD$79,OR(CONCATENATE("*",Summary!$A30,"*"),CONCATENATE("*",Summary!$A31,"*"),[...snip...]))

but this gives 0.
Is there a way to do this? Ideally without resorting to VBA.

A: Here are two possible formula approaches - if the "valid tokens" are shown (one each) in cells Summary!A30:A32 then you can use this version
=SUMPRODUCT((ISNUMBER(SEARCH(Summary!A30,Raw!$AD$2:$AD$79))+ISNUMBER(SEARCH(Summary!A31,Raw!$AD$2:$AD$79))+ISNUMBER(SEARCH(Summary!A32,Raw!$AD$2:$AD$79))>0)+0)
or more easily "extensible" for a larger criteria range try this array formula
=SUM((MMULT(ISNUMBER(SEARCH(TRANSPOSE(Summary!A30:A32),Raw!$AD$2:$AD$79))+0,{1;1;1})>0)+0)
confirmed with CTRL+SHIFT+ENTER
{1;1;1} needs to match the length of the criteria range and TRANSPOSE is only required if the criteria range is vertical.....

A: You could maybe find all the zeroes, and subtract this from the total?
I'm thinking of:
=counta(Raw!$AD$2:$AD$79)-countif(Raw!$AD$2:$AD$79,0)
[I'm assuming there are no blank cells in range AD2:AD79]
That seems to get me what you want to get. Could you perhaps confirm?
EDIT: Okay, seems your initial data is not at ALL what you actually have, so, change in approach.
I would suggest this formula in one additional column (cell C2):
=IF(AND(ISERROR(FIND("A",B2)),ISERROR(FIND("B",B2)),ISERROR(FIND("C",B2))),0,1)
This gives 0 if any of A, B or C aren't in cell B2, and gives 1 if any one of those are in cell B2.
Drag to the bottom. Excel's status bar gives you the sum, or you could use a =SUM() function on the column.

A: My first thought was using the COUNTIFS function but that ANDs the criteria together. The OR is the right idea but as you noticed it doesn't test the cell value inside the OR criteria.
The only thing I could come up with was to use VBA. I put your sample tokens in the first six rows in a worksheet and came up with this code. It could easily be modified to be a new function to use as a formula as well.

Sub CountTokens()

    Dim count As Integer
    Dim token As String
    Dim tokens As Variant

    For Each Cell In Sheet1.Range("A1:A6")
        tokens = Split(Cell.Value, ", ")
        For tIndex = LBound(tokens) To UBound(tokens)
            token = tokens(tIndex)
            If token = "A" Or token = "B" Or token = "C" Then
                count = count + 1
                Exit For
            End If
        Next tIndex
    Next Cell

    MsgBox "Count: " & count

End Sub


text:
Q: SWIFT: Button Title changing back to original title unwarranted So I have the following code which executes upon tapping one side or another of my segmented control:
@IBAction func logInOrSignUpIndexChanged(_ sender: UISegmentedControl) {

    // Correct setup for Sign Up
    if sender.selectedSegmentIndex == 0 {

        confirmPasswordTextfield.isHidden = false
        confirmPasswordTextfield.isUserInteractionEnabled = true
        createAccountOrLogInButton.titleLabel?.text = "Create Account"
        rememberMeViewTopConstraint.constant = 20

    } // Correct setup for Log In
    else if sender.selectedSegmentIndex == 1 {

        confirmPasswordTextfield.isHidden = true
        confirmPasswordTextfield.isUserInteractionEnabled = false
        createAccountOrLogInButton.titleLabel?.text = "Log In"
        rememberMeViewTopConstraint.constant = -34

    }

}

For some reason, when I press the segmented index value of 1 (so the bottom if statement executes), the button title changes to "Log In" for a split second then reverts back to "Create Account".  I tried changing the initial title of the button which of course doesn't work, and tried taking out the line in the first if statement, that changes the title to "Create Account", and the title still changes, so I know that the first if statement is not being executed again for some  arbitrary reason.  Any idea what's wrong?

A: Change
createAccountOrLogInButton.titleLabel?.text = "Log In"

to
createAccountOrLogInButton.setTitle("Log In",for:.normal)

same for the first if also

A: My issue with Xcode 13 was posted
here
Select the style of default on the button.


text:
Q: Why is call by reference so much slower than inline code? I am programming a physics simulation with few particles (typically 3, no more than 5).
In a condensed version my code structure like this:
#include<iostream>

class Particle{
  double x; // coordinate
  double m; // mass
};

void performStep(Particle &p, double &F_external){
   p.x += -0.2*p.x + F_external/p.m; // boiled down, in reality complex calculation, not important here
}

int main(){

 dt = 0.001; // time step, not important

 Particle p1;
 p1.x = 5; // some random number for initialization, in reality more complex but not important here
 p.m = 1;

 Particle p2;
 p2.x = -1; // some random numbersfor initialization, in reality more complex but not important here
 p.m = 2;

 Particle p3;
 p3.x = 0; // some random number for initialization, in reality more complex but not important here
 p.m = 3;

 double F_external = 0; // external forces

 for(unsigned long long int i=0; i < 10000000000; ++i){ // many steps, typically 10e9
    F_external = sin(i*dt);
    performStep(p1, F_external);
    performStep(p2, F_external);
    performStep(p3, F_external);
 }

 std::cout << "p1.x: " << p1.x << std::endl;
 std::cout << "p2.x: " << p2.x << std::endl;
 std::cout << "p3.x: " << p3.x << std::endl;

}

I have determined with clock() that the performStep(p, F_external) call is the bottleneck in my code).
When I tried to do inline calculation, i.e. replace performStep(p1, F_external) by p1.x += -0.2*p1.x + F_external/p1.m; the calculation suddenly was roughly a factor of 2 faster. Note that performStep() in reality is about ~60 basic arithmetic calculations over ~20 lines, so the code becomes really bloated if I just inline it for every particle.
Why is that the case? I am compiling with MinGW64/g++ and the -O2 flag. I thought the compiler would optimize such things?
Edit:
Here is the function that is called. Note that in reality, I calculate all three coordinates x,y,z with a couple of different external forces. Variables which are not passed via the function are a member of SimulationRun. The algorithm is a fourth-order leapfrog algorithm.
void SimulationRun::performLeapfrog_z(const unsigned long long int& i, const double& x, const double& y, double& z, const double& vx, const double& vy, double& vz, const double& qC2U0,
    const double& U0, const double& m, const double& C4, const double& B2, const double& f_minus, const double& f_z, const double& f_plus, const bool& bool_calculate_xy,
    const double& Find, const double& Fheating) {

    // probing for C4 == 0 and B2 == 0 saves some computation time
    if (C4 == 0) {
        Fz_C4_Be = 0;
    }
    if (B2 == 0 || !bool_calculate_xy) {
        Fz_B2_Be = 0;
    }

    z1 = z + c1 * vz * dt;

    if (C4 != 0 && !bool_calculate_xy) {
        Fz_C4_Be = (-4) * q * C4 * U0 * z1 * z1 * z1;
    }
    else if (C4 != 0 && bool_calculate_xy) {
        Fz_C4_Be = q * C4 * U0 * (-4 * z1 * z1 * z1 + 6 * z1 * (x * x + y * y));
    }
    if (B2 != 0 && bool_calculate_xy) {
        Fz_B2_Be = q * B2 * (-vx * z1 * y + vy * z1 * x);
    }
    acc_z1 = (qC2U0 * (-2) * z1 + Find + Fz_C4_Be + Fz_B2_Be + Fheating) / m;
    vz1 = vz + d1 * acc_z1 * dt;
    z2 = z1 + c2 * vz1 * dt;

    if (C4 != 0 && !bool_calculate_xy) {
        Fz_C4_Be = (-4) * q * C4 * U0 * z2 * z2 * z2;
    }
    else if (C4 != 0 && bool_calculate_xy) {
        Fz_C4_Be = q * C4 * U0 * (-4 * z2 * z2 * z2 + 6 * z2 * (x * x + y * y));
    }
    if (B2 != 0 && bool_calculate_xy) {
        Fz_B2_Be = q * B2 * (-vx * z2 * y + vy * z2 * x);
    }
    acc_z2 = (qC2U0 * (-2) * z2 + +Find + Fz_C4_Be + Fz_B2_Be + Fheating) / m;
    vz2 = vz1 + d2 * acc_z2 * dt;
    z3 = z2 + c3 * vz2 * dt;

    if (C4 != 0 && !bool_calculate_xy) {
        Fz_C4_Be = (-4) * q * C4 * U0 * z3 * z3 * z3;
    }
    else if (C4 != 0 && bool_calculate_xy) {
        Fz_C4_Be = q * C4 * U0 * (-4 * z3 * z3 * z3 + 6 * z3 * (x * x + y * y));
    }
    if (B2 != 0 && bool_calculate_xy) {
        Fz_B2_Be = q * B2 * (-vx * z3 * y + vy * z3 * x);
    }
    acc_z3 = (qC2U0 * (-2) * z3 + Find + Fz_C4_Be + Fz_B2_Be + Fheating) / m;
    vz3 = vz2 + d3 * acc_z3 * dt;

    z = z3 + c4 * vz3 * dt;
    vz = vz3;
}

A: Optimization is hard, even for compilers. Here are some optimization tips:

*

*Since your performStep is hotspot, put it into a header file(in case that you split declaration and definition into header/source), then add inline keyword, like:

// at file xxx.h
inline void performStep(Particle &p, double F_external){
   p.x += -0.2*p.x + F_external/p.m; // boiled down, in reality complex calculation, not important here
}

*Upgrade your compiler, maybe to the latest.

*use https://godbolt.org/ to check the assembly code. In this case, unnecessary dereference is the headache of performance.


text:
Q: How does one update the GTK+ GUI in C++ with time consuming operations? I am using OpenMP to perform a time consuming operation. I am unable to update a ProgressBar from GTK+ from within the time consuming loop at the same time the operations are carried out. The code I have updtates the ProgressBar, but it does so after everything is done. Not as the code progresses.
This is my dummy code that doesn't update the ProgressBar until everything is done:
void largeTimeConsumingFunction (GtkProgressBar** progressBar) {

    int extensiveOperationSize = 1000000;

    #pragma omp parallel for ordered schedule(dynamic)
    for (int i = 0; i < extensiveOperationSize; i++) {
        // Do something that will take a lot of of time with data

        #pragma omp ordered
        {
            // Update the progress bar
            gtk_progress_bar_set_fraction(*progressBar, i/(double)extensiveOperationSize);
        }

    }
}

When I do the same, but without using OpenMP, the same happens. It doesn't get updated until the end.
How could I get that GTK+ Widget to update at the same time the loop is working?
Edit: This is just a dummy code to keep it short and readable. It has the same structure as my actual code, but in my actual code I don't know before hand the size of the items I will be processing. It could be 10 or more than 1 million items and I will have to perform some action for each of them.

A: There are two potential issues here:
First, if you are performing long running computations that might block main thread, you have to call
while (gtk_events_pending ())
  gtk_main_iteration ();

every now and then to keep UI responsive (which includes redrawing itself).
Second, you should call GTK+ functions only from main thread.


text:
Q: Ef-Core - What regex can I use to replace table names with nolock ones in Db Interceptor I've been trying to port our EF6 project to EF-Core-2.0.
In EF6, we were using DbNolock interceptor for adding With (NOLOCK) hint which queries we want. You can find my ex-running Db interceptor code below.
   public class DbNoLockInterceptor : DbCommandInterceptor
    {
    private static readonly Regex TableAliasRegex = new Regex(@"((?<!\){1,5})AS \[Extent\d+\](?! WITH \(NOLOCK\)))", RegexOptions.Multiline | RegexOptions.IgnoreCase);

    public override void ScalarExecuting(DbCommand command,
        DbCommandInterceptionContext<object> interceptionContext)
    {
        command.CommandText =
            TableAliasRegex.Replace(command.CommandText, mt => mt.Groups[0].Value + " WITH (NOLOCK) ");
    }

    public override void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
    {
        command.CommandText = TableAliasRegex.Replace(command.CommandText,  mt => mt.Groups[0].Value + " WITH (NOLOCK) ");
    }
}

In Ef-Core, we can make interception nearly same way. But because of changing naming convention of tables, I couldn't write a Regex for the new one. You can find the new Ef-Core version below:
public class DbNoLockListener
{
    private static readonly Regex TableAliasRegex = new Regex(@"((?<!\){1,5})AS \[Extent\d+\](?! WITH \(NOLOCK\)))", RegexOptions.Multiline | RegexOptions.IgnoreCase);
    [DiagnosticName("Microsoft.EntityFrameworkCore.Database.Command.CommandExecuting")]
    public void OnCommandExecuting(DbCommand command, DbCommandMethod executeMethod, Guid commandId, Guid connectionId, bool async, DateTimeOffset startTime)
    {
        command.CommandText =
                        TableAliasRegex.Replace(command.CommandText, mt => mt.Groups[0].Value + " WITH (NOLOCK) ");
    }
}

Ef6 Generated SQL:
SELECT
    [Extent1].[Id] AS [Extent1Id],
    [Extent2].[Id] AS [Extent2Id]
    FROM [Advert].[Advert]  AS [Extent1]
    INNER JOIN [Membership].[Members] AS [Extent2] ON [Extent1].[MemberId] = [Extent2].[MemberId]

Ef-Core Genereated SQL:
SELECT
     [t].[Id]
    ,[t.Member].[Id]
FROM [Advert].[Advert] AS [t]
INNER JOIN [Membership].[Members] AS [t.Member] ON [t].[MemberId] = [t.Member].[MemberId]

You can also take a look this github issue for more detail.
I want to replace
AS [t] with AS [t] WITH (NOLOCK) and
AS [t.Member] with AS [t.Member] WITH (NOLOCK)
Which pattern can I use to do the same in Ef-Core?

A: This interception method doesn't look good to me. A better ways IMO is to hook into EF Core infrastructure to replace the IQuerySqlGenerator service implementation for SqlServer with custom implementation overriding the VisitTable method like this:
public override Expression VisitTable(TableExpression tableExpression)
{
    // base will append schema, table and alias
    var result = base.VisitTable(tableExpression);
    Sql.Append(" WITH (NOLOCK)");
    return result;
}

Hooking is a bit complicated because we need to create and replace the "factory" service in order to be able to replace the sql generator. The full code for all that, along with helper extension method is as follows:
EF Core 7.0:
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.SqlServer.Query.Sql.Internal;
using Microsoft.EntityFrameworkCore.SqlServer.Query.Internal;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
using Microsoft.EntityFrameworkCore.Storage;

namespace Microsoft.EntityFrameworkCore
{
    public static partial class CustomDbContextOptionsBuilderExtensions
    {
        public static DbContextOptionsBuilder UseCustomSqlServerQuerySqlGenerator(this DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.ReplaceService<IQuerySqlGeneratorFactory, CustomSqlServerQuerySqlGeneratorFactory>();
            return optionsBuilder;
        }
    }
}

namespace Microsoft.EntityFrameworkCore.SqlServer.Query.Sql.Internal
{
    class CustomSqlServerQuerySqlGeneratorFactory : IQuerySqlGeneratorFactory
    {
        public CustomSqlServerQuerySqlGeneratorFactory(QuerySqlGeneratorDependencies dependencies, IRelationalTypeMappingSource typeMappingSource)
            => (Dependencies, TypeMappingSource) = (dependencies, typeMappingSource);
        public QuerySqlGeneratorDependencies Dependencies { get; }
        public IRelationalTypeMappingSource TypeMappingSource { get; }
        public QuerySqlGenerator Create() => new CustomSqlServerQuerySqlGenerator(Dependencies, TypeMappingSource);
    }

    public class CustomSqlServerQuerySqlGenerator : SqlServerQuerySqlGenerator
    {
        public CustomSqlServerQuerySqlGenerator(QuerySqlGeneratorDependencies dependencies, IRelationalTypeMappingSource typeMappingSource)
            : base(dependencies, typeMappingSource) { }
        protected override Expression VisitTable(TableExpression tableExpression)
        {
            // base will append schema, table and alias
            var result = base.VisitTable(tableExpression);
            Sql.Append(" WITH (NOLOCK)");
            return result;
        }
    }
}

EF Core 3.x:
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.SqlServer.Query.Sql.Internal;
using Microsoft.EntityFrameworkCore.SqlServer.Query.Internal;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;

namespace Microsoft.EntityFrameworkCore
{
    public static class CustomDbContextOptionsBuilderExtensions
    {
        public static DbContextOptionsBuilder UseCustomSqlServerQuerySqlGenerator(this DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.ReplaceService<IQuerySqlGeneratorFactory, CustomSqlServerQuerySqlGeneratorFactory>();
            return optionsBuilder;
        }
    }
}

namespace Microsoft.EntityFrameworkCore.SqlServer.Query.Sql.Internal
{
    class CustomSqlServerQuerySqlGeneratorFactory : IQuerySqlGeneratorFactory
    {
        public CustomSqlServerQuerySqlGeneratorFactory(QuerySqlGeneratorDependencies dependencies)
            => Dependencies = dependencies;
        public QuerySqlGeneratorDependencies Dependencies { get; }
        public QuerySqlGenerator Create() => new CustomSqlServerQuerySqlGenerator(Dependencies);
    }

    public class CustomSqlServerQuerySqlGenerator : SqlServerQuerySqlGenerator
    {
        public CustomSqlServerQuerySqlGenerator(QuerySqlGeneratorDependencies dependencies)
            : base(dependencies) { }
        protected override Expression VisitTable(TableExpression tableExpression)
        {
            // base will append schema, table and alias
            var result = base.VisitTable(tableExpression);
            Sql.Append(" WITH (NOLOCK)");
            return result;
        }
    }
}

EF Core 2.x:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore.Query.Expressions;
using Microsoft.EntityFrameworkCore.Query.Sql;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.SqlServer.Infrastructure.Internal;
using Microsoft.EntityFrameworkCore.SqlServer.Query.Sql.Internal;

namespace Microsoft.EntityFrameworkCore
{
    public static class CustomDbContextOptionsBuilderExtensions
    {
        public static DbContextOptionsBuilder UseCustomSqlServerQuerySqlGenerator(this DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.ReplaceService<IQuerySqlGeneratorFactory, CustomSqlServerQuerySqlGeneratorFactory>();
            return optionsBuilder;
        }
    }
}

namespace Microsoft.EntityFrameworkCore.SqlServer.Query.Sql.Internal
{
    class CustomSqlServerQuerySqlGeneratorFactory : SqlServerQuerySqlGeneratorFactory
    {
        private readonly ISqlServerOptions sqlServerOptions;
        public CustomSqlServerQuerySqlGeneratorFactory(QuerySqlGeneratorDependencies dependencies, ISqlServerOptions sqlServerOptions)
            : base(dependencies, sqlServerOptions) => this.sqlServerOptions = sqlServerOptions;
        public override IQuerySqlGenerator CreateDefault(SelectExpression selectExpression) =>
            new CustomSqlServerQuerySqlGenerator(Dependencies, selectExpression, sqlServerOptions.RowNumberPagingEnabled);
    }

    public class CustomSqlServerQuerySqlGenerator : SqlServerQuerySqlGenerator
    {
        public CustomSqlServerQuerySqlGenerator(QuerySqlGeneratorDependencies dependencies, SelectExpression selectExpression, bool rowNumberPagingEnabled)
            : base(dependencies, selectExpression, rowNumberPagingEnabled) { }
        public override Expression VisitTable(TableExpression tableExpression)
        {
            // base will append schema, table and alias
            var result = base.VisitTable(tableExpression);
            Sql.Append(" WITH (NOLOCK)");
            return result;
        }
    }
}

Quite a bit code for adding just one meaningful line, but the benefit it that it does it the way EF Core would probably do it in case there is such query option.
Anyway, with the above code all you need is to activate it from your context  OnConfiguring override:
optionsBuilder.UseCustomSqlServerQuerySqlGenerator();

A: The equivalent of the interceptor can be done by hooking into the DiagnosticSource infrastructure.
First create an interceptor:
public class NoLockInterceptor : IObserver<KeyValuePair<string, object>>
{
    public void OnCompleted()
    {
    }

    public void OnError(Exception error)
    {
    }

    public void OnNext(KeyValuePair<string, object> value)
    {
        if (value.Key == RelationalEventId.CommandExecuting.Name)
        {
            var command = ((CommandEventData)value.Value).Command;

            // Do command.CommandText manipulation here
        }
    }
}

Next, create a global listener for EF diagnostics. Something like:
public class EfGlobalListener : IObserver<DiagnosticListener>
{
    private readonly NoLockInterceptor _noLockInterceptor = new NoLockInterceptor();

    public void OnCompleted()
    {
    }

    public void OnError(Exception error)
    {
    }

    public void OnNext(DiagnosticListener listener)
    {
        if (listener.Name == DbLoggerCategory.Name)
        {
            listener.Subscribe(_noLockInterceptor);
        }
    }
}

And register this as part of application startup
DiagnosticListener.AllListeners.Subscribe(new EfGlobalListener());


text:
Q: Efficient way to calculate part of a multivariate normal density I am interested in calculating quantity:

where x_i is a 1xD vector (one out of my N data of dimension D), μ is a DxK matrix and W is a list of K DxD matrices.
This should result in a 1XK vector. I try it for all N and K in the following way that works:
res = zeros(N,K);
for i in 1:N
    for k in 1:K
        res[i,k] = (x_matrix[i,:]-mus_matrix[:,k])'*
                   w_matrix[k]*(x_matrix[i,:]-mus_matrix[:,k])

If I try to vectorize it, using the following:
 res = zeros(N,K);
for i in 1:N
        res[i,:] = (x_matrix[i,:].-mus_matrix)'.*w_matrix.*(x_matrix[i,:].-mus_matrix)

I get the following error:
ERROR: DimensionMismatch("arrays could not be broadcast to a common size")
Stacktrace:
 [1] _bcs1(::Base.OneTo{Int64}, ::Base.OneTo{Int64}) at ./broadcast.jl:70
 [2] _bcs at ./broadcast.jl:63 [inlined]
 [3] broadcast_shape(::Tuple{Base.OneTo{Int64},Base.OneTo{Int64}}, ::Tuple{Base.OneTo{Int64}}, ::Tuple{Base.OneTo{Int64},Base.OneTo{Int64}}, ::Vararg{Tuple{Base.OneTo{Int64},Base.OneTo{Int64}},N} where N) at ./broadcast.jl:57 (repeats 3 times)
 [4] broadcast_indices(::Array{Float64,2}, ::Array{Any,1}, ::Array{Float64,1}, ::Vararg{Any,N} where N) at ./broadcast.jl:53
 [5] broadcast_c(::Function, ::Type{Array}, ::Array{Float64,2}, ::Array{Any,1}, ::Vararg{Any,N} where N) at ./broadcast.jl:311
 [6] broadcast(::Function, ::Array{Float64,2}, ::Array{Any,1}, ::Array{Float64,1}, ::Vararg{Any,N} where N) at ./broadcast.jl:434

Here is an example:
julia> N = 5
5

julia> D=2
2

julia> K = 4
4

julia> W=[]
0-element Array{Any,1}

julia> x = rand(N,D)
5×2 Array{Float64,2}:
 0.576477  0.9575
 0.184454  0.660436
 0.470267  0.729649
 0.648879  0.782561
 0.626453  0.111332

julia> mu = rand(K,D)
4×2 Array{Float64,2}:
 0.989281  0.00126782
 0.659106  0.66136
 0.50843   0.289442
 0.327962  0.523229

julia> for i in 1:K
           push!(W,rand(D,D))
       end

And then run
julia> (x_matrix[i,:]-mus_matrix[:,k])'*
                               w_matrix[k]*(x_matrix[i,:]-mus_matrix[:,k])
34649.850360744866

But with the second code
julia> (x_matrix[i,:].-mus_matrix)'.*w_matrix.*(x_matrix[i,:].-mus_matrix)
ERROR: DimensionMismatch("arrays could not be broadcast to a common size")
Stacktrace:
 [1] _bcs1(::Base.OneTo{Int64}, ::Base.OneTo{Int64}) at ./broadcast.jl:70
 [2] _bcs at ./broadcast.jl:63 [inlined]
 [3] broadcast_shape(::Tuple{Base.OneTo{Int64},Base.OneTo{Int64}}, ::Tuple{Base.OneTo{Int64}}, ::Tuple{Base.OneTo{Int64},Base.OneTo{Int64}}, ::Vararg{Tuple{Base.OneTo{Int64},Base.OneTo{Int64}},N} where N) at ./broadcast.jl:57 (repeats 3 times)
 [4] broadcast_indices(::Array{Float64,2}, ::Array{Any,1}, ::Array{Float64,1}, ::Vararg{Any,N} where N) at ./broadcast.jl:53
 [5] broadcast_c(::Function, ::Type{Array}, ::Array{Float64,2}, ::Array{Any,1}, ::Vararg{Any,N} where N) at ./broadcast.jl:311
 [6] broadcast(::Function, ::Array{Float64,2}, ::Array{Any,1}, ::Array{Float64,1}, ::Vararg{Any,N} where N) at ./broadcast.jl:434

A: TL/DR: optimized variant below, but Einsum looks nicer, IMHO.

Looks like a case for using Einstein summation notation.  In Julia, Einsum.jl can do this:
julia> N = 5
5

julia> D = 3
3

julia> K = 10
10

julia> x = rand(N, D)
5×3 Array{Float64,2}:
 0.587436  0.210529  0.261725
 0.527269  0.457477  0.482939
 0.52726   0.411209  0.138872
 0.89107   0.464789  0.758392
 0.885267  0.931014  0.672959

julia> μ = rand(D, K)
3×10 Array{Float64,2}:
 0.280792   0.265066   0.81437   0.503377  0.0717916  …  0.275872  0.609961   0.0820088  0.0042564
 0.0177643  0.0959438  0.563948  0.332433  0.088527      0.691971  0.0296638  0.604488   0.956057
 0.668128   0.444816   0.74203   0.518232  0.48689       0.465067  0.117469   0.729514   0.109973

julia> W = rand(K, D, D)
10×3×3 Array{Float64,3}:
[:, :, 1] =
 0.320861   0.662103  0.219234
 0.780944   0.769377  0.566203
 0.466207   0.428527  0.330901
 0.15534    0.035435  0.346737
 0.810676   0.328116  0.469505
 0.676575   0.668204  0.285334
 0.455551   0.211295  0.85295
 0.229995   0.741487  0.783361
 0.0937583  0.401419  0.47032
 0.956335   0.434213  0.967791

[:, :, 2] =
 0.275903   0.130298   0.184485
 0.941648   0.940107   0.439454
 0.425292   0.252654   0.797115
 0.0203406  0.594075   0.484809
 0.164309   0.941597   0.455314
 0.73628    0.109502   0.920664
 0.906305   0.177235   0.540193
 0.360038   0.0486971  0.20626
 0.914357   0.699901   0.295872
 0.284143   0.659117   0.291479

[:, :, 3] =
 0.138311   0.921371  0.353719
 0.345247   0.70865   0.246736
 0.361364   0.636543  0.343837
 0.752149   0.581561  0.346399
 0.705888   0.24765   0.703952
 0.992327   0.369668  0.109407
 0.341624   0.223715  0.970667
 0.762169   0.94248   0.917569
 0.0367128  0.589345  0.121106
 0.826602   0.692111  0.229499

julia> using Einsum

julia> @einsum r[n,k] := (x[n,i] - μ[i,k]) * W[k,i,j] * (x[n,j] - μ[j,k])

julia> r
5×10 Array{Float64,2}:
  0.0176889  0.087092   0.522184    0.0417967   …  -0.0430999   0.041266   -0.0596579  0.432076
  0.0521066  0.364059   0.181515    0.00434307     -0.0248712   0.226976   -0.0686294  0.437169
 -0.0472136  0.127803   0.458812    0.0119074       0.0391649  -0.0190299  -0.0585371  0.264379
  0.468634   1.16498   -0.00263205  0.192809        0.273537    1.13787    -0.0653081  1.41321
  0.749655   2.20266    0.0205068   0.420249        0.573358    1.42499     0.441232   1.67574

Which @macroexpands to essentially the following loops (plus preparation and bounds checking):
begin
    local k
    for k = 1:size(μ, 2)
        begin
            local n
            for n = 1:size(x, 1)
                begin
                    local s = zero(T)
                    begin
                        local j
                        for j = 1:size(W, 3)
                            begin
                                local i
                                for i = 1:size(x, 2)
                                    s += (x[n, i] - μ[i, k]) * W[k, i, j] * (x[n, j] - μ[j, k])
                                end
                            end
                        end
                    end
                    r[n, k] = s
                end
            end
        end
    end
end

Now, to find something more performant, I compared a couple of variants using BenchmarkTools.jl. You can see the full code and results on my laptop here. It shows that the Einsum variant already is in fact better than the original:
# Original:
#   memory estimate:  1017.73 MiB
#   allocs estimate:  3429967
#   median time:      361.982 ms (15.94% GC)

# Einsum:
#   memory estimate:  2.64 MiB
#   allocs estimate:  76
#   median time:      127.536 ms (0.00% GC)

By far the most efficient and least allocating variant is the following, which requires x = x' and W = permutedims(W, [2, 3, 1]) (assuming you can change your representation easily):
function test_optimized!(res, x, μ, W)
    z = zero(eltype(x))

    for k = 1:size(μ, 1)
        for n = 1:size(x, 1)
            res[n, k] = z

            for i = 1:size(W, 1)
                for j = 1:size(W, 2)
                    @inbounds res[n, k] += (x[i, n] - μ[i, k]) * W[i, j, k] * (x[j, n] - μ[j, k])
                end
            end
        end
    end
end

function test_optimized(x, μ, W)
    res = zeros(N, K)
    test_optimized!(res, x, μ, W)
    res
end

This brings us down to
#   memory estimate:  2.63 MiB
#   allocs estimate:  2
#   median time:      521.215 μs (0.00% GC)

It uses a couple of "tricks" that can be found in the docs: filling a preallocated matrix in a separate method, accessing strides in column-major order, and using @inbounds (although that only improves things at the order of a microsecond).

There is also TensorOperations.jl, which I think does more intelligent things under the hood, but it fail on this:
julia> @tensor r[n,k] := (x[n,i] - μ[i,k]) * W[k,i,j] * (x[n,j] - μ[j,k])
ERROR: TensorOperations.IndexError{String}("invalid index specification: (:n, :i) to (:i, :k)")
Stacktrace:
 [1] add_indices(::Tuple{Symbol,Symbol}, ::Tuple{Symbol,Symbol}) at /home/philipp/.julia/v0.6/TensorOperations/src/implementation/indices.jl:22
 [2] + at /home/philipp/.julia/v0.6/TensorOperations/src/indexnotation/sum.jl:40 [inlined]
 [3] -(::TensorOperations.IndexedObject{(:n, :i),:N,Array{Float64,2},Int64}, ::TensorOperations.IndexedObject{(:i, :k),:N,Array{Float64,2},Int64}) at /home/philipp/.julia/v0.6/TensorOperations/src/indexnotation/sum.jl:44

I guess that's deliberate and has to do with efficiency, see this issue.


text:
Q: How to copy array to structure with fixed array? What is the best way for Copying 'mydata' to 'sample_a'?
I expect to get 4 in sample_a.data_array[ 1 ]. That value is p[ 9 ].
I plan to use this for TCP/UDP packet communication.
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct SampleA
{
    public int data1;
    public int data2;
    public unsafe fixed char data_array[3];
    public int data3;
}

static void Main(string[] args)
{
    Console.WriteLine("Hello World!");

    short bytesize = 15;
    byte[] mydata = new byte[bytesize];
    unsafe
    {
        fixed (byte* p = mydata)
        {
            // data1
            p[0] = 1;
            // data2
            p[4] = 2;
            // data_array
            p[8] = 3;
            p[9] = 4;
            p[10] = 5;
            // data3
            p[11] = 6;
        }

        // Copy 'mydata' to 'sample_a'
        IntPtr intptr = Marshal.AllocHGlobal(bytesize);
        Marshal.Copy(mydata, 0, intptr, bytesize);
        SampleA sample_a = (SampleA)Marshal.PtrToStructure(intptr, typeof(SampleA));
        Marshal.FreeHGlobal(intptr);

        // I want to get 4 in a1
        int a1 = (int)sample_a.data_array[1];
    }
}

A: You can avoid a lot of work here with spans:

// note: size is 18; if you intended 15 - perhaps change char=>byte
byte[] mydata = new byte[Unsafe.SizeOf<SampleA>()];
// alternative: Span<byte> mydata = stackalloc byte[Unsafe.SizeOf<SampleA>()];

// ..TODO: populate mydata

// cast it out
var sample_a = MemoryMarshal.Cast<byte, SampleA>(mydata)[0];

You can also use Unsafe.As, but this is IMO not a good idea as it won't detect incorrect memory conditions as well:
var sample_a = Unsafe.As<byte, SampleA>(ref mydata[0]);

A: Your problem is that C#'s chars are 2 bytes wide, and you're treating them as if they're 1 byte wide.
One fix is to explicitly declare them as byte:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct SampleA
{
    public int data1;
    public int data2;
    public unsafe fixed byte data_array[3];
    public int data3;
}

It's more common to embed arrays using UnmanagedType.ByValArray:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct SampleA
{
    public int data1;
    public int data2;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
    public byte[] data_array;
    public int data3;
}

If you want to use char, you can tell the marshaller that each should be marshalled as a U8:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct SampleA
{
    public int data1;
    public int data2;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3, ArraySubType = UnmanagedType.U8)]
    public char[] data_array;
    public int data3;
}

You can also tell the marshaller that you're using ANSI strings, which has the same effect
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
struct SampleA
{
    public int data1;
    public int data2;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
    public char[] data_array;
    public int data3;
}