text:
Q: Bitmap, check if orthogonal path is closed An 2d array of bits are given.
var map1 = [[0,0,0,0,0,0,0,0],
            [0,0,0,0,1,0,0,0],
            [0,0,1,1,1,1,1,0],
            [0,0,1,0,0,0,1,0],
            [0,0,1,1,0,0,1,0],
            [0,0,1,0,0,0,1,0],
            [0,0,1,1,1,1,1,0],
            [0,0,0,0,0,0,0,0]];

How I can programmaticaly check if some of the "ones" are forming a closed path ?
http://jsfiddle.net/RvN3k/
The two left bitmaps contains closed paths, the upper one is obvious, the lower one are simply a closed path with nothing inside.
The two right bitmaps doesn't contains closed paths, in the upper example one bit is missing, in the lower example the one diagonal pixel doesn't count, orthogonal paths only.

A: Find a cell that holds a 1, then "flood" from there on. By this I mean: use a second map, all initially set to 0. When you encounter the first 1, set the cell in the second map to 1. Now check all adjacent cells, setting the cell in the second map to 1 if that in the original map is also 1. Once you try to set a cell that was already 1, you know you have encountered a closed path; do not check that cell again or you'll get an infinite loop.
EDIT: if you want a complete list of all cells connected to one cell by closed paths, juts add every cell you encounter during the "flooding" to a list that initially only holds the starting cell. If at some point you don't find another cell to flood, there is no closed path and you can throw away the list. Depending on whether you want the little "stubs" in your linked bitmaps to be considered part of the path or not, you'll have to do some branching, introducing new lists for each branch, merging them if they intersect.

A: I've forked your fiddle and added a method findCycle().
var fill = function(map, x, y) {
    if (Math.min(x,y) >= 0 && Math.max(x,y) < mapSize && map[x][y] == 0) {
        map[x][y] = -1;
        for (var dx = -1; dx <=1; dx +=1) {
            for (var dy=-1; dy<=1; dy += 1) {
                fill(map, x+dx, y+dy);
            }
        }
    }
}

function detect(map) {
    for(var x = 0; x + 1 < mapSize; x++){
       for(var y = 0; y + 1 < mapSize; y++){
           if (map[x][y] == 0) {
               map[x][y] = -2;
               return;
           }
           else if (map[x][y]== 1 && map[x+1][y]==1 && map[x][y+1]== 1 && map[x+1][y+1]==1) {
               map[x][y] = -2;
               return;
           }
       }
    }
}

function findCycle(mapData) {
    for(var x = 0; x < mapSize; x++){
       for(var y = 0; y < mapSize; y++){
           if (mapData[x][y] == 0) {
               fill(mapData, x, y);
                detect(mapData);
               return;
           }
       }
    }
}

It finds the first 0. Recursively fills all adjacent 0's with "-1". Then searches for any still existing 0's that couldn't be reached from the initial 0. (while at the same time searching for a square of four "1" (red) squares.
http://jsfiddle.net/bn6pa/1/
A black square is drawn at the first point where it finds a cycle.

A: How about this:
for each cell that's set to 1
    set that cell to -1
    recursively look for neighbouring cells set to 1, and set them to -1
        if you find a neighbouring cell that is already set to -1, loop found
    clean-up (set all cells that are set to -1 to 0, they are no longer relevant)

This ought to run close to O(N).
Here, I've implemented this into a fiddle, check it out here. You'll notice that the 4th example is odd: I haven't worked out the kinks because your problem definition doesn't state if you wanted the largest possible loop or any. In fact, you just wanted to know if there was a loop, which is known the moment you hit a light blue pixel.


text:
Q: child div height of 100% being ignored I'm using peter's excellent example for a 100% height div with a sticky footer (HERE). I've omitted the footer parts a i'm not using it.
However, whenever i use a child div and try to do the same thing it doesn't work. I want a child div to also take 100% of its parent's height. Here is CSS:

and here is my HTML code:

CSS layout: 100% height with header and footer

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eget massa dolor, rhoncus tempor nunc. Donec tempor odio eget purus vehicula auctor.

    Aenean quam mauris, iaculis non aliquet quis, facilisis sed turpis. Cras id erat velit, nec bibendum erat. Vivamus feugiat purus vitae velit dictum in vestibulum ante tristique. Vestibulum ut massa vel justo eleifend consectetur eget ut nisi. Phasellus ut diam nulla. Suspendisse potenti. Praesent blandit gravida facilisis. Donec elementum faucibus gravida. Nullam nec enim velit, ac scelerisque justo. Pellentesque lacus metus, adipiscing nec congue a, volutpat sollicitudin eros. Donec tortor leo, tempor non viverra at, molestie sed dui. Nullam ipsum purus, tempus elementum tincidunt id, iaculis at lectus. Vestibulum viverra mi in mauris ultrices sollicitudin

 this sub div not stretching to 100%;
 this sub div not stretching to 100%;
 this sub div not stretching to 100%;
 this sub div not stretching to 100%;
 this sub div not stretching to 100%;

A: You can only apply min-height:100% to the first element of the body.
Put the header inside the content div or create a min-height:100% wrapper div.

A: Try this code then :
html,body {
    margin:0;
    padding:0;
    height:100%; /* needed for container min-height */
    background:gray ;
    font-family:arial,sans-serif;
    font-size:small;
    color:#666;
}

div#container {
    position:relative; /* needed for footer positioning*/
    margin:0 auto; /* center, not in IE5 */
    width:750px;
    background:#f0f0f0;

    height:auto !important; /* real browsers */
    height:100%; /* IE6: treaded as min-height*/

    min-height:100%; /* real browsers */
}

div#header {
    padding:1em;
    background:#ddd url("../csslayout.gif") 98% 10px no-repeat;
    border-bottom:6px double gray;
}

div#content {
    padding:1em 1em 5em; /* bottom padding for footer */
    position:relative; /* needed for footer positioning*/
    margin:0 auto; /* center, not in IE5 */

    height:auto !important; /* real browsers */
    height:100%; /* IE6: treaded as min-height*/

    min-height:100%; /* real browsers */
}
div#content_subdiv{
    padding:1em 1em 5em; /* bottom padding for footer */
    background:#999;
   color:#fff;    }

CSS layout: 100% height with header and footer

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eget massa dolor, rhoncus tempor nunc. Donec tempor odio eget purus vehicula auctor.

Aenean quam mauris, iaculis non aliquet quis, facilisis sed turpis. Cras id erat velit, nec bibendum erat. Vivamus feugiat purus vitae velit dictum in vestibulum ante tristique. Vestibulum ut massa vel justo eleifend consectetur eget ut nisi. Phasellus ut diam nulla. Suspendisse potenti. Praesent blandit gravida facilisis. Donec elementum faucibus gravida. Nullam nec enim velit, ac scelerisque justo. Pellentesque lacus metus, adipiscing nec congue a, volutpat sollicitudin eros. Donec tortor leo, tempor non viverra at, molestie sed dui. Nullam ipsum purus, tempus elementum tincidunt id, iaculis at lectus. Vestibulum viverra mi in mauris ultrices sollicitudin

 this sub div not stretching to 100%;
 this sub div not stretching to 100%;
 this sub div not stretching to 100%;
 this sub div not stretching to 100%;
 this sub div not stretching to 100%;

redpajama_set_name: RedPajamaStackExchange


text:
Q: fatal: Access denied for user golden by PAM account configuration [preauth] I am trying to setup passwordless ssh from "machineA" to "machineB" but somehow it's not working and I am getting below error. I have already added public key of jenkins user from "machineA" into "authorized_keys" file in "machineB" golden user..
jenkins@machineA:~$ ssh golden@machineB
Connection to machineB closed by remote host.
Connection to machineB closed.

And I logged into this "machineB" and I checked "auth.log" file and I see below error:
Feb 13 14:29:49 machineB sshd[22145]: rexec line 90: Deprecated option RhostsAuthentication
Feb 13 14:29:50 machineB sshd[22145]: pam_access(sshd:account): access denied for user `golden' from `machineA'
Feb 13 14:29:50 machineB sshd[22145]: fatal: Access denied for user golden by PAM account configuration [preauth]

And below is how my permission thing is setup on machineB:
golden@machineB:~$ ls -lrtha
total 56K
-rw-------  1 golden golden  675 Oct  6 21:39 .profile
-rw-------  1 golden golden 3.6K Oct  6 21:39 .bashrc
-rw-------  1 golden golden  220 Oct  6 21:39 .bash_logout
drwx------  3 golden golden 4.0K Oct  7 12:03 .config
drwxr-xr-x 13 root     root     4.0K Oct 19 18:41 ..
-rw-------  1 golden golden  12K Feb 13 13:54 .bash_history
-rw-------  1 golden golden  11K Feb 13 14:10 .viminfo
drwx------  2 golden golden 4.0K Feb 13 14:10 .ssh
drwx------  4 golden golden 4.0K Feb 13 14:10 .

golden@machineB:~$ ls -lrtha .ssh/
total 24K
-rw------- 1 golden golden 1.7K Oct 19 22:46 id_rsa
-rw-r--r-- 1 golden golden  381 Oct 19 22:46 id_rsa.pub
-rw-r--r-- 1 golden golden 2.2K Oct 19 22:48 known_hosts
-rw-r--r-- 1 golden golden 1.2K Feb 13 14:10 authorized_keys
drwx------ 4 golden golden 4.0K Feb 13 14:10 ..
drwx------ 2 golden golden 4.0K Feb 13 14:10 .

And this is my /etc/security/access.conf file on machineB:
+:ALL:LOCAL
+:root:ALL
+:tom:ALL
# generated by puppet
# beginldap
+:@golden:ALL
+:@opers:ALL
+:@unixcore:ALL
+:stack:ALL
+:comet:ALL
# endldap
-:ALL:ALL

I am using below permission:
chmod 700 ~/.ssh
chmod 644 ~/.ssh/authorized_keys

What is wrong I am doing here?


text:
Q: select inside another select doesn't show everything I'm trying to select data from my database and images as well.
Both work separately but if I paste the image select inside the while loop, it shows only one row of the database.
This is the first select:
$example = 5;
$stmt = $conn->prepare("SELECT id, name, etc.. FROM cards WHERE example = ?");
$stmt->bind_param("i", $example);
$stmt->execute();
$result = $stmt->get_result();
while ($record = mysqli_fetch_assoc($result)) {
?>

//using the records here like this:

<?php echo $record['job']; ?>

//more records here

<?php
$sql = "SELECT id, image FROM cardimages WHERE cardid = ?";
$stmt = $conn->prepare($sql);
$id = $record['id'];
$stmt->bind_param('i', $id);
$stmt->execute();
$result = $stmt->get_result();

if (mysqli_fetch_assoc($result) != null) {
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$image = $row['image'];
$data[] = $row;
?>

Below is where I show the results:
<div class="modal fade bd-example-modal-lg show" id="myModal<?php echo $row["id"]; ?>" role="dialog">

<button type="button" class="close" data-dismiss="modal">
×
</button>

<?php
echo "";
?>

Ending the while loop:

}
} else {
echo '
No image availabe
';
}
}
$conn->close();
?>

A: As was pointed out in a comment by @dharman, the variable $result is getting overwritten inside the loop.
$result = $stmt->get_result();

ie.
$stmt = $conn->prepare("SELECT id, name, etc.. FROM cards WHERE example = ?");
$stmt->bind_param("i", $example);
$stmt->execute();
$result = $stmt->get_result();

and then later in the code:
$sql = "SELECT id, image FROM cardimages WHERE cardid = ?";
$stmt = $conn->prepare($sql);
$id = $record['id'];
$stmt->bind_param('i', $id);
$stmt->execute();
$result = $stmt->get_result();

If you store your result in the loop as another variable then both loops should run properly.


text:
Q: How to get the best indoor gps coordinates in objective c How do I get the best Accuracy Indoor GPS Co-ordinates in device? Whenever I am launching the application in same location, the GPS value gets different different coordinates values. If, I will get the Proper coordinates, then only I can calculate the actual distance between the two coordinates and navigate a user.
Here my sample code:
_locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
_locationManager.distanceFilter = kCLHeadingFilterNone;
[self.locationManager startUpdatingLocation];

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
  userLat = newLocation.coordinate.latitude;
  userLon = newLocation.coordinate.longitude;
 }

A: @batMan007 this is the best result you can get from the gps. You might be able to get a more accurate coordinate by connecting to a wifi network. Besides, if you are very particular about the distance in terms of meters, perhaps iBeacon is your only option.


text:
Q: Django: How to destroy user session after a password reset/change? i've recently implemented a simple change password view in my django project. The thing is that the old session should be destroyed for security reasons. What's the best way of doing this without asking the user to log in again.
I think i could just logout/login him/her, something like this:
from django.contrib.auth import login as auth_login
from django.contrib.auth import logout as auth_logout

@login_required
def change_password(request):
  # My stuff
  request.user.set_password(new_password)
  request.user.save()
  # I need this:
  logout(request)
  login(request,request.user)

But i think this is not the best idea. What do you think?
Is there another way to do this?
Am I missing something? (I mean, is this secure)

A: Take a look at this app https://github.com/atugushev/django-password-session.
This package makes invalidated all sessions (except a current session) after change a password.
Also this feature finally was implemented in Django 1.7. See: https://docs.djangoproject.com/en/dev/topics/auth/default/#session-invalidation-on-password-change

A: I just found out that this is now a built-in feature of Django, and has been since 1.7:
https://docs.djangoproject.com/en/1.7/topics/auth/default/#session-invalidation-on-password-change
Essentially, all sessions now include a hash of the users' password, so if the user ever changes their password, all their existing sessions are automatically invalidated.
So, the short answer to your question is: upgrade django.
One possibly undesirable side effect of this change is that, by default, a user ends up having to log in again as soon as they change their password.  So you probably actually want the current user session to stay logged in.  See the docs already linked, Django's built-in views for password change do that for you default, or you can manually call a function called update_session_auth_hash

A: django clears the session on logout so you will be fine:
https://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.logout

When you call logout(), the session data for the current request is completely cleaned out. All existing data is removed. This is to prevent another person from using the same Web browser to log in and have access to the previous user's session data.

A: I don't understand whats are these security reasons that forces to reset session. But, the way is:
@login_required
def change_password(request):
  request.user.set_password(new_password)
  request.user.save()
  username = request.user.username
  logout(request)
  user = authenticate(username=username, password=new_password) #<-- here!!
  if user is not None:
      login(request,user)
  else:
      #raise your exception

you should authenticate before login. Quoting doc:

Calling authenticate() first When you're manually logging a user in,
  you must call authenticate() before you call login(). authenticate()
  sets an attribute on the User noting which authentication backend
  successfully authenticated that user (see the backends documentation
  for details), and this information is needed later during the login
  process.


text:
Q: WSO2 EI - retry, suspend - still wait for TimeOut can anybody explain me how to enable correct retry?
I use only Integration Studio Editor just downloaded from WSO2 site.
I have code with URL https://api.github.com/user that return 401 and JSON (see logs). So why WSO2 wait for TimeOut that is set in configuratipon file (I have changes it to 30 seconds)? Shouldn't retry immadietly after getting 401 or after time in <timeout><duration>?
    <?xml version="1.0" encoding="UTF-8"?>
<proxy name="HelloWorld" startOnLoad="true" transports="http https" xmlns="http://ws.apache.org/ns/synapse">
    <target>
        <inSequence>
            <property name="DISABLE_CHUNKING" scope="axis2" type="STRING" value="true"/>
            <property action="remove" name="NO_ENTITY_BODY" scope="axis2"/>
            <property name="NO_KEEPALIVE" scope="axis2" type="STRING" value="true"/>
            <send>
                <endpoint name="github">
                    <address format="get" optimize="mtom" uri="https://api.github.com/user">
                        <timeout>
                            <duration>5</duration>
                            <responseAction>fault</responseAction>
                        </timeout>
                        <suspendOnFailure>
                            <initialDuration>1000</initialDuration>
                            <progressionFactor>2.0</progressionFactor>
                        </suspendOnFailure>
                        <markForSuspension>
                            <retriesBeforeSuspension>3</retriesBeforeSuspension>
                            <retryDelay>1000</retryDelay>
                        </markForSuspension>
                    </address>
                </endpoint>
            </send>
        </inSequence>
        <outSequence>
            <log level="full"/>
            <log level="custom">
                <property expression="$axis2:HTTP_SC" name="###### HTTP Status #######" xmlns:ns="http://org.apache.synapse/xsd"/>
            </log>
            <respond/>
        </outSequence>
        <faultSequence/>
    </target>
</proxy>

WSO2 logs:
    [2020-06-14 14:51:57,811]  INFO {org.apache.synapse.transport.passthru.SourceHandler} - Writer null when calling informWriterError
[2020-06-14 14:51:57,812]  WARN {org.apache.synapse.transport.passthru.SourceHandler} - Connection time out after request is read: http-incoming-4 Socket Timeout : 30000 Remote Address : /127.0.0.1:55124
[2020-06-14 14:51:58,149]  INFO {org.apache.synapse.endpoints.EndpointContext} - Endpoint : github with address https://api.github.com/user currently TIMEOUT will now be marked active since it processed its last message
[2020-06-14 14:51:58,150]  INFO {org.apache.synapse.mediators.builtin.LogMediator} - To: http://www.w3.org/2005/08/addressing/anonymous, WSAction: , SOAPAction: , MessageID: urn:uuid:76137204-8644-4e3c-a1ba-4e1f011382ea, Direction: response, Payload: {"message":"Requires authentication","documentation_url":"https://developer.github.com/v3/users/#get-the-authenticated-user"}
[2020-06-14 14:51:58,151]  INFO {org.apache.synapse.mediators.builtin.LogMediator} - ###### HTTP Status ####### = 401
[2020-06-14 14:52:27,843]  INFO {org.apache.synapse.transport.passthru.SourceHandler} - Writer null when calling informWriterError
[2020-06-14 14:52:27,844]  WARN {org.apache.synapse.transport.passthru.SourceHandler} - Connection time out after request is read: http-incoming-5 Socket Timeout : 30000 Remote Address : /127.0.0.1:55145
[2020-06-14 14:52:28,341]  INFO {org.apache.synapse.mediators.builtin.LogMediator} - To: http://www.w3.org/2005/08/addressing/anonymous, WSAction: , SOAPAction: , MessageID: urn:uuid:35dda6ba-faae-47bd-8180-d130a1604877, Direction: response, Payload: {"message":"Requires authentication","documentation_url":"https://developer.github.com/v3/users/#get-the-authenticated-user"}
[2020-06-14 14:52:28,343]  INFO {org.apache.synapse.mediators.builtin.LogMediator} - ###### HTTP Status ####### = 401
[2020-06-14 14:52:57,868]  INFO {org.apache.synapse.transport.passthru.SourceHandler} - Writer null when calling informWriterError
[2020-06-14 14:52:57,869]  WARN {org.apache.synapse.transport.passthru.SourceHandler} - Connection time out after request is read: http-incoming-6 Socket Timeout : 30000 Remote Address : /127.0.0.1:55164

How to make it working?

A: Can you try like below with the address endpoint instead of http.
<endpoint>
<address uri="http://localhost:8000">
  <suspendOnFailure>
     <initialDuration>1000</initialDuration>
     <progressionFactor>2.0</progressionFactor>
  </suspendOnFailure>
  <markForSuspension>
     <retriesBeforeSuspension>3</retriesBeforeSuspension>
     <retryDelay>1000</retryDelay>
  </markForSuspension>
  <timeout>
     <duration>6000</duration>
     <responseAction>fault</responseAction>
  </timeout>
</address></endpoint>


text:
Q: Alea.cubase gpu programming in F# While running one piece of code using Alea.cuBase I am getting a type initialization exception
let worker = Engine.workers.DefaultWorker

System.TypeInitializationException was unhandled
  Message: The type initializer for 'Worker' threw an exception.

I am using

*

*visual studio 2012

*.Net frame work 4.0

*F# 3.1

Another piece of code I tried and got the same error at,
useprogram = template |> Compiler.loadWorker.Default

I started with trial version of Alea.cuBase 1.3.914.
Guide me how to fix this..

A: Problem got resolved.
My pc was having graphics card quadro fx 1800.
Because Alea cuBase support fermi or higher architecture.
When I tried with k4000 I could run the same program.


text:
Q: Unistall apache 2.4 + php 7.1 Ребят, нужна помощь, скажите какими командами или как вообще возможно перманентно удалить Apache 2.4  и PHP 7.1 с MAC OS High Sierra?

A: Примерно так:

*

*Получить весь лист всех установленных пакетов через brew
brew list

*Либо если знаете название пакета, то:
brew list mtr

*Удалить пакет:
brew uninstall mtr
Uninstalling /usr/local/Cellar/mtr/0.92... (12 files, 181.9KB)

Для вас это должны быть команды:
brew uninstall apache2
brew uninstall php@7.0
brew uninstall php@7.1


text:
Q: Why is source code text-only? All my life I have used text-based source code editors.
I can't believe we're all still doing this!  There must be a better way.
I don't mean that I want to use a WYSIWYG-editor, I usually hate those, since they don't exactly produce what you want.
No, I mean a text-based source-code editor that is greatly enhanced by the following extra's:

*

*include pictures, excel-data, pdf's, etc. INSIDE the source code, to explain certain data-structures, to include (mockup) screenshots of what the client actually wants, etc. Of course with the option to minify/hide/fold these things.
(the advantage of this as opposed to separate file, is clear, you want to store this information together WITH your source code)

*comments not as text, but more like post-it-like items, that are resizable, moveable, clickable, etc.

*Class definitions and instances not as text, but as clickable object-boxes, maybe even with an icon to quickly see in the source code which class an object is).

*operators that are now 2 characters as 1 symbol. For example:  -> in PHP  as a real arrow.

*possibility to use colors, different text sizes and other layout tools inside the source code   (i'm not talking about automatic syntax coloring, sometimes it can be handy to emphasize certain blocks of text by using a layout tools as you do in Word)

*include separate files inside a different file, but still be able to edit/view those as if it were 1 file   (comparable to Adobe Illustrator where you can place separate files inside a document, but still be able to edit them).
I know a lot of hardcore programmers are appalled by these kind of things, but they can still edit the way they want, I just think it would be neat to have those extra possibilities. Why on earth is source code STILL only text, where so many other types of documents are much more complex?
Does anyone know of any source code editor that has some of these features??

A: There have been attempts to make visual development tools in the past - but the problem is that computers need very precise statements in a formal language in order to fully meet a specific requirement of a user.
In fact, if you write down a requirement and then read it with different emphasis you will see that it is very hard to write an unambiguous statement.
This example is from Software Craftsmanship: The New Imperative by Pete McBreen (978-0201733860).

Mary had a little lamb - the lamb belongs to Mary and not anybody else
Mary had a little lamb - she no longer has it
Mary had a little lamb - there was only one
Mary had a little lamb - it was exceptionally small
Mary had a little lamb - everybody else ate chicken

This is why we need a language that requires us to be more explicit that natural language requires and why visual aids to development are not useful.
For example, being to annotate code with a "post-it" is less useful that writing clean readable code that is easy for other people to read. In fact, sharing code with other developers means changing text size and colour would require other developers to suffer your personal style, which is not cool.
Some of the ideas you mention are actually available now. Being able to view a class diagram and navigate to the code by clicking on the class "boxes" is a feature of Visual Studio - as is organisation of multiple files behind a single file in the tree view.

A: This is just my opinion of course, so take it with a grain of salt. I think the main reason that something like this hasn't been done is because the compilers still expect plain text. If you have a source code editor like you mention, it's going to be just a front end - the actual source files will still be plain text. The problem that you run into is that each source editor that takes this approach may have a different way of implementing certain features, so what appears to be identical source will in fact be completely different in the plain text.
When you compile that source, you'll be in a world of trouble. It might be fine for the example you mentioned, PHP, but for the type of things that I work on (real-time C++ applications for industry) I need exact low level control over the source so that I know exactly how my code is being compiled. This would never work for the vast majority of programmers, which is why it's never been done. The target audience is small at best.

A: What you are describing sounds a lot like https://en.wikipedia.org/wiki/Literate_programming to me.
There has been some progress on this and some of this is useful right now
Fonts with ligatures (and editors with support for them)

(https://github.com/tonsky/FiraCode in https://www.jetbrains.com/idea/)
Jupyter Notebook, though you cannot easily "tangle" an executable or library for end-users out of it.

(http://jupyter.org/)
Fortress (programming language from Sun)
Fortress supported source code in utf-8 and encouraged its use, esp. for user-defined operators. They experimented with typesetting the source in editors (since most of it was computational science, so lots of math).
Elastic tabstops

(http://nickgravgaard.com/elastic-tabstops/)
Conclusion
There is many efforts like that, actually. There is not yet anything like UX movement for developer tooling, but I have hope it will gather momentum in the coming years.


text:
Q: Selenium Python - How to handle a random pop up? For the past few months, I have been using Selenium to automate a very boring but essential part of my job which involves uploading forms.
Recently, the site has implemented a feed back survey which randomly pops up and switches the driver to a new frame. I have written the code which can handle this pop up and switch back to my default frame however the issue is with the randomness.
Is there a way to run my popup handling code as soon the exception generated by the wrong frame is thrown?
I could encase my whole script in a try and except block but how do I direct the script to pick back up from where it left off?
Any advice is much appreciated!

A: I've encountered this on sites that I work on also. What I've found on our site is that it's not really random, it's on a timer. So basically the way it works is a customer comes to the site. If they haven't been prompted to sign up for X, then they get a popup. If they signed up or dismissed the popup, a cookie is written tracking that they already got the message. You want to find that tracking cookie and recreate it to prevent the popups.
What I did was find that cookie, recreate it on an error page on the site domain (some made up page like example.com/some404page), and then start the script as normal. It completely prevents the popup from occurring.
To find out if this is your case, navigate to the home page (or whatever is appropriate) and just wait for the popup. That will give you a sense of how long the timer is. Close the popup and reload the page. If the popup doesn't occur again, then I'm guessing it's the same mechanic.
To find the cookie, clear cookies in your browser and open your site again. (Don't close the popup yet). I use Chrome so I'll describe how to do it. The general approach should work in other browsers but the specific steps and command names may vary.

*

*Open up the devtools (F12)

*Navigate to the Application tab and find Cookies (left panel)

*Expand Cookies and click on the domain of the site you are working on. There may be a lot of cookies in there from other sites, depending on your site.

*Click the Clear All button to clear all the cookies.

*Close the popup and watch for cookies to be created. Hopefully you will see one or just a few cookies created.

*Note the name of the cookies and delete them one at a time and reload the page and wait the 15s (or whatever) and see if the popup occurs.

Once the popup appears, you know that the last cookie you deleted is the one you need to recreate. You can now write a quick function that creates the cookie using Selenium by navigating to the dummy error page, example.com/some404page, and create the cookie. Call that function at the start of your script. Profit.

A: I have encountered a similar kind of situation.
My recommendation to you is speak to your front end devs or the company which provides the feedback survey and ask them for a script to disable the pop-ups for a browser session that you run.
Then, execute the script using selenium library(like JavascriptExecutor) as soon as you open the web page so that you do not see the random occuring pop-ups.


text:
Q: Speed up working with big arrays of string in c# This method takes the most frequent words from string array.
It works very slowly for big arrays (like 190.000 milliseconds for 70.000 strings).
I've measured (using Stopwatch()) that its first part is the slowest one:
public static List<WordDouble> MostFrequentWords(double count, string[] words)
    {
        var wordsAndNumbers = new List<WordDouble>();

        foreach (var word in words)
        {
            if (wordsAndNumbers.Exists(e => e.Word == word.ToLower()))
                wordsAndNumbers[wordsAndNumbers.FindIndex(e => e.Word == word.ToLower())].Count++;
            else
            {
                var addWord = new WordDouble();
                addWord.Word = word.ToLower();
                addWord.Count = 1;
                wordsAndNumbers.Add(addWord);
            }
         }

/*method goes on, other parts work fast and do not need improvement */
...
return something;
}

public class WordDouble
    {
        public string Word;
        public double Count;
    }

How can I improve performance of this method?

A: Checking for an item using Exists in a list is an O(n) operation, while checking for an item in a dictionary is an O(1) operation.
This runs in a fraction of the time (actually in about 1/2200 of the time):
Dictionary<string, int> wordsAndNumbers = new Dictionary<string, int>();

foreach (string word in words) {
  if (wordsAndNumbers.ContainsKey(word.ToLower())) {
    wordsAndNumbers[word.ToLower()]++;
  } else {
    wordsAndNumbers.Add(word.ToLower(), 1);
  }
 }

Here is the result of a test run with 70000 strings, for the original code, my code, and Console's code, respectively:
00:01:21.0804944
00:00:00.0360415
00:00:00.1060375

You can even speed it up a little more by doing ToLower only once in the loop:
var wordsAndNumbers = new Dictionary<string, int>();

foreach (var word in words) {
  string s = word.ToLower();
  if (wordsAndNumbers.ContainsKey(s)) {
    wordsAndNumbers[s]++;
  } else {
    wordsAndNumbers.Add(s, 1);
  }
}

Test run:
00:00:00.0235761

A: First of all why do you use a double to count words?
Use a long Dictionary and never cast to lower just for comparison.
Dictionary<string,long> wordsAndNumbers = new
    Dictionary<string,long>(StringComparer.OrdinalIgnoreCase);

foreach(var word in words)
{
    if (!wordsAndNumbers.ContainsKey(word))
        wordsAndNumbers[word] = 1;
    else
        wordsAndNumbers[word]++;
 }

with 70000 Words i get the following runtime: 00:00:00.0152345 which is significant faster then the to lower solution on my machine which takes 00:00:00.0320127


text:
Q: "Does that mean to kill" or "does that mean killing", Which one is the proper one, and why? Should I say:

What is the English translation of 'ermorden', does it mean "to kill"?
What is the English translation of 'ermorden', does it mean "killing"?

I don't know which one to use, although "Does it mean to kill?" seems the right one, I feel like I'm missing something. May you guys tell me which one is grammatically correct and why?

A: The word ermorden is an German infinitive. In English, you make a verb into an infinitive  by putting the word "to" in front it, and you make a noun (Ermorden with a capital E) or an active participle by putting "-ing" on the end of it. So, it you want to ask for the exact meaning, you would ask

What is the English translation of 'ermorden': does it mean "to kill"?

and the answer would be

"Nearly right... a better translation would be "to assassinate" or "to murder".

For more information about gerunds (verbal nouns), participles and infinitives, see here

A: In a general context we would ask this using the infinitive (either marked with to or unmarked), since that's generally regarded as the 'base' form of a verb.

What is the English translation of 'ermorden'? Does it mean "to kill"? OR
  What is the English translation of 'ermorden'? Does it mean "kill"? †

In some specific contexts, however, things get a little more complicated, because both the infinitive (to) kill and the gerund-participle killing may be appropriate translation of ermorden employed as a nominal designating the act or practice of killing.

"Kleine Kinder ermorden ist schließlich das schlimmste und gemeinste." How should I translate ermorden here? Would "to kill" or "killing" express the sense more accurately?

†And in a general context the answer to both of these is "Probably not"—ermorden will usually call for a stronger translation as murder or in some circumstances assassinate—or as a nominal, assassination.

A: It depends on the context. It's perfectly acceptable to ask:

What is the English translation of 'ermorden', does it mean 'to kill'?


text:
Q: Intersecting Points on a Line in $ℝ^3$ Suppose you have a line in $ℝ^3$ that contains points $A(a,b,c)$ and $B(d,e,f)$.
Is it then true that the midpoint of $A$ and $B$ (say $C$) also lies on that line?
In other words, does it follow that the line also intersects point $C(\frac{a+d}{2},\frac{b+e}{2},\frac{c+f}{2})$?
Any help would be greatly appreciated.
CONTEXT:
I have an assignment question where you're given the equations of two lines $L_1$ and $L_2$ in $ℝ^3$ that contain unknown points $A$ and $B$ respectively, and you have to find the equation of a line that contains both points and is perpendicular to $L_1$ and $L_2$.
So far I have found the cross product of direction vectors of $L_1$ and $L_2$, which I will use as the direction vector of my new line.
I was then wondering if, by letting $C(\frac{a+d}{2},\frac{b+e}{2},\frac{c+f}{2})$ lie on my new line, this would then satisfy the requirement that the line contains $A$ and $B$.

A: It is intuitively clear. To show this, you may take the cross product of the vectors $\vec {CA}$ and $\vec{CB}.$ That should vanish.


text:
Q: How do I conditionally create a new instance of a class in C# asp.net? I have a class with different constructors. One constructor, nothing is passed through (creating a new record), the other an ID is passed through (which is used for an update). I'd like to test for a condition and make a new instance of the class object based on the outcome. My problem is that the object doesn't carry out of the if statement.
protected void Position()
{
    if (Session["PositionID"] == null)
    {
        JobPosition p = new JobPosition();
    }
    else
    {
        JobPosition p = new JobPosition(Convert.ToInt32(Session["PositionID"]));
    }
    p.positionTitle= pTitle.text;
    p.positionMission= pMission.text;
    p.positionDepartment= pDept.text;
    Session["PositionID"] = Convert.ToString(p.SaveDB());
}

p cannot be used in the current context. I could copy my code into each condition, it just seems like I shouldn't need to do that.
How can I use p?

A: You need to move the declaration of p to above the if statement:
JobPosition p;

if (Session["PositionID"] == null)
{
    p = new JobPosition();
}
else
{
    p = new JobPosition(Convert.ToInt32(Session["PositionID"]));
}

If you declare a variable inside a local scope, it is not accessible when you leave that scope.

A: Maybe I'm misunderstanding your question, but it seems like you want:
protected void Position()
{
    JobPosition p;
    if (Session["PositionID"] == null)
    {
        p = new JobPosition();
    }
    else
    {
        p = new JobPosition(Convert.ToInt32(Session["PositionID"]));
    }
    p.positionTitle= pTitle.text;
    p.positionMission= pMission.text;
    p.positionDepartment= pDept.text;
    Session["PositionID"] = Convert.ToString(p.SaveDB());
}

A: Move the JobPosition declaration outside the conditional.

A: protected void Position()
{
   JobPosition p; // No need for null;
   if (Session["PositionID"] == null)
    {
        p = new JobPosition();
    }
    else
    {
        p = new JobPosition(Convert.ToInt32(Session["PositionID"]));
    }

    // Don't need to check if p is null again here too
        p.positionTitle= pTitle.text;
        p.positionMission= pMission.text;
        p.positionDepartment= pDept.text;
        Session["PositionID"] = Convert.ToString(p.SaveDB());

}

A: Move p out of the if/else scope into the method scope.
JobPosition p = null;

if (Session["PositionID"] == null)
{
    p = new JobPosition();
}
else
{
    p = new JobPosition(Convert.ToInt32(Session["PositionID"]));
}

A: Declare JobPosition outside the if block:
JobPosition p;
if (Session["PositionID"] == null)
{
    p = new JobPosition();
}
else
{
    p = new JobPosition(Convert.ToInt32(Session["PositionID"]));
}

A: Change your code to:
JobPosition p = null;
if (Session["PositionID"] == null)
{
    p = new JobPosition();
}
else
{
    p = new JobPosition(Convert.ToInt32(Session["PositionID"]));
}

The null isn't strictly needed.

A: protected void Position()
{
    JobPosition p = null; //declare only once
    if (Session["PositionID"] == null)
    {
        p = new JobPosition();
    }
    else
    {
        p = new JobPosition(Convert.ToInt32(Session["PositionID"]));
    }
    p.positionTitle= pTitle.text;
    p.positionMission= pMission.text;
    p.positionDepartment= pDept.text;
    Session["PositionID"] = Convert.ToString(p.SaveDB());
}

A: I would be more inclined to do the following.
    protected void Position()
    {
        const string positionIdKey = "PositionID";
        var positionId = Session[positionIdKey];
        var p = positionId == null
            ? new JobPosition()
            : new JobPosition(Convert.ToInt32(positionId));
        p.Update(pTitle.text, pMission.text, pDept.text);
        Session[positionIdKey] = p.SaveDB();
    }


text:
Q: Writing to JS file with ASP Is it possible to write info to a JS file in ASP? I know that you can write to txt files, which I've done, but when I try the same method with JS files, it doesn't seem to work. I'm mainly a PHP programmer so I'm used to using fopen and fwrite to any of those file types and was curious if there's something similar in ASP. Thanks for your help!

A: Your question is a bit weird, but I am going to try and answer it for you in 3 different ways and perhaps then you can choose what fits your scenario.  In the future try to be as detailed as possible.

*

*If you are asking if you can use JavaScript as the scripting language for your ASP pages, versus using Vb Script then the answer is yes.  ASP can work with a few languages including Perl, and JavaScript (Jscript).   You need to declare it on top of your asp page, and stick to that language for the whole page (cannot mix languages).  <%@ Language= "Javascript" %>

*If you are asking if you can create physical files with .js extensions on the server, then that answer again is true.  You use the FileSystemObject to create these physical files, and write lines which have JavaScript code.  You want to make sure you completely close your file streams and FSO objects.  Good practice is to write to a temp location, then copy to production location when writing is done (all via FSO methods).   The biggest challenge you will run into with this type of coding is IUSER permissions for the directories you are trying to write files to.  FSO is great for writing logs, but probably should not be used to generate javascript.

*If you are looking to create Dynamic Javascript you have a few options.   You could go into IIS and let IIS know that .js files should be handled by asp.dll.  THis means files requested with .js extension would be run through the whole ASP pipeline and code with <% blocks %> would be run.   Alternately, if you can have a .asp extension for your javascript file.  For example if you want to create the following user variables from database you could do something like this.
<%

Response.Clear()
  Response.ContentType = "text/javascript"
dim UserID
  UserID = "Frank1979" ' Get this from a database or whatever.
' write out as javascript variable for use on client side.
  ' This will create a global js variable named UserID with value of frank1979
   Response.Write "var UserID = " & lcase(userID) & ";"
%>


text:
Q: Monitor when app opens file I am wondering if there is a way to monitor when a user presses open file (cmd+o) in any application.
I was thinking I could use addGlobalMonitorForEvents, but I was not sure how to get the specific on "Open File..." event.

A: I was able to mostly solve the problem by using this answer:
    let keycode = UInt16(0x1F)
    let keymask: NSEvent.ModifierFlags = NSEvent.ModifierFlags.command
    //...
    let options = NSDictionary(object: kCFBooleanTrue, forKey: kAXTrustedCheckOptionPrompt.takeUnretainedValue() as NSString) as CFDictionary
    let trusted = AXIsProcessTrustedWithOptions(options)
    if (trusted) {
        NSEvent.addGlobalMonitorForEvents(matching: .keyUp, handler: self.handler)
    }


text:
Q: Views dont render on ViewController presented programmatically from a different storyboard I'm developing app with a structure like this:
Edit: There's a common tab bar controller on main.storyboard
main.Storyboard -> NavController -> (relationship) ViewControllerA -> (show/push segue) ViewControllerB
secondary.Storyboard -> NavController -> (relationship) ViewControllerC
From ViewControllerC, I need to segue to ViewControllerB. I'm doing this using a Storyboard reference. The segue works, dependencies are passed in the segue, but I have one programmatic view that I load which isn't loading when the VC is presented from ViewControllerC on secondary.Storyboard and loads normally when presented with a storyboard segue
Here's how I'm triggering the segue to ViewControllerB:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let someObject = fetchedResultsController.object(at: indexPath).someRepresentation
    performSegue(withIdentifier: "theIdentifier", sender: someObject)
}

Here's how I'm handling the segue:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "theIdentifier" {
        guard let destination = segue.destination as? ViewControllerB,
        let sender = sender as? SomeCustomClass else { return }
        destination.receivedObject = sender
    }
}

I'm creating the views and adding to the view's subView in ViewWillAppear. I've also tried this in ViewDidAppear with no changed effect. Again, the views are created when the ViewController is presented from the same storyboard
Here's how I'm eventually creating the views
let webNavView = WebNavToolbarView(viewLayoutMarginsGuide: view.layoutMarginsGuide)
let yPosition: CGFloat = webNavView.frame.height / 4
let xOffset: CGFloat = 8

let backButton = createButton(
    image: .back,
    xPosition: xOffset,
    yPosition: yPosition,
    selector: #selector(goBackPressed)
)

let forwardButton = createButton(
    image: .forward,
    xPosition: backButton.frame.maxX + xOffset,
    yPosition: yPosition,
    selector: #selector(goForwardPressed)
)

// FIXME: Doing this just to get the width for the createButtonMethod's xPosition parameter
let homeButton = createButton(
    image: .home,
    xPosition: webNavView.frame.maxX - forwardButton.frame.width - xOffset,
    yPosition: yPosition,
    selector: #selector(goHomeButtonPressed)
)

webNavView.translatesAutoresizingMaskIntoConstraints = false
webNavView.addSubview(backButton)
webNavView.addSubview(forwardButton)
webNavView.addSubview(homeButton)

self.view.addSubview(webNavView)

The webNavView is using the layoutGuide that's passed in to get its width. X and Y are 0,0
All views are being created without constraints (using frames). The createButton method is just positioning the buttons after calling an initializer that styles them.
If I print view.subViews, webNavView is in there, but it doesn't appear on screen or in the Views Debugger. It's height and width are both 0, though it's height is hard-coded to 60
Also, if I add the toolbar to parent.view, it gets added but doesn't respect any of the safe area (it gets placed over the status bar)
Checking webNavView's frame:

Subviews also print out with the right position. But again, nothing even shows in Views Debugger
Main.storyboard:

secondary.storyboard:

storyboard reference:

A: I think I may have found your problem. You said you were laying out your views using frames, yet you are setting: webNavView.translatesAutoresizingMaskIntoConstraints = false. You need to get rid of this line of code because this tells the compiler that you are laying out your view using autolayout, and so it will ignore the frame. And since don't have any auto layout constraints defined, your webview is not showing on the screen.
I would also double check to make sure that you are not setting translatesAutoresizingMaskIntoConstraints to false for the webNavView's subviews.

A: Setting the webNavView.frame.origin.y = view.safeAreaInsets.top resolved the issue


text:
Q: Is bintray repository available for free? I searched for:
<dependency>
  <groupId>com.oracle</groupId>
  <artifactId>ojdbc6</artifactId>
  <version>11.2.0.2.0</version>
</dependency>

And found it at this site. It provides 2 links, one to mvnsearch and second for bintray. mvnsearch does not work while bintray can be opened without any authentication process.  It doesn't prompt for a username or password. So does bintray provide this dependency for free or there will be a problem when jar downloaded several times?

A: The link you have supplied is to JCenter, which is an open source free maven repository built on top of JFrog Bintray.  JFrog Bintray provides some free services to open-source users.  Bottom line, the link is free.
Disclaimer: I am with JFrog.


text:
Q: Plesk 12 Firewall blocking VNC connections I've looked far and wide for an answer to this and can't seem to find one.
I'm running Plesk 12 on Debian 7 and every time I activate the Plesk firewall it times out VNC connections refusing to connect them. If I disable the firewall it works fine, but obviously this isn't something that I want to do.
I've tried adding rules to allow incoming and outgoing connections on port 5900 (as suggested in the Windows docs, I assume it's the same on Linux?) but still no joy.
Anybody have any ideas?

A: Ahh finally found it...
https://www.realvnc.com/products/vnc/documentation/5.0/guides/user/ai1047203.html
Just in case anybody else is experiencing this problem, on linux, you have to also allow incoming connections on port 5901 ;)


text:
Q: How to enhance faceted pie charts labels in R? I have an energy dataframe for the share of different sources of energy for several years:
Year<-c("2016","2016","2016","2017","2017","2017","2018","2018","2018")
Source<-c("coal","hydro","solar","coal","hydro","solar","coal","hydro","solar")
Share<-c(0.5,0.25,0.25,0.4,0.15,0.45,0.7,0.1,0.2)
df<-cbind.data.frame(Year,Source,Share)

I am trying to plot the dataframe as faceted pie charts for the several years:

ggplot(df, aes(x=1, y=Share, fill=Source)) +
  geom_bar(stat="identity", width=1,position="fill")+
  coord_polar("y", start=0) +
  geom_text(aes(label = paste0(round(Share*100), "%")),size=2)+
  labs(x = NULL, y = NULL, fill = NULL, title = "Energy Mix")+
  theme_classic() + theme(axis.line = element_blank(),
          axis.text = element_blank(),
          axis.ticks = element_blank(),
          plot.title = element_text(hjust = 0.5, color = "#666666"))+
  facet_wrap(~Year)

and I get the following result:

How can I put the labels outside of the pie slices and centered for their arches, and how can I also add black thin borders to the slices? I know pie charts are not readable, and that bar charts are a bit better, but I am trying to play a bit diverse in options.
Many thanks in advance

A: Pie charts are basically stacked bar charts - thus you can apply the same rules. Comments in the code.
library(ggplot2)
Year<-c("2016","2016","2016","2017","2017","2017","2018","2018","2018")
Source<-c("coal","hydro","solar","coal","hydro","solar","coal","hydro","solar")
Share<-c(0.5,0.25,0.25,0.4,0.15,0.45,0.7,0.1,0.2)

## don't do that cbind stuff
df<-data.frame(Year,Source,Share)

ggplot(df, aes(x=1, y=Share, fill=Source)) +
  ## geom_col is geom_bar(stat = "identity")(bit shorter)
  ## use color = black for the outline
  geom_col(width=1,position="fill", color = "black")+
  coord_polar("y", start=0) +
  ## the "radial" position is defined by x = play around with the values
  ## the position along the circumference is defined by y, akin to
  ## centering labels in stacked bar charts - you can center the
  ## label with the position argument
  geom_text(aes(x = 1.7, label = paste0(round(Share*100), "%")), size=2,
            position = position_stack(vjust = 0.5))+
  labs(x = NULL, y = NULL, fill = NULL, title = "Energy Mix")+
  theme_classic() + theme(axis.line = element_blank(),
                          axis.text = element_blank(),
                          axis.ticks = element_blank(),
                          plot.title = element_text(hjust = 0.5, color = "#666666"))+
  facet_wrap(~Year)

Created on 2021-12-19 by the reprex package (v2.0.1)


text:
Q: App crash only on iPhone Device and not in Simulator - Xamarin Binding project I created iOS Binding Project with two static lib to SDK Payleven (github.com/payleven/mPOS-SDK-iOS). App crash only on iPhone Device and not in Simulator. On Simulator app works fine.
In "iOS Build" I set the same settings for iPhone and Simulator. The only difference is "Supported architecture:"
iPhone: ARMv7 + ARMv7s + ARM64
Simulator: i386 + x86_64
I try all configurations in "Linker behavior".
Without additional mtouch arguments in IOS Build I have 34  errors
http://pastebin.com/03S6P9DU
with arguments
-gcc_flags "-L${ProjectDir}/Soft.ePosPayleven/ -lPaylevenSDK -lAdyenToolkit -force_load ${ProjectDir}/Soft.ePosPayleven/libPaylevenSDK.a ${ProjectDir}/Soft.ePosPayleven/libAdyenToolkit.a"

I have this exception http://pastebin.com/8eEMrU0n  in class generated by xamarin in binding project.
[CompilerGenerated]
        [EditorBrowsable (EditorBrowsableState.Advanced)]
        [Export ("init")]
        public PLVPayleven () : base (NSObjectFlag.Empty)
        {
            IsDirectBinding = GetType ().Assembly == global::ApiDefinition.Messaging.this_assembly;
            if (IsDirectBinding) {
exception-->    InitializeHandle (global::ApiDefinition.Messaging.IntPtr_objc_msgSend (this.Handle, global::ObjCRuntime.Selector.GetHandle ("init")), "init");
            } else {
                InitializeHandle (global::ApiDefinition.Messaging.IntPtr_objc_msgSendSuper (this.SuperHandle, global::ObjCRuntime.Selector.GetHandle ("init")), "init");
            }
        }

libAdyenToolkit.linkwith.cs
[assembly: LinkWith ("libAdyenToolkit.a", LinkTarget.ArmV7 | LinkTarget.ArmV7s | LinkTarget.Simulator | LinkTarget.Simulator64 | LinkTarget.Arm64, SmartLink = true, ForceLoad = true,
     Frameworks = "CoreFoundation CoreData CoreLocation ExternalAccessory SystemConfiguration UIKit Foundation", LinkerFlags = "-lz -lsqlite3", IsCxx = true)]

libPaylevenSDK.linkwith.cs
[assembly: LinkWith ("libPaylevenSDK.a", LinkTarget.Simulator | LinkTarget.Simulator64 | LinkTarget.ArmV7 | LinkTarget.Arm64, SmartLink = true, ForceLoad = true,
     Frameworks = "CoreFoundation CoreData CoreLocation ExternalAccessory SystemConfiguration UIKit Foundation", LinkerFlags = "-lz -lsqlite3", IsCxx = true)]

Device: iPhone 5s
Xamarin Studio: 5.9.7 (build 9)
Tested on Simulators: 5, 5s, 6 with sdk 8.4 i 8.1
"lipo -info libPaylevenSDK.a" gives me: Architectures in the fat file: libPaylevenSDK.a are: i386 x86_64 armv7 arm64
and
"lipo -info libAdyenToolkit.a" : Architectures in the fat file: libAdyenToolkit.a are: i386 x86_64 armv7 armv7s arm64

A: As long as you have got an undefined symbol exception, you probably has your .a file built only for simulator. You can know it exactly if you run
nm %yourLibrary%.a | grep _SecCertificateCreateWithData

and find there only one line for one architecture.
Build one more library, for devices, and merge them with lipo like here:
https://developer.xamarin.com/guides/ios/advanced_topics/native_interop/


text:
Q: How do I make the plotOptions work in Highcharts Logarithmic axis? I was building a chart in HighCharts with logarithmic axis type. Here is a link to the code in JSfiddle.
https://jsfiddle.net/PowerHouse/ekwoupcy/15/
I'm consuming data from Google sheets and at the moment, the values are plotted exactly as in Google Sheets. I however wanted to plot the changes over time instead, something similar to this image. Ignore the left percentages (labels), the ones on the right are the workable ones or rather where my focus is on.

I have tried applying the plotOptions and specifying the compare: 'percent', but still I get the chart not showing the change over time but the exact stock value instead. Is there a way I could get the percent changes instead of the values themselves? I will appreciate any assistance. Thanks!


text:
Q: Run AVCaptureDevice.requestAccess blocking In my app I want to ask for camera access when the user pressed a camera button, which would take him to an AVFoundation based camera live preview.
That view is presented using a "present modally segue".
So in my ViewController I currently override the shouldPerformSegue() and return true if the user gives permission or has granted it already, otherwise false.
If the user didn't grant access I am showing an Alert in which he can go to settings to change the permission. That is done in showPermissionInfo().
My problem is, that AVCaptureDevice.requestAccess is called asynchronously and thus hasCameraPermission is not set to true before I'm checking for it.
Is there a way to call these restriction accesses in a blocking way?
Thank you!
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {

    if identifier == "Modally_ToCameraViewController"
    {
        var hasCameraPermission = false

        if AVCaptureDevice.authorizationStatus(for: .video) ==  .authorized
        {
            hasCameraPermission = true
        } else {
            AVCaptureDevice.requestAccess(for: .video, completionHandler: { (granted: Bool) in
                if granted {
                    hasCameraPermission = true
                } else {
                    hasCameraPermission = false
                }
            })
        }

        if(!hasCameraPermission){
            showPermissionInfo()
        }

     return hasCameraPermission
    }

        return true

}

A: One easy solution would be to create a semaphore and wait on it until the completion closure is called. semaphore.wait will block the current thread until semaphore.signal is called.
let semaphore = DispatchSemaphore(value: 0)

AVCaptureDevice.requestAccess(for: .video, completionHandler: { (granted: Bool) in
    if granted {
        hasCameraPermission = true
    } else {
        hasCameraPermission = false
    }
    semaphore.signal()
})

semaphore.wait()


text:
Q: How to REMOVE the splitting of text (output) in c++? I would like to know if there's a way to remove the splitting of text in the output in c++? For example in this pic,

the program ask me to input an amount and it will print the alphabet 'a' in that amount. So the input was 900 and thus the program printed 'a' 900 times but with splitting. I want that the program prints 'a' in just ONE single line.
The reason why I'm asking this is because I'm making a program which will print a certain command (I just need to copy-paste the output) some numbers of time and if those commands are split like this then they wouldn't just work.
Thanks.

A: The only thing I can think of is changing the size of the terminal window.
To do this: right-click on the status bar > Properties > Layout > Window Size > increase width.
This may not be what you want, but it may help a bit.  Of course, this is also limited by the size of your monitor.


text:
Q: pre-allocate memory to aligned byte like aligned_alloc in c or c++ 512 intrinsic I need to align memory to a 64 byte boundary in c or c++ guide
I can do that with char *ptr = aligned_alloc(64, size); aligned_alloc
But i want to do something like char ptr[size] = {0}; aligned to a block


text:
Q: Unity C# CharacterController Script I have a simple script attached to a ball model in unity. In a effort to control the ball, I have attempted to mimic this example provided by the documentation. The issue I receive is my ball visually rotates half as fast as its physical rotation changes.
Ex: The ball will rotate visually 180 degrees when you make a 360 degree physics rotation.
public class PlayerController : MonoBehaviour {
public float MoveSpeed;
public float RotationSpeed;
CharacterController controller;

void Start()
{
    controller = GetComponent<CharacterController>();
}

void Update()
{
    transform.Rotate(new Vector3(0, Input.GetAxis("Horizontal") * RotationSpeed, 0));
    Vector3 forward = Input.GetAxis("Vertical") * transform.TransformDirection(transform.forward) * MoveSpeed;

    controller.Move(forward);
}

What I would like to accomplish is for the ball to rotate in alignment with the rotation of its physics controls.

A: Just get rid of the transform.TransformDirection(transform.forward), since you are trying to transform the local forward vector of the transform to the forward vector of the same transform.
Just use a simple transform.forward instead.


text:
Q: how to get max of string in a group by in dataframe Table :-
I/P
user_id | channel

123.    | online
123.    | Null
123     |

Group by user_id and max of channel
O/P
user_id | channel

123.    | online

in SQL it is done using this query
select user_id,max(channel) from table_name group by user_id
the same functionality I need in pandas Dataframe

A: Gedas Miksenas is right... But in your data there is blank & null too, so might through error, it's better to first convert the channel column to str then do groupby... like this...
df = pd.DataFrame({"user_id":[123,123,123],
                   "channel":["online",np.nan,""]})
df['channel'] = df['channel'].astype(str)
df1 = df.groupby('user_id')['channel'].max().reset_index()

# Output
   user_id channel
0      123  online


text:
Q: Is it possible to use Apple Push Notification Service only for local network? I have an apsd process which stands for Apple Push Notification service daemon man_page_on_developers.apple.com (it has a name applepushserviced on osx 10.7 and lower). Is it possible to restrict it only for local APN server without having a connection to the apple global APN server?

A: Disabling the internet connection for this service would prevent you from receiving any notifications which use the Apple Push service. Restricting it to your local network would have the same effect as preventing it from connecting at all, since there is no local APN server.


text:
Q: How to disable mutiselect option in datagrid in c# How to disable mutiselect option in datagrid with datatables in c# ?
Actually I have two tables A and B now I'm gonna select a value from table A and click on down arrow button to move the selected row from table A to table B
Now for first time, when i select a row in table A and click on down arrow button
selected row fails to add but when i try to the same operation its working fine ..
Here is my code snippet -- Here very first time when i select a row and click on down arrow button it pop up me the :: No rows selected! and after that it works perfectly ..
private void btnSelect_Click(object sender, EventArgs e)
        {
            dgvFormFieldsView.MultiSelect = false;
            DataGridViewSelectedRowCollection selectedRows = dgvFormFieldsView.SelectedRows;
            dgvFormFieldsView.ClearSelection();

            if (selectedRows.Count == 0)
            {
            MessageBox.Show("No rows selected!", "Warning");
            return;
            }

            for (int i = selectedRows.Count -1 ; i >= 0; i--)
            {
                    string fieldLabel = null;
                    string fieldType = null;
                    string tabOrder = null;

                    tabOrder = (string)selectedRows[i].Cells[0].Value;
                    fieldLabel = (string)selectedRows[i].Cells[1].Value;
                    fieldType = (string)selectedRows[i].Cells[2].Value;

                    DataRow newRow = selectedFieldsTable.NewRow();
                    newRow["Field Name"] = fieldLabel;
                    newRow["Field Type"] = fieldType;

                    /*Temp Table*/
                    DataRow newRows = TempTable.NewRow();
                    newRows["Field Name"] = fieldLabel;
                    newRows["Field Type"] = fieldType;

                    if (!selectedFieldsTable.Rows.Contains(new System.Object[] { fieldType, fieldLabel }))
                    {
                       selectedFieldsTable.Rows.Add(newRow);
                       acc = selectedFieldsTable.Rows.Count;
                       temprow = TempTable.Rows.Count;
                       if (temprow < 5)
                       {
                           TempTable.Rows.Add(newRows);
                           //Console.WriteLine(counter);
                           currenttemptablecounter = currenttemptablecounter + 1;
                           Console.WriteLine(currenttemptablecounter);
                       }
                       if (temprow >= 5)
                       {
                           NextSelect.Enabled = true;
                       }
                    }
                    else
                    {
                          MessageBox.Show("Form Field :" + fieldLabel + " already selected", "PDF Perform Info");
                    }
            }
            dgvSelectedFieldsView.DataSource = TempTable;
            dgvSelectedFieldsView.ClearSelection();
            applyFormattingSelectedFieldsTable();
         }

What am I doing wrong?

A: you must use the MultiSelect Property if the DataGridView, set to false (like you did), but in the initalization of the window (or in the designer), not in the select event.


text:
Q: Estimating largest eigenvalue of $N_{d\gg 1}(0,\Sigma)$ from small data I am trying to estimate the largest eigenvalue of some $d$-dimensional normal distribution $N_d(0,\Sigma)$ from the sample data
$$X_1, \ldots, X_N \sim_{iid} N(0,\Sigma)$$
where $N$ is much smaller than $d$, say $N = 20$ and $d=2000$. (Recall that PCA works nicely for $N$ much larger than $d$, but may not work in my case [1].) There's no assumption on the real-valued covariance matrix $\Sigma$. However, by performing PCA anyways, our observation shows that the eigenvalues seem to decay log-linearly.
Question How do we estimate the largest eigenvalue?
Pointers to any analysis are appreciated too, for example, an analysis that quantifies how bad the estimation is by running PCA on this setting anyways.
Footnote

*

*[1] However, a quick experiment in python actually suggests that this approach is stable enough! I still need a formal analysis though.

A: There is a history of answers to this kind of question following Horn's 1965 article on parallel analysis in principal component/s analysis (which has a confusing history of being called factor analysis, which Horn did). At any rate, in the 1960s Horn was interested in accounting for "sampling error and least-squares bias" in PCAs of the correlation matrix $\mathbf{R}$. Horn's solution was to make a quantitative, not analytic, estimation through PCA on $k$ matrices of random data of size $N\times d$, and to average the resulting $1^{\text{st}}$, $2^{\text{nd}}$, … $d^{\text{th}}$ eigenvalues (which he then subtracted from the eigenvalues of the PCA of the observed $\mathbf{R}$). This should also work for $\mathbf{\Sigma}$.
Because generating (pseudo) random numbers and because eigen-decomposition were both computationally expensive until about the mid 90s (and perhaps later, depending on the size of $N \times d$), there's a literature until about the turn of the millennium on estimating these average eigenvalues from $1$ to $d$ given $N$ and $d$ using computationally cheap formulas, while still using his parallel analysis approach to component retention decisions (Humphries and Montanelli, 1976; Allen and Hubbard, 1986; Lautenschlager, 1989; Longman, et al., 1989; Keeling, 2000). These methods were generally considered to be pretty lousy for the purposes of actual parallel analysis (e.g., see Zwick and Velicer, 1986; Hayton, et al., 2004), however, if, for your purposes, $\mathbf{\Sigma}$ is reasonably close to $\mathbf{R}$, you could probably use one of them.
There's also been a bit of a literature (Hayton, et al., 2004; Peres-eto, et al., 2005) about resampling/rerandomizing to generate the random data for parallel analysis, but this is unnecessary, since eigen-decomposition is not of the data per se, but of $\mathbf{R}$, and is insensitive to the distributional form of the data (Dinno, 2009).

References
Allen, S. J., & Hubbard, R. (1986). Regression equations for the latent roots of random data correlation matrices with unities on the diagonal. Multivariate Behavioral Research, 21(3), 393–396.
Dinno, A. (2009). Exploring the Sensitivity of Horn's Parallel Analysis to the Distributional Form of Simulated Data. Multivariate Behavioral Research, 44(3), 362–388.
Hayton, J. C., Allen, D. G., & Scarpello, V. (2004). Factor Retention Decisions in Exploratory Factor Analysis: A Tutorial on Parallel Analysis. Organizational Research Methods, 7(2), 191–205.
Horn, J. L. (1965). A rationale and test for the number of factors in factor analysis. Psychometrika, 30(2), 179–185.
Humphreys, L. G., & Montanelli, R. G. (1976). Latent roots of random data correlation matrices with squared multiple correlations on the diagonal: A Monte Carlo study. Psychometrika, 41(3), 341–348.
Keeling, K. B. (2000). A Regression Equation for Determining the Dimensionality of Data. Multivariate Behavioral Research, 35(4), 457–468.
Lautenschlager, G. J. (1989). A comparison of alternatives to conducting Monte Carlo analyses for determining parallel analysis criteria. Multivariate Behavioral Research, 24(3), 365–395.
Longman, R. S., Cota, A. A., Holden, R. R., & Fekken, G. C. (1989). A regression equation for the parallel analysis criterion in principal components analysis: Mean and 95th percentile eigenvalues. Multivariate Behavioral Research, 24(1), 59–69.
Montanelli, R. G., & Humphreys, L. G. (1976). Latent roots of random data correlation matrices with squared multiple correlations on the diagonal: A Monte Carlo study. Psychometrika, 41(3), 341–348.
Peres-Neto, P. R., Jackson, D. A., & Somers, K. M. (2005). How many principal components? Stopping rules for determining the number of non-trivial axes revisited. Computational Statistics & Data Analysis, 49(4), 974–997.
Zwick, W. R., & Velicer, W. F. (1986). A comparison of five rules for determining the number of factors to retain. Psychological Bulletin, 99(3), 432–442.


text:
Q: Graphics/Vision Interesting Topics I would like to do an interesting project for a computer graphics course. I know that there is a lot of literature out there (i.e. SIGGRAPH conference papers). I have a very large range of interest with regard to computer graphics (i.e. image processing, 3D modeling, rendering, animation). However, I've only taken computer vision/graphics for 2 semesters and thus don't have too much background experience, except for the class projects that I had to do.
I've been looking through SIGGRAPH papers trying to see if there is anything that will be of interest to me but the literature is extremely vast. I was wondering if anyone has any topic suggestions, anything interesting that you ran across that you could recommend. I would prefer to do something fun yet slightly challenging (not really interested in making a shooter game).
If this question does not belong here, I apologize and please let me know where I should move it.
Thanks!

A: Image Drawing animator. (the name is kind of misleading, but I didn't care much about it)
Anyway, the software does the following:

*

*Takes an image say a JPEG or BMP as input.

*Extract the lines from the image. (I used Matlab and Laplace transformations)

*Convert the static lines to Vector paths.

*Simulate drawing the image using the extracted paths.

In summary, you should give an image, for example a city scape, the program extract all lines and start drawing the buildings, streets and sunset lines, then finally add the colors one by one, until the full image is done.

A: Real time hand(s) detector.
You'll have plenty of interesting and fun applications with this.


text:
Q: signInSuccessUrl of firebaseUI not work for me I followed this tutorial enter link description here
After authentication succeed (Has been confirmed in Firebase console), the page not move to "/success"(signInSuccessUrl), and show the error message below:

I tried to changed the url to other page, "https://google.com", but it also not work.
Any advice will be helpful.
main.js
    new Vue({
        vuetify,
        el: '#app',
        router,
        components: { App },
        template: '<App/>',
        created() {
            firebase.initializeApp(config);
            firebase.auth().onAuthStateChanged((user) => {
                if (user) {
                    console.log("success")
                    this.$router.push('/success')
                } else {
                    console.log("auth")
                    // this.$router.push('/auth')
                }
            });
        },
    })

router/index.js
    let router = new Router({
      mode: 'history',
      routes: [
        {
          path: '/',
          component: Auth
        },
        {
          path: '/auth',
          component: Auth
        },
        {
          path: '/success',
          component: AuthSuccess
        }
      ]
    })

    export default router;

Auth.vue
<template lang="html">

</template>

Success.vue
<template>

Signup succeeded

    <button @click='logOut'>Log out</button>

{{name}}

{{email}}

{{userId}}

{{user}}

</template>

A: I forget to say I deployed this app to google app engine.
After I add localhost:8080 to the "Authorized JavaScript origins" in "APIs & Service" -> Credentials -> "Client ID for Web application", there is no problem now.
But there is one strange thing left: After I delete localhost:8080, the redirect still works fine.


text:
Q: Is it possible to supply a selection of two positional arguments where one of the two must be selected? I need to set a single positional argument to supply two available options, either the user can enter use the positional argument add or the positional argument delete. I would like to know how something like this is an option and hopefully a code example for how it might look.
an example of how I would expect the CLI to use this argument:
./myscript.py add --user USERNAME,
or
./myscript.py delete --user USERNAME,
or
./myscript.py delete --database DATABASE, etc.
Bonus points if we can somehow make this positional argument none-required
P.S. I don't mean to make the bonus question, the main question... it's much less important :)
Thanks all

A: You can limit the possible values with a choices parameter.  And make it optional with the '?' nargs:
parser=argparse.ArgumentParser()
parser.add_argument('foo',choices=['abc','def'],nargs='?')
parser.add_argument('-d')     # flagged options
args = parser.parse_args()
print(args)

The positional can occur in any order relative to the optionals.
Using more than one positional, where one is '?', is a bit trickier, see: Python argparse, Value after positional argument
For more control over which optional is allowed with these positional values, look at the subparsers mechanism.  But for a start try this simple version.
Test with:
print(parser.parse_args([]))   # no input, ok
print(parser.parse_args(['-d', '1', 'abc']  # ok
parser_parse_args(['adf'])  # error

A: Hi you can use a mutually exclusive group. From the official docs:
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> group = parser.add_mutually_exclusive_group()
>>> group.add_argument('--foo', action='store_true')
>>> group.add_argument('--bar', action='store_false')
>>> parser.parse_args(['--foo'])
Namespace(bar=True, foo=True)
>>> parser.parse_args(['--bar'])
Namespace(bar=False, foo=False)
>>> parser.parse_args(['--foo', '--bar'])
usage: PROG [-h] [--foo | --bar]
PROG: error: argument --bar: not allowed with argument --foo


text:
Q: Duplicates in temporal history table We have JCC feed that pumping data from Oracle to SQL Server 2016. For some unknown reasons there are duplicates in the history table with THE SAME start and end times. How can it happen? I tried to update record with the condition SET Column = Column. In that case I have 2 records where all the fields are the same, but start and end times are different. How can it happen that there are same datetimes?
UPDATE:

DDL:
CREATE TABLE [dbo].[LEASES](
    [LEASE_NUMBER] [CHAR](7) NOT NULL,
    [CREDIT_DECISION_CODE] [CHAR](1) NULL,
    [LEASE_APPLICATION] [CHAR](7) NULL,
    [ACCOUNT_NUMBER] [CHAR](8) NULL,
    [CELLULAR_NUMBER] [CHAR](10) NULL,
    [DEALER_CODE] [CHAR](5) NULL,
    [USERNAME] [CHAR](12) NULL,
    [LEASE_DATE] [DATETIME2](7) NULL,
    [NEW_USED_FLAG] [CHAR](1) NULL,
    [MANUFACTURER_CODE] [CHAR](6) NULL,
    [MODEL] [CHAR](10) NULL,
    [SERIAL_NUMBER_ELECTRONIC] [INT] NULL,
    [SERIAL_NUMBER_MECHANICAL] [CHAR](10) NULL,
    [CONTROL_HEAD] [CHAR](12) NULL,
    [LEASE_TERM] [SMALLINT] NULL,
    [LESSEE_CITY] [CHAR](17) NULL,
    [LESSEE_ADDRESS_1] [CHAR](30) NULL,
    [LESSEE_ADDRESS_2] [CHAR](30) NULL,
    [LESSEE_STATE] [CHAR](2) NULL,
    [LESSEE_ZIP_CODE] [CHAR](9) NULL,
    [LESSEE_NAME] [CHAR](30) NULL,
    [KEY_NAME] [CHAR](12) NULL,
    [BASE_PAYMENT] [DECIMAL](10, 2) NULL,
    [MONTHLY_SALES_TAX] [DECIMAL](10, 2) NULL,
    [INSURANCE] [DECIMAL](10, 2) NULL,
    [MONTHLY_PAYMENT] [DECIMAL](10, 2) NULL,
    [SECURITY_DEPOSIT] [DECIMAL](10, 2) NULL,
    [INVOICES_GENERATED_COUNT] [SMALLINT] NULL,
    [DATE_LAST_INVOICED] [DATETIME] NULL,
    [DATE_LAST_LATE_FEE] [DATETIME] NULL,
    [SECURITY_DEPOSITS_INVOICED] [DECIMAL](10, 2) NULL,
    [SECURITY_DEPOSITS_REFUNDED] [DECIMAL](10, 2) NULL,
    [ADVANCE_RENT] [DECIMAL](10, 2) NULL,
    [ADVANCE_SALES_TAX] [DECIMAL](10, 2) NULL,
    [TOTAL_ADVANCE_PAYMENT] [DECIMAL](10, 2) NULL,
    [AUTO_LEASE_EXPIRATION_DATE] [CHAR](4) NULL,
    [PAYMENTS_REMAINING] [SMALLINT] NULL,
    [PV_PAYMENTS_REMAINING] [DECIMAL](10, 2) NULL,
    [TAX_RATE] [DECIMAL](10, 4) NULL,
    [TAX_STATE] [CHAR](2) NULL,
    [LEASE_FACTOR] [DECIMAL](10, 4) NULL,
    [AMOUNT_FINANCED] [DECIMAL](10, 2) NULL,
    [REMARKS] [CHAR](60) NULL,
    [VOUCHER_NUMBER] [CHAR](12) NULL,
    [BILL_METHOD_ADVANCE] [CHAR](1) NULL,
    [FINANCING_PACKAGE] [INT] NULL,
    [BUYOUT_AMOUNT] [DECIMAL](10, 2) NULL,
    [BUYOUT_DATE] [DATETIME] NULL,
    [DEPRECIATION_MONTHS] [SMALLINT] NULL,
    [SALVAGE_VALUE] [DECIMAL](10, 2) NULL,
    [LAST_DEPRECIATION_DATE] [DATETIME] NULL,
    [LAST_DEPRECIATION_AMOUNT] [DECIMAL](10, 2) NULL,
    [ACCUMULATED_DEPRECIATION] [DECIMAL](10, 2) NULL,
    [BILL_METHOD_BUYOUT] [CHAR](1) NULL,
    [BUYOUT_INVOICED] [CHAR](1) NULL,
    [RECEIVED_DATE] [DATETIME] NULL,
    [LEASE_PROGRAM] [CHAR](5) NULL,
    [PAYMENTS_INCLUDED_ADVANCE] [SMALLINT] NULL,
    [SALESPERSON_CODE] [CHAR](5) NULL,
    [UNGUARANTEED_RESIDUAL_VALUE] [DECIMAL](10, 2) NULL,
    [UNEARNED_INCOME] [DECIMAL](10, 2) NULL,
    [DIRECT_COST] [DECIMAL](10, 2) NULL,
    [AMORTIZABLE_UNEARNED_INCOME] [DECIMAL](10, 2) NULL,
    [AMORTIZED_FLAG] [CHAR](1) NULL,
    [RESIDUAL_VALUE_PERCENTAGE] [DECIMAL](10, 4) NULL,
    [MINIMUM_LEASE_PAYMENTS] [DECIMAL](10, 2) NULL,
    [IMPLICIT_MONTHLY_INTEREST_RATE] [DECIMAL](10, 8) NULL,
    [AP_POSTED_FLAG] [CHAR](1) NULL,
    [AP_POSTED_DATE] [DATETIME] NULL,
    [CAPITALIZED_LEASE_FLAG] [CHAR](1) NULL,
    [LEASE_STATUS] [CHAR](1) NULL,
    [GROSS_INVESTMENT] [DECIMAL](10, 2) NULL,
    [ADVANCE_BILLED_FLAG] [CHAR](1) NULL,
    [AP_VOUCHER_NUMBER] [CHAR](12) NULL,
    [BANK_PACKAGE] [CHAR](5) NULL,
    [INSURANCE_BINDER] [CHAR](1) NULL,
    [CURRENT_BUYOUT] [DECIMAL](10, 2) NULL,
    [LEASE_AGE_YEARS] [SMALLINT] NULL,
    [GUARANTOR_NAME] [CHAR](30) NULL,
    [GUARANTOR_ADDRESS_LINE_1] [CHAR](30) NULL,
    [GUARANTOR_ADDRESS_LINE_2] [CHAR](30) NULL,
    [GUARANTOR_CITY] [CHAR](17) NULL,
    [GUARANTOR_STATE] [CHAR](2) NULL,
    [GUARANTOR_ZIP] [CHAR](9) NULL,
    [GUARANTOR_TELEPHONE] [CHAR](18) NULL,
    [GUARANTOR_SS_NUMBER] [CHAR](9) NULL,
    [GUARANTOR] [CHAR](30) NULL,
    [BILL_CYCLES_DEFER] [INT] NULL,
    [REVENUE_ACCOUNT] [CHAR](5) NULL,
    [INVOICE_TYPE] [CHAR](5) NULL,
    [CORRESPONDENCE_FLAG] [CHAR](1) NULL,
    [DOWN_PAYMENT] [DECIMAL](10, 2) NULL,
    [ADVANCE_INSURANCE] [DECIMAL](10, 2) NULL,
    [ORIGINAL_EQUIPMENT_COST] [DECIMAL](10, 2) NULL,
    [SERVICING_DEALER_CODE] [CHAR](5) NULL,
    [DEALER_BUYOUT_DATE] [DATETIME] NULL,
    [LEASE_OWNER_CODE] [CHAR](5) NULL,
    [LEASE_OWNER_DATE] [DATETIME] NULL,
    [VENDOR_CODE] [CHAR](5) NULL,
    [SPLIT_FUNDING_COUNT] [SMALLINT] NULL,
    [DEALER_AMOUNT] [DECIMAL](10, 2) NULL,
    [VENDOR_AMOUNT] [DECIMAL](10, 2) NULL,
    [SALESPERSON_AMOUNT] [DECIMAL](10, 2) NULL,
    [DEALER_OFFICE] [SMALLINT] NULL,
    [ASSESSMENT_YEAR] [SMALLINT] NULL,
    [PROPERTY_TAX_RATE] [DECIMAL](10, 4) NULL,
    [ASSESSMENT_FACTOR] [DECIMAL](10, 4) NULL,
    [MONTHLY_PROPERTY_TAX] [DECIMAL](10, 2) NULL,
    [MANAGER_CODE] [CHAR](5) NULL,
    [DEALER_BUYOUT_PROGRAM] [CHAR](5) NULL,
    [SHARED_RESID_METHOD] [CHAR](1) NULL,
    [SHARED_RESID_AMOUNT] [DECIMAL](10, 2) NULL,
    [SHARED_RESID_PERCENT] [DECIMAL](10, 4) NULL,
    [SHARED_RESID_L_AND_D] [CHAR](1) NULL,
    [SHARED_RESID_COLLECTION_TYPE] [CHAR](1) NULL,
    [SHARED_RESID_MONTHS_OVERDUE] [SMALLINT] NULL,
    [ORIGINAL_LEASE_TERM] [SMALLINT] NULL,
    [ORIGINAL_LEASE_DATE] [DATETIME] NULL,
    [ORIGINAL_BASE_PAYMENT] [DECIMAL](10, 2) NULL,
    [ORIGINAL_MINIMUM_PAYMENTS] [DECIMAL](10, 2) NULL,
    [NEW_PAYMENT_PLAN_FLAG] [CHAR](1) NULL,
    [NEW_PAYMENT_PLAN_OFFSET] [SMALLINT] NULL,
    [NEW_PAYMENT_PLAN_DATE] [DATETIME] NULL,
    [NEW_MINIMUM_PAYMENTS] [DECIMAL](10, 2) NULL,
    [BILLING_PERIOD_NUMBER] [SMALLINT] NULL,
    [BILLING_PERIOD_1_INVOICES] [SMALLINT] NULL,
    [BILLING_PERIOD_1_PAYMENT] [DECIMAL](10, 2) NULL,
    [BILLING_PERIOD_2_INVOICES] [SMALLINT] NULL,
    [BILLING_PERIOD_2_PAYMENT] [DECIMAL](10, 2) NULL,
    [BILLING_PERIOD_3_INVOICES] [SMALLINT] NULL,
    [BILLING_PERIOD_3_PAYMENT] [DECIMAL](10, 2) NULL,
    [BILLING_PERIOD_4_INVOICES] [SMALLINT] NULL,
    [BILLING_PERIOD_4_PAYMENT] [DECIMAL](10, 2) NULL,
    [BILLING_PERIOD_5_INVOICES] [SMALLINT] NULL,
    [BILLING_PERIOD_5_PAYMENT] [DECIMAL](10, 2) NULL,
    [BILLING_PERIOD_6_INVOICES] [SMALLINT] NULL,
    [BILLING_PERIOD_6_PAYMENT] [DECIMAL](10, 2) NULL,
    [EQUIPMENT_AMOUNT] [DECIMAL](10, 2) NULL,
    [SERVICE_AMOUNT] [DECIMAL](10, 2) NULL,
    [MONTHS_OF_RECOURSE] [SMALLINT] NULL,
    [VENDOR_PAID_FLAG] [CHAR](1) NULL,
    [SALESPERSON_PAID_FLAG] [CHAR](1) NULL,
    [AP_ACCOUNT] [CHAR](5) NULL,
    [GL_AP_ACCOUNT] [CHAR](4) NULL,
    [GL_OWNER_COMPANY] [CHAR](4) NULL,
    [GL_BRANCH] [CHAR](1) NULL,
    [GL_DEPARTMENT] [CHAR](2) NULL,
    [GL_EQUIPMENT] [CHAR](2) NULL,
    [GL_STATE] [CHAR](2) NULL,
    [DEALER_RECOURSE_PERCENT] [DECIMAL](10, 4) NULL,
    [VENDOR_RECOURSE_PERCENT] [DECIMAL](10, 4) NULL,
    [SALESPERSON_RECOURSE_PERCENT] [DECIMAL](10, 4) NULL,
    [NUMBER_OF_UNITS] [SMALLINT] NULL,
    [INVOICES_SUBJECT_TO_DISCOUNT] [CHAR](1) NULL,
    [ORIGINAL_LEASE_PROGRAM] [CHAR](5) NULL,
    [MISSING_PAYMENT_COUNT] [SMALLINT] NULL,
    [BROKER_CODE] [CHAR](5) NULL,
    [REVENUE_SHARING_CODE] [CHAR](5) NULL,
    [REVENUE_SHARING_FACTOR] [DECIMAL](5, 2) NULL,
    [REVENUE_SHARING_FLAG] [CHAR](1) NULL,
    [DEALER_SHARING_CODE] [CHAR](5) NULL,
    [DEALER_SHARING_FACTOR] [DECIMAL](5, 2) NULL,
    [DEALER_SHARING_FLAG] [CHAR](1) NULL,
    [CHARGEBACK_RESERVE_FLAG] [CHAR](1) NULL,
    [FUNDING_FEE] [DECIMAL](10, 2) NULL,
    [FUNDING_FEE_INVOICED_FLAG] [CHAR](1) NULL,
    [LEASE_REFERENCE] [CHAR](30) NULL,
    [ORIGINAL_LEASE_NUMBER] [CHAR](12) NULL,
    [ORIGINAL_ACCOUNT_NUMBER] [CHAR](12) NULL,
    [BASE_PAYMENT_TAXABLE] [CHAR](1) NULL,
    [DAY_TO_CHARGE_BACK] [SMALLINT] NULL,
    [LESSEE_FED_ID_NUMBER] [CHAR](9) NULL,
    [ORIGINAL_PURCHASE_PRICE] [DECIMAL](10, 2) NULL,
    [ORIGINAL_PURCHASE_DATE] [DATETIME] NULL,
    [ACQUISITION_PURCHASE_PRICE] [DECIMAL](10, 2) NULL,
    [ACQUISITION_PURCHASE_DATE] [DATETIME] NULL,
    [BROKER_REV_SHAR_AMT_OVERRIDE] [DECIMAL](10, 2) NULL,
    [DEALER_REV_SHAR_AMT_OVERRIDE] [DECIMAL](10, 2) NULL,
    [UPFRONT_TAX_FLAG] [CHAR](1) NULL,
    [UPFRONT_TAX_AMOUNT] [DECIMAL](10, 2) NULL,
    [UPFRONT_TAX_BILLED] [CHAR](1) NULL,
    [SysStart] [DATETIME2](7) GENERATED ALWAYS AS ROW START NOT NULL,
    [SysEnd] [DATETIME2](7) GENERATED ALWAYS AS ROW END NOT NULL,
PRIMARY KEY CLUSTERED
(
    [LEASE_NUMBER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
    PERIOD FOR SYSTEM_TIME ([SysStart], [SysEnd])
) ON [PRIMARY]
WITH
(
SYSTEM_VERSIONING = ON ( HISTORY_TABLE = [dbo].[LEASES_HISTORY] )
)
GO

UPDATE 2:
I can't provide the real data, however this is the query I've used to get duplicates. Note that I am GROUPing BY all columns from the table, so these are definite duplicates:
SELECT LEASE_NUMBER
     , SysStart
     , SysEnd
     , cnt
  FROM
       (   SELECT *
                , COUNT(*) cnt
             FROM dbo.LEASES_HISTORY AS l
            GROUP BY l.LEASE_NUMBER
                   , l.CREDIT_DECISION_CODE
                   , l.LEASE_APPLICATION
                   , l.ACCOUNT_NUMBER
                   , l.CELLULAR_NUMBER
                   , l.DEALER_CODE
                   , l.USERNAME
                   , l.LEASE_DATE
                   , l.NEW_USED_FLAG
                   , l.MANUFACTURER_CODE
                   , l.MODEL
                   , l.SERIAL_NUMBER_ELECTRONIC
                   , l.SERIAL_NUMBER_MECHANICAL
                   , l.CONTROL_HEAD
                   , l.LEASE_TERM
                   , l.LESSEE_CITY
                   , l.LESSEE_ADDRESS_1
                   , l.LESSEE_ADDRESS_2
                   , l.LESSEE_STATE
                   , l.LESSEE_ZIP_CODE
                   , l.LESSEE_NAME
                   , l.KEY_NAME
                   , l.BASE_PAYMENT
                   , l.MONTHLY_SALES_TAX
                   , l.INSURANCE
                   , l.MONTHLY_PAYMENT
                   , l.SECURITY_DEPOSIT
                   , l.INVOICES_GENERATED_COUNT
                   , l.DATE_LAST_INVOICED
                   , l.DATE_LAST_LATE_FEE
                   , l.SECURITY_DEPOSITS_INVOICED
                   , l.SECURITY_DEPOSITS_REFUNDED
                   , l.ADVANCE_RENT
                   , l.ADVANCE_SALES_TAX
                   , l.TOTAL_ADVANCE_PAYMENT
                   , l.AUTO_LEASE_EXPIRATION_DATE
                   , l.PAYMENTS_REMAINING
                   , l.PV_PAYMENTS_REMAINING
                   , l.TAX_RATE
                   , l.TAX_STATE
                   , l.LEASE_FACTOR
                   , l.AMOUNT_FINANCED
                   , l.REMARKS
                   , l.VOUCHER_NUMBER
                   , l.BILL_METHOD_ADVANCE
                   , l.FINANCING_PACKAGE
                   , l.BUYOUT_AMOUNT
                   , l.BUYOUT_DATE
                   , l.DEPRECIATION_MONTHS
                   , l.SALVAGE_VALUE
                   , l.LAST_DEPRECIATION_DATE
                   , l.LAST_DEPRECIATION_AMOUNT
                   , l.ACCUMULATED_DEPRECIATION
                   , l.BILL_METHOD_BUYOUT
                   , l.BUYOUT_INVOICED
                   , l.RECEIVED_DATE
                   , l.LEASE_PROGRAM
                   , l.PAYMENTS_INCLUDED_ADVANCE
                   , l.SALESPERSON_CODE
                   , l.UNGUARANTEED_RESIDUAL_VALUE
                   , l.UNEARNED_INCOME
                   , l.DIRECT_COST
                   , l.AMORTIZABLE_UNEARNED_INCOME
                   , l.AMORTIZED_FLAG
                   , l.RESIDUAL_VALUE_PERCENTAGE
                   , l.MINIMUM_LEASE_PAYMENTS
                   , l.IMPLICIT_MONTHLY_INTEREST_RATE
                   , l.AP_POSTED_FLAG
                   , l.AP_POSTED_DATE
                   , l.CAPITALIZED_LEASE_FLAG
                   , l.LEASE_STATUS
                   , l.GROSS_INVESTMENT
                   , l.ADVANCE_BILLED_FLAG
                   , l.AP_VOUCHER_NUMBER
                   , l.BANK_PACKAGE
                   , l.INSURANCE_BINDER
                   , l.CURRENT_BUYOUT
                   , l.LEASE_AGE_YEARS
                   , l.GUARANTOR_NAME
                   , l.GUARANTOR_ADDRESS_LINE_1
                   , l.GUARANTOR_ADDRESS_LINE_2
                   , l.GUARANTOR_CITY
                   , l.GUARANTOR_STATE
                   , l.GUARANTOR_ZIP
                   , l.GUARANTOR_TELEPHONE
                   , l.GUARANTOR_SS_NUMBER
                   , l.GUARANTOR
                   , l.BILL_CYCLES_DEFER
                   , l.REVENUE_ACCOUNT
                   , l.INVOICE_TYPE
                   , l.CORRESPONDENCE_FLAG
                   , l.DOWN_PAYMENT
                   , l.ADVANCE_INSURANCE
                   , l.ORIGINAL_EQUIPMENT_COST
                   , l.SERVICING_DEALER_CODE
                   , l.DEALER_BUYOUT_DATE
                   , l.LEASE_OWNER_CODE
                   , l.LEASE_OWNER_DATE
                   , l.VENDOR_CODE
                   , l.SPLIT_FUNDING_COUNT
                   , l.DEALER_AMOUNT
                   , l.VENDOR_AMOUNT
                   , l.SALESPERSON_AMOUNT
                   , l.DEALER_OFFICE
                   , l.ASSESSMENT_YEAR
                   , l.PROPERTY_TAX_RATE
                   , l.ASSESSMENT_FACTOR
                   , l.MONTHLY_PROPERTY_TAX
                   , l.MANAGER_CODE
                   , l.DEALER_BUYOUT_PROGRAM
                   , l.SHARED_RESID_METHOD
                   , l.SHARED_RESID_AMOUNT
                   , l.SHARED_RESID_PERCENT
                   , l.SHARED_RESID_L_AND_D
                   , l.SHARED_RESID_COLLECTION_TYPE
                   , l.SHARED_RESID_MONTHS_OVERDUE
                   , l.ORIGINAL_LEASE_TERM
                   , l.ORIGINAL_LEASE_DATE
                   , l.ORIGINAL_BASE_PAYMENT
                   , l.ORIGINAL_MINIMUM_PAYMENTS
                   , l.NEW_PAYMENT_PLAN_FLAG
                   , l.NEW_PAYMENT_PLAN_OFFSET
                   , l.NEW_PAYMENT_PLAN_DATE
                   , l.NEW_MINIMUM_PAYMENTS
                   , l.BILLING_PERIOD_NUMBER
                   , l.BILLING_PERIOD_1_INVOICES
                   , l.BILLING_PERIOD_1_PAYMENT
                   , l.BILLING_PERIOD_2_INVOICES
                   , l.BILLING_PERIOD_2_PAYMENT
                   , l.BILLING_PERIOD_3_INVOICES
                   , l.BILLING_PERIOD_3_PAYMENT
                   , l.BILLING_PERIOD_4_INVOICES
                   , l.BILLING_PERIOD_4_PAYMENT
                   , l.BILLING_PERIOD_5_INVOICES
                   , l.BILLING_PERIOD_5_PAYMENT
                   , l.BILLING_PERIOD_6_INVOICES
                   , l.BILLING_PERIOD_6_PAYMENT
                   , l.EQUIPMENT_AMOUNT
                   , l.SERVICE_AMOUNT
                   , l.MONTHS_OF_RECOURSE
                   , l.VENDOR_PAID_FLAG
                   , l.SALESPERSON_PAID_FLAG
                   , l.AP_ACCOUNT
                   , l.GL_AP_ACCOUNT
                   , l.GL_OWNER_COMPANY
                   , l.GL_BRANCH
                   , l.GL_DEPARTMENT
                   , l.GL_EQUIPMENT
                   , l.GL_STATE
                   , l.DEALER_RECOURSE_PERCENT
                   , l.VENDOR_RECOURSE_PERCENT
                   , l.SALESPERSON_RECOURSE_PERCENT
                   , l.NUMBER_OF_UNITS
                   , l.INVOICES_SUBJECT_TO_DISCOUNT
                   , l.ORIGINAL_LEASE_PROGRAM
                   , l.MISSING_PAYMENT_COUNT
                   , l.BROKER_CODE
                   , l.REVENUE_SHARING_CODE
                   , l.REVENUE_SHARING_FACTOR
                   , l.REVENUE_SHARING_FLAG
                   , l.DEALER_SHARING_CODE
                   , l.DEALER_SHARING_FACTOR
                   , l.DEALER_SHARING_FLAG
                   , l.CHARGEBACK_RESERVE_FLAG
                   , l.FUNDING_FEE
                   , l.FUNDING_FEE_INVOICED_FLAG
                   , l.LEASE_REFERENCE
                   , l.ORIGINAL_LEASE_NUMBER
                   , l.ORIGINAL_ACCOUNT_NUMBER
                   , l.BASE_PAYMENT_TAXABLE
                   , l.DAY_TO_CHARGE_BACK
                   , l.LESSEE_FED_ID_NUMBER
                   , l.ORIGINAL_PURCHASE_PRICE
                   , l.ORIGINAL_PURCHASE_DATE
                   , l.ACQUISITION_PURCHASE_PRICE
                   , l.ACQUISITION_PURCHASE_DATE
                   , l.BROKER_REV_SHAR_AMT_OVERRIDE
                   , l.DEALER_REV_SHAR_AMT_OVERRIDE
                   , l.UPFRONT_TAX_FLAG
                   , l.UPFRONT_TAX_AMOUNT
                   , l.UPFRONT_TAX_BILLED
                   , l.SysStart
                   , l.SysEnd
           HAVING COUNT(*) > 1
       ) a;

UPDATE 3: Ok, by this time this is new info I was able to got. We tried to catch rpc_completed events to see what was actually going on. The trace file had 7 different statements with the different event_sequence numbers. As far as I understand this means that these statements were executed in different transactions. I'll try to prepare more detailed update later, but for now the statements were following (All the statements except the final one were executed using sp_prepexec stored procedures):
There are actually 3 different states the row had, let's call them x,y,z

*

*UPDATE record by PK with x state -- at this point there is no such record in the DB

*UPDATE record by PK with y state-- at this point there is no such record in the DB

*INSERT record with x state

*INSERT record with y state -- this failed with PK constraint violation

*UPDATE record to the x state -- that actually didn't change any row, so the actual record didn't change

*UPDATE record to the y state -- the actual record changed

*UPDATE record to the z state using sp_execute procedure where the handle_id is the same from the previous update (updating to the z state) but the values passed via parameters are different

So at the end of these operations we have:
Original table is in z state, and the history table has something like that (the datetimes are the real values):

*

*x state columns, 2017-11-01 16:55:31.3358248,  2017-11-01 16:55:31.3358248

*x state columns, 2017-11-01 16:55:31.3358248,  2017-11-01 16:55:31.3358248

*y state columns, 2017-11-01 16:55:31.3358248,  2017-11-01 16:55:41.9296659

A: Temporal tables use the begin time of the transaction as the timestamp used (see Temporal Tables in MS Docs under the insert, update, and delete sections). By doing multiple updates within your transaction, or an insert followed by an update within the same transaction you will get multiple records for a given primary key value with the same start/end times.
An excerpt from the link:

UPDATES: On an UPDATE, the system stores the previous value of the row
  in the history table and sets the value for the SysEndTime column to
  the begin time of the current transaction (in the UTC time zone) based
  on the system clock

Here is an example that will reproduce the behaviour. Notice that there are 2 identical entries for Miniature Widgets in the ProductsHistory table for ProductId = 2. Also note that although the updates for ProductId = 1 did not change the value, they still created identical history table records.
create table test.Products (
        ProductId       int not null primary key,
        ProductName     nvarchar(100) not null,
        EffectiveDate   datetime2(7) generated always as row start hidden not null,
        EndingDate      datetime2(7) generated always as row end hidden not null,
        period for system_time (EffectiveDate, EndingDate)
        )
        with (system_versioning = on (history_table = test.ProductsHistory));

go

begin tran

insert  test.Products (ProductId, ProductName) values
        (1, N'Widgets'),
        (2, N'Miniature Widgets');

update  test.Products set ProductName = 'Tiny Widgets' where ProductId = 2;
update  test.Products set ProductName = 'Miniature Widgets' where ProductId = 2;
update  test.Products set ProductName = 'Tiny Widgets' where ProductId = 2;
update  test.Products set ProductName = 'Widgets' where ProductId = 1;
update  test.Products set ProductName = 'Widgets' where ProductId = 1;

commit tran

select  p.ProductId, p.ProductName, p.EffectiveDate, p.EndingDate
from    test.Products for system_time all p;

select  *
from    test.ProductsHistory;

A: I'm going to add another possibility as a separate answer although I think this is far less likely - the server clock has changed. I have seen instances (more with text log files than SQL but still possible) with time overlap where the server/PC time has changed. This can happen when daylight savings starts/ends (although in this scenario it is unlikely since the start/end fields are in UTC). A more remote possibility is that you are having server clock drift. I doubt you would see this on a server - we were seeing it on single core industrial PCs running hot and CPU frequently maxxed out. Even synching the clock daily we could be short by a minute or 2 at the end of the day.


text:
Q: Datatables Row Grouping Stop Expanding When Input Clicked Using datatables and row grouping I am trying to get the rows to not expand when a input is clicked.. but only expand when the tr is clicked.    .stopPropagation() isn't working.
I am using .live() because the table is dynamically created by ajax.
$("#example input[type='text']").live('click',function(event){
    event.stopPropagation();
    return false;
});

Here's a jsfiddle:
http://jsfiddle.net/JWvZt/

A: While troubleshooting, it took me a while to find that you had your click event bound twice in your jsfiddle (at the beginning and at the end of the javascript frame).
After removing the first one and defining the 2nd as:
$("#example td").on('click','input[type="text"]', function(event){
    event.stopPropagation();
    return false;
});

the code works as desired.
Note: I'm using .on() because .live() is deprecated. In order to refresh the event bindings, when you dynamically create your rows you will have to call the above code fragment in the AJAX success handler (or .done() method).
Here's a link to jsfiddle


text:
Q: How to sort a html table column by clicking the header [PHP/MYSQL] I have a table that is populated by data from a mysql database and i need to be able to click on certain columns of the table to sort them ascending and descending, im not sure how to go about this if i can use php html or javascript , i will attach an image to show what i already have to give a better idea of what im talking about
https://imgur.com/a/ypnNxB0
<?php
$connection = mysqli_connect('localhost', 'root', '','nba201819'); //The Blank string is the password

$result = mysqli_query($connection,"SELECT * FROM `teamstats` ORDER BY `teamstats`.`WIN%` DESC");

?>

    Code
    Team
    GP
    W
    L
    WIN%
    MIN
    PTS
    FGM
    FGA
    FG%
    3PM
    3P%
    FTM
    FTA
    FT%
    OREB
    DREB
    REB
    AST

<?php
    while($row = mysqli_fetch_array($result))
    {

    echo "
";
    echo "	" ;
    echo "" . $row['TEAMCODE'] . "	";
    echo "" . $row['NAME'] . "	";
    echo "" . $row['GP'] . "	";
    echo "" . $row['W'] . "	";
    echo "" . $row['L'] . "	";
    echo "" . $row['WIN%'] . "	";
    echo "" . $row['MIN'] . "	";
    echo "" . $row['PTS'] . "	";
    echo "" . $row['FGM'] . "	";
    echo "" . $row['FGA'] . "	";
    echo "" . $row['FG%'] . "	";
    echo "" . $row['3PM'] . "	";
    echo "" . $row['3P%'] . "	";
    echo "" . $row['FTM'] . "	";
    echo "" . $row['FTA'] . "	";
    echo "" . $row['FT%'] . "	";
    echo "" . $row['OREB'] . "	";
    echo "" . $row['DREB'] . "	";
    echo "" . $row['REB'] . "	";
    echo "" . $row['AST'] . "	";

    echo "
";

    }

    echo "
";

?>

A: There are various js plugins to help achieve data table sorting such as easyui, datatables etc.
If you only want to achieve it with simple code like you provided, you have to retrieve the sortBy variable and put it in your SQL query:
$connection = mysqli_connect('localhost', 'root', '','nba201819'); //The Blank string is the password

if (isset($_GET['sortBy'])) {
    if ($_GET['sortBy'] !== '') {
        $sortBy = str_replace( "`", "``", $_GET['sortBy']);
    } else {
        $sortBy = 'WIN%';
    }
} else {
    $sortBy = 'WIN%';
}

$result = mysqli_query($connection,"SELECT * FROM `teamstats` ORDER BY `teamstats`.`$sortBy` DESC");