text:
Q: solving the recurrence T(floor[n/2]) + T(ceil[n/2]) + n - 1 I have the following recurrence:
T(n) = c for n = 1.
T(n) = T(floor[n/2]) + T(ceil[n/2]) + n - 1 for n > 1.

It looks like merge sort to me so i guess that the solution to the recurrence is Θ(nlogn). According to the master method i have:
a) Θ(1) for n = 1 (constant time).
b) If we drop the floor and ceil we have: (step1)
   T(N) = 2T(N/2) + n - 1 => a = 2, b = 2.
   logb(a) (base b) = lg(2) = 1 so n^lg(2) = n^1 = n

Having a closer look we know that we have case 2 of master method:
 if f(n) = Θ(log(b)a) our solution to the recurrence is T(n) = Θ(log(b)a log(2)n)

The solution is indeed T(n) = Θ(nlogn) but we are off my a constant factor 1.
My first question is:
at step 1 we dropped of ceil and floor. Is this correct ? The second question is how do i get rid of the constant factor 1 ? do i drop it ? or should i name it d and prove that n - 1 is indeed n (if so how do i prove it ?). Lastly is it better to prove it with the substitution method ?
Edit: if we use the substitution method we get:
  We guess that the solution is O(n). We need to show that T(n) <= cn.
  Substitutting in the recurrence we obtein
  T(n) <= c(floor[n/2]) + c(ceil[n/2]) + n/2 - 1 = cn + n/2 - 1

So it is not merge sort ? What do i miss?

A: It was long time ago, but here goes
Step 1 we dropped of ceil and floor. Is this correct ?
I would rather say
T(floor(n/2)) + T(floor[n/2)) <= T(floor(n/2)) + T(ceil[n/2))
T(floor(n/2)) + T(ceil[n/2)) <= T(ceil(n/2)) + T(ceil[n/2))

in case they are not equal they differ by 1 (and you can ignore any constant)
The second question is how do i get rid of the constant factor 1 ?
You ignore it. Reasoning behind it is : even if constant is huge 10^100 it will be small compared to the size when n grows larger. In real life you can't really ignore really big constants, but that is how real life and theory differs. In any case 1 makes smallest amount of difference.
Lastly is it better to prove it with the substitution method
You can prove how you like, some are just simpler. Simpler are usually better, but other then that 'better' has no meaning. So my answer is no.


text:
Q: Drag multiple images separately in swift I have just started coding and this is my first project, and I want to drag couple images set on the screen separately and leave them where they are dragged.
However currently I could manage dragging images separately but comes back in their original position... what should I change if I want to leave each images where they are dragged.
HStack {
    ForEach(stickers) { sticker in
        Image(sticker.name)
            .resizable()
            .frame(width: self.screenWidth*0.2, height: self.screenWidth*0.2)
            .offset(x: self.selectedSticker == sticker ? self.dragOffset.width : 0,
                    y: self.selectedSticker == sticker ? self.dragOffset.height : 0)
            .gesture(
                DragGesture()
                    .updating(self.$dragOffset, body: { (value, state, transaction) in
                        if nil == self.selectedSticker {
                            self.selectedSticker = sticker
                        }
                        state = value.translation

                    }).onEnded { _ in self.selectedSticker = nil }
            )
    }
}

A: It seems that once the sticker is no longer the selected.sticker, its offset returns to zero. You'd need to set a variable that saves the images' locations after they are updated.
You could perhaps add another variable, offset, to Sticker:
struct Sticker: ... {
    var offset = CGSize.zero
    ...
}

And then store the offset value for each sticker in sticker.offset in .onEnded:
HStack {
    ForEach(stickers) { sticker in
        Image(sticker.name)
            .resizable()
            .frame(width: self.screenWidth*0.2, height: self.screenWidth*0.2)
            .offset(x: self.selectedSticker == sticker ? self.dragOffset.width : sticker.offset.width,
                    y: self.selectedSticker == sticker ? self.dragOffset.height : sticker.offset.height)
            .gesture(
                DragGesture()
                    .updating(self.$dragOffset, body: { (value, state, transaction) in
                        if nil == self.selectedSticker {
                            self.selectedSticker = sticker
                        }
                        state = value.translation
                    })
                    .onEnded { _ in
                        sticker.offset = dragOffset
                        self.selectedSticker = nil
                    }
            )
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Azure Storage Queue performance We are migrating a transaction-processing service which was processing messages from MSMQ and storing transacitons in a SQLServer Database to use the Azure Storage Queue (to store the id's of the messages and placing the actual messages in the Azure Storage Blob).
We should at least be able to process 200.000 messages per hour, but at the moment we barely reach 50.000 messages per hour.
Our application requests batches of 250 messages from the Queue (which now takes about 2 seconds to get the id's from the azure queue and about 5 seconds to get the actual data from the azure blob storage) and we're storing this data in one time into the database using a stored procedure accepting a datatable.
Our service also resides in Azure on a virtual machine, and we use the nuget-libraries Azure.Storage.Queues and Azure.Storage.Blobs suggested by Microsoft to access the Azure Storage queue and blob storage.
Does anyone have suggestions how to improve the speed of reading messages from the Azure Queue and then retrieving the data from the Azure Blob?
            var managedIdentity = new ManagedIdentityCredential();

            UriBuilder fullUri = new UriBuilder()
            {
                Scheme = "https",
                Host = string.Format("{0}.queue.core.windows.net",appSettings.StorageAccount),
                Path = string.Format("{0}", appSettings.QueueName),
            };
            queue = new QueueClient(fullUri.Uri, managedIdentity);
            queue.CreateIfNotExists();
            ...
            var result = await queue.ReceiveMessagesAsync(1);
            ...
            UriBuilder fullUri = new UriBuilder()
            {
                Scheme = "https",
                Host =  string.Format("{0}.blob.core.windows.net", storageAccount),
                Path = string.Format("{0}", containerName),
            };

            _blobContainerClient = new BlobContainerClient(fullUri.Uri, managedIdentity);
            _blobContainerClient.CreateIfNotExists();
            ...

        public async Task<BlobMessage> GetBlobByNameAsync(string blobName)
        {
            Ensure.That(blobName).IsNotNullOrEmpty();

            var blobClient = _blobContainerClient.GetBlobClient(blobName);
            if (!blobClient.Exists())
            {
                _log.Error($"Blob {blobName} not found.");
                throw new InfrastructureException($"Blob {blobName} not found.");
            }

            BlobDownloadInfo download = await blobClient.DownloadAsync();
            return new BlobMessage
                {
                    BlobName = blobClient.Name,
                    BaseStream = download.Content,
                    Content = await GetBlobContentAsync(download)
                };
        }

Thanks,
Vincent.

A: Based on the code you posted, I can suggest two improvements:

*

*Receive 32 messages at a time instead of 1: Currently you're getting just one message at a time (var result = await queue.ReceiveMessagesAsync(1);). You can receive a maximum of 32 messages from the top of the queue. Just change the code to var result = await queue.ReceiveMessagesAsync(32); to get 32 messages. This will save you 31 trips to storage service and that should lead to some performance improvements.

*Don't try to create blob container every time: Currently you're trying to create a blob container every time you process a message (_blobContainerClient.CreateIfNotExists();). It is really unnecessary. With fetching 32 messages, you're reducing this method call by 31 times however you can just move this code to your application startup so that you only call it once during your application lifecycle.


text:
Q: How to set up multiple permission for different folder in svn I have a folder name folder with name folder1 and another folder with name folder2. I have to set different read and write permission to these two folders.
i have done this in following way.
1) create new svn for my project using svnadmin create myproject -> This generate a folder under /home/svn/myproject(eventhough there is a folder /home/svn/repos)
2) Then i set up conf/passwd as
dev1 = dev1
dev2 = dev2

des1 = des1
des2 = des2

3) Then my svnserv.conf
anon-access = none
auth-access =write
password-db = passwd
authz-db = authz

4) and my authz file have
[groups]
developers = dev1,dev2
designers = des1, des2

[myproject:/dev_folder]
@developers = rw
@designers = none

[myproject:/des_folder]
@developers = none
@designers = rw

The dev_folder and des_folder are two folder under my project.
I think i have set up all correctly but when i check out or try to commit to svn it says inavlid authz configuration. Can anybody help me on this?
Also one more thing when i install svn there is a folder repos under /home/svn. But when i create a new svn the svn folder /home/svn folder not under /home/svn/repos. Can anybody tell me what is the purpose of the folder repos?

A: It seems like you want two separate repos - that is if you really don't want the designers to even read dev_folder.  I think this will be your best bet
[groups]
developers = dev1,dev2
designers = des1, des2

[/]
@developers = r
@designers = r

[myproject:/dev_folder]
@developers = rw
@designers = r

[myproject:/des_folder]
@developers = r
@designers = rw


text:
Q: Finding subsequences from list Hello i can't figure out how to solve an assignment. I am supposed to find the consecutive element combinations from a list. For example: the list [1,2,3]
should give me [1],[2],[3], [1,2], [2,3], [1,2,3] but the problem i have is that my attempt also gives me [1,3]
Code:
subseq([], []).
subseq([H|T], [H|R]) :- subseq(T, R).
subseq([_|T], R) :- subseq(T, R).

A: The problem here is that on each element of the given list, you have two clauses:

*

*the second line where you select the item; and

*the third line where you do not select the item.

So that means you generate all lists where for every item it is an option to include it, or exclude it.
For a subsequence, the ones defined in your question, it is a different story: you basically have two selection points:

*

*the point where you "start" the subsequence; and

*the point where you "stop" the subsequence.

Stopping a subsequence is actually the same as generating a prefix:
myprefix(_, []).
myprefix([H|T], [H|T2]) :-
    myprefix(T, T2).

So now for a subsequence, we only need to branch over the starting point, and then add a prefix of the remaining list, like:
subsequence([H|T], [H|T2]) :-
    myprefix(T, T2).
subsequence([_|T], T2) :-
    subsequence(T, T2).

This then yields the expected:
?- subsequence([1, 2, 3], X).
X = [1] ;
X = [1, 2] ;
X = [1, 2, 3] ;
X = [2] ;
X = [2, 3] ;
X = [3] ;
false.


text:
Q: Retrieve shipping address from Paypal order server-side I have implemented Paypal smart buttons on the client side and I am capturing funds on the server side using PaypalCheckoutSdk nuget package.
During the checkout, paypal collects shipping address from the customer. How do I retrieve the shipping address after capturing funds?
This is how I capture funds from Paypal, which gives me an Order object with no shipping address:
        OrdersCaptureRequest request = new OrdersCaptureRequest(orderId);
        request.Prefer("return=representation");
        request.RequestBody(new OrderActionRequest());
        var response = await _client.Execute(request);
        var result = response.Result<Order>();

A: The order object does return a shipping address.
It will be inside the order object -> purchase_units -> shipping -> address.


text:
Q: ngMessages validation in AngularJS doesn't clean the error message in CSS Do you know why I keep having the red color underline error even when there is no error and validation passed fine??

I have my own directive to match both password and I'm using Angular material.
WORKING CODE HERE::::::::::::::
http://codepen.io/anon/pen/gPrMRM
http://codepen.io/anon/pen/gPrMRM
Angular app and js:
angular.module('MyApp', ['ngMaterial', 'ngMessages'])

.controller('AppCtrl', function ($scope) {
    $scope.project = {
        description: 'Nuclear Missile Defense System',
        rate: 500
    };
})
.directive('validPasswordC', function () {
    return {
        require: 'ngModel',
        link: function (scope, elm, attrs, ctrl) {
            ctrl.$parsers.unshift(function (viewValue, $scope) {
                var noMatch = viewValue != scope.projectForm.password.$viewValue;
                scope.projectForm.password.$error = {};
                ctrl.$setValidity('noMatch', !noMatch);
                console.log("scope.projectForm.password.$error: ");
                console.dir(scope.projectForm.password.$error);
            })
        }
    }
});

HTML:

    <md-content layout-padding="">
        <form name="projectForm">
            <md-input-container class="md-block">
                Client Email
                <input required="" type="email" name="clientEmail" ng-model="project.clientEmail" minlength="10" maxlength="100" ng-pattern="/^.+@.+\..+$/">

                        Your email must be between 10 and 100 characters long and look like an e-mail address.

            </md-input-container>

            <md-input-container class="md-block">
                Password
                <input type="password" id="password" name="password" ng-model="formData.password" ng-minlength="8" required />

required.

Passwords must be between 8 and 20 characters.

            </md-input-container>
            <md-input-container class="md-block">
                Confirm Password
                <input type="password" id="password_c" name="password_c" ng-model="formData.password_c" valid-password-c required />

Please confirm your password.

Passwords do not match.

projectForm.password.$error = {{ projectForm.password.$error | json }}

projectForm.password.$touched = {{ projectForm.password.$touched | json }}

projectForm.password_c.$error = {{ projectForm.password_c.$error | json }}

projectForm.password_c.$touched = {{ projectForm.password_c.$touched | json }}

            </md-input-container>
        </form>
    </md-content>

WORKING CODE HERE::::::::::::::
http://codepen.io/anon/pen/gPrMRM
http://codepen.io/anon/pen/gPrMRM

A: It is because you have a $parser that is not returning a value. You should change your directive to use the validators pipeline instead of the parsers.
<input type="password" id="password_c" name="password_c" required
       ng-model="formData.password_c"
       valid-password-c="{{formData.password}}" />

ctrl.$validators.noMatch = function (value) {

    // Return true if either of the passwords have not been provided yet
    if (!attrs.validPasswordC || !value) {
        return true;
    }

    return value === attrs.validPasswordC;
}

Updated to pass original password as attribute

A: You forgot to return the viewValue from the $parser function:
    ctrl.$parsers.unshift(function (viewValue, $scope) {
                var noMatch = viewValue != scope.projectForm.password.$viewValue;
                scope.projectForm.password.$error = {};
                ctrl.$setValidity('noMatch', !noMatch);
                console.log("scope.projectForm.password.$error: ");
                console.dir(scope.projectForm.password.$error);
                return viewValue;
            })

Here's a working codepen


text:
Q: Divider in Navigation Drawer using a xml menu I've been following the latest (?) tutorial of how to implement a Material Design Navigation Drawer side by side with this blogpost.
Instead of populating a list view it uses a menu resource (xml). Very neat and easy, but..
I can't figure out how to add dividers between menu items.
Image from Material Design spec:

menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android">
   <group android:checkableBehavior="single">
      <item
         android:id="@+id/item_1"
         android:checked="true"
         android:icon="@android:drawable/ic_menu_info_details"
         android:title="Item1"
      />
      <item
         android:id="@+id/item_2"
         android:icon="@android:drawable/ic_menu_agenda"
         android:title="Item2"
      />
      <item
         android:id="@+id/item_3"
         android:icon="@android:drawable/ic_menu_mapmode"
         android:title="Item3"
      />
      <item
         android:id="@+id/item_4"
         android:icon="@android:drawable/ic_menu_help"
         android:title="Item4"
      />
   </group>
</menu>

I have tried dividing by groups, but it gives me no divider. When I added a submenu, I got a divider but also an unwanted header.
Like this:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
  <group android:checkableBehavior="single">
    <item
      android:id="@+id/item_1"
      android:checked="true"
      android:title="Header1"
    >
      <menu>
        <item
          android:id="@+id/item_2"
          android:icon="@android:drawable/ic_menu_agenda"
          android:title="SubItem1"
        />
      </menu>
    </item>
    <item
      android:id="@+id/item_2"
      android:icon="@android:drawable/ic_menu_agenda"
      android:title="Item2"
    />
    <item
      android:id="@+id/item_3"
      android:icon="@android:drawable/ic_menu_mapmode"
      android:title="Item3"
    />
    <item
       android:id="@+id/item_4"
       android:icon="@android:drawable/ic_menu_help"
       android:title="Item4"
    />
  </group>
</menu>

I want the divider, but not the header.
Thanks in advance, I appreciate the help!

A: To add a divider after each menu item provide unique id to each group item as shown below

<group
    android:id="@+id/group_item_1"
    android:checkableBehavior="single">
    <item
        android:id="@+id/nav_agreement"
        android:icon="@mipmap/ic_launcher"
        android:title="Agreement" />
</group>
<group
    android:id="@+id/group_item_2"
    android:checkableBehavior="single">
    <item
        android:id="@+id/nav_aboutus"
        android:icon="@mipmap/ic_launcher"
        android:title="About Us" />
</group>
<group
    android:id="@+id/group_item_3"
    android:checkableBehavior="single">
    <item
        android:id="@+id/nav_terms"
        android:icon="@mipmap/ic_launcher"
        android:title="Terms Condition  " />
</group>
<group
    android:id="@+id/group_item_4"
    android:checkableBehavior="single">
    <item
        android:id="@+id/nav_chngpassword"
        android:icon="@mipmap/ic_launcher"
        android:title="Change Password" />
</group>
<group
    android:id="@+id/group_item_5"
    android:checkableBehavior="single">
    <item
        android:id="@+id/nav_signout"
        android:icon="@mipmap/ic_launcher"
        android:title="Sign Out" />
</group>


text:
Q: Correctness of limit proof for asymptotic analysis $ n^{\log(n)} \in o(\log(n)^n) $ Suppose that we want to show that $ n^{\log(n)} \in o(\log(n)^n) $.
Using the limit definition for asymptotic analysis we have
$$ n^{\log(n)} \in o(\log(n)^n) \ \ \Leftrightarrow \ \lim_{n \to \infty } \
\frac{n^{\log(n)}}{\log(n)^n} = 0 $$
Then
\begin{align}\lim_{n \to \infty } \frac{n^{\log(n)}}{\log(n)^n} &= \lim_{n \to \infty } \frac{e^{\log(n)^2} }{ e^{\log(\log(n)) n} } \\&= \lim_{n \to \infty } e^{\log(n)^2 - \log(\log(n)) n} \\&= e^{\lim_{n \to \infty } \log(n)^2 - \log(\log(n)) n} \end{align}

$$ e^{\lim_{n \to \infty } \log(n)^2 - \log(\log(n)) n} = 0 \ \Leftrightarrow \
\lim_{n \to \infty } \ \frac{\log(n)^2}{\log(\log(n)) n} = 0 $$
So we have
$$ \lim_{n \to \infty } \ \frac{\log(n)^2}{\log(\log(n)) n} \stackrel{\text{(L'Hopital)}}{=}   \ 2 \ \lim_{n \to \infty } \ \frac{\log(n)}{n (\frac{1}{log(n)} + log(log(n))}
\stackrel{\text{(L'Hopital)}}{=}   \ 2 \ \lim_{n \to \infty} \ \frac{1}{n \,
(\underbrace{\frac{1}{\log(n)} + 1 + \log(\log(n)) + \frac{1}{\log(n)}}_{> \, 0} )}
= 0 $$
Is this an acceptable proof?


text:
Q: Is there $g\in L^1(0,1)$ such that $\int_{\frac 12} ^1f' =-\int_0 ^1gf$ for all $f\in C^1_0(0,1)$? Consider a function $g\in L^1(0,1)$ such that $\int_{\frac 12} ^1f' =-\int_0 ^1gf$ for all $f\in C^1(0,1)$ with compact support.
Is such a function $g$ exists? My guess is no. My attempt is as follows:
From the fundamental theorem and from the compactness of the support of every $f$ we know that $f(\frac 12)=\int_0 ^1gf$. Now by choosing $f$ such that $f(\frac 12)=1$ and $\max f(x)=1$ we can derive from the Cauchy-Schwartz inequality that $1\le\int_0 ^1|g|$. Now I want to show that $\int _0 ^1 |g|<1$ but I could not do that. Any ideas?

A: I do not expect you can show $\int_0^1 |g| <1$. Indeed, the contradiction comes from the conclusion that $\int_0^1 |g|$ is "concentrated at $1/2$":
Note that
$$\tag{1}\lim_{\epsilon \to 0^+} \int_{1/2-\epsilon}^{1/2+\epsilon} |g|  = 0 \ \ \text{(How?)}$$
On the other hand, let $f = f_\epsilon$ be in $C^1_0(0,1)$ so that $|f|\le 1$, $f(1/2) = 1$ and $f(y) = 0$ if $|y-1/2|\ge \epsilon$.
Then
$$1 = f(1/2) = \int_0^1 gf = \int_{1/2-\epsilon}^{1/2+\epsilon} gf \le \int_{1/2-\epsilon}^{1/2+\epsilon} |g|.$$
But that will contradict $(1)$ for $\epsilon$ small enough.


text:
Q: How to set up static ip in ubuntu-server 18.04 using netplan on VM VirtualBox? Now I'm trying to set up static IP using netplan in ubuntu-server(18.04) on VM VirtualBox. I can access ubuntu-server(in VM) using putty in my local desktop, but ubuntu-server cannot access the internet.
There are my network settings and netplan setting.
VirtualBox Network Settings
Network
Host Network Manager
ubuntu-server Network Settings
Adapter1: NAT
Adapter2: Host-only Adapter
# /etc/netplan
# before

$ ls -al

drwxr-xr-x  2 root root 4096 Dec 24 16:20 .
drwxr-xr-x 94 root root 4096 Dec 24 12:46 ..
-rw-r--r--  1 root root  529 Dec 24 16:20 50-cloud-init.yaml

# /etc/netplan/50-cloud-init.yaml
network:
    ethernets:
        enp0s3:
            dhcp4: true
    version: 2

# /etc/netplan
# after

$ ls -al

drwxr-xr-x  2 root root 4096 Dec 24 16:53 .
drwxr-xr-x 94 root root 4096 Dec 24 12:46 ..
-rw-r--r--  1 root root  529 Dec 24 16:20 01-netcig.yaml
-rw-r--r--  1 root root  383 Dec 24 16:53 50-cloud-init.yaml

# /etc/netplan/50-cloud-init.yaml
network:
    ethernets:
        enp0s3:
            dhcp4: true
    version: 2
# /etc/netplan/01-netcig.yaml
network:
    ethernets:
        enp0s8:
            addresses: [192.168.56.102/24]
            gateway4: 192.168.56.1
            dhcp4: no
            nameservers:
                addresses: [8.8.8.8,8.8.4.4]
    version: 2

$ ifconfig

enp0s3: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 10.0.2.15  netmask 255.255.255.0  broadcast 10.0.2.255
        inet6 fe80::a00:27ff:fe4e:ace4  prefixlen 64  scopeid 0x20<link>
        ether 08:00:27:4e:ac:e4  txqueuelen 1000  (Ethernet)
        RX packets 2  bytes 1180 (1.1 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 10  bytes 1328 (1.3 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

enp0s8: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.56.102  netmask 255.255.255.0  broadcast 192.168.56.255
        inet6 fe80::a00:27ff:fe9d:f985  prefixlen 64  scopeid 0x20<link>
        ether 08:00:27:9d:f9:85  txqueuelen 1000  (Ethernet)
        RX packets 105  bytes 10500 (10.5 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 69  bytes 10361 (10.3 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 80  bytes 5920 (5.9 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 80  bytes 5920 (5.9 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

I can access ubuntu-server using putty on my local desktop, but my ubuntu-server can't access the internet. I can't send ping www.google.com and I can't command 'apt-get update'.
Please, help me.
What is the problem....


text:
Q: Timing Functions in c++: The most accurate approach I'd like to time each function in my code. So I have
func1();
func2();
func3();

At the moment I'm using
#include <omp.h>
#include <time.h>

double start1=omp_get_wtime();
func1();
double end1=omp_get_wtime();
cout<<"\nfunc1 run time :"<<end1-start1<<endl;

double start2=omp_get_wtime();
func2();
double end2=omp_get_wtime();
cout<<"\nfunc2 run time :"<<end2-start2<<endl;
...

Question: Is there any better and more accurate way than I'm using to measure run time for each function?

A: C++ recently (i.e., standard C++11) introduced std::chrono for getting timing information. This is a cross-platform mechanism. See here. If you have a modern compiler, you can use it as follows:
std::chrono::time_point<std::chrono::system_clock> t;
t = std::chrono::system_clock::now();

Prior than C++11, C++ did not contain any timing facility and you add to rely on either

*

*mechanisms provided by the operating system; on Linux you can use  clock_gettime()

*mechanism provided by the hardware platform (e.g., x86 TSC)

Which is the most accurate mechanism depends on your specific operating system and hardware platform.


text:
Q: how to run netflix on ubuntu 16.04 lts? how can I do tu use netflix whith ubuntu 16.04 LTS? I think that I need a complement but I don't know how to install it

A: Please look at the below link which says, install chrome and that has netflix out of box.
How to watch Netflix in Ubuntu?
let me know if you have question on installing chrome on ubuntu...

A: You should be able to see Netflix in the default web browser that comes in all Ubuntu official flavors: Firefox.
When you login to your Netflix account you should see a popup inviting you to enable DRM to be able to play Netflix media.
You can also of course, as previous comments suggest, install Google Chrome (not the same as Chromium).


text:
Q: How to take the most similar rand generated string to a master string, mutate the random string through generations to achieve the original string? i have generated N random sequences of length L in the letters A, C, G, T(e.g N= 10, L= 21) and created a function that calculates the distance between two 21 letter words,

as you can see, the output of this consists of the master genome and the mutations of said genome and how different the mutated genomes are from the original genome(how many characters are similar).
The issue is, i would like to be able to select the random sequence that has minimum distance to the 21-letter master sequence GATACCAATTACCAGATACCA. An alternative perspective of the same thing is to find the random sequence with the maximal overlap with the master sequence. This is a measure of fitness for these random sequences, and you select the random sequence with the highest fitness. Write a function that measures this overlap/fitness between a random 21-letter sequence and the master sequence.
After this initial step, create 10 offspring copies of that maximum fitness sequence, but evolve them by having a certain probability (e.g. 1/100) for each of the 21 letters to be randomly turned into a random letter of the alphabet (a mutation).
At each generation step, select from the 10 offspring the one with the highest fitness, and use that to evolve again in the next generation.
i would like to then be able to be able to repeat this process for a number of G generations, until the original master genome has been achieved through evolution- and how many generations it took- It should look something like this:

A: master = list('AATTATGTACCGGGAGCTCCG')
mutation = list('GTATCACGATGTCATCATCAA')
nucleotides = ("A", "C", "G", "T")

def hamming_distance(mutation, x = 0):
    list = []
    if mutation != master:
        for i, nuc in enumerate(mutation):
            if nuc != master[i]:
                list.append(i)
        print(f'Mutated: {"".join(mutation)}, {len(mutation) - len(list)}, {x}')
        for num in list:
            y = random.choice(nucleotides)
            mutation[num] = y
        x += 1
        hamming_distance(mutation, x = x)
    elif mutation == master:
        print(f'Mutated: {"".join(mutation)}, {len(mutation) - len(list)}, {x}')
        print("Master sequence has been achieved")

print(f'Master:  {"".join(master)}')
hamming_distance(mutation)

Example output:

Master:  AATTATGTACCGGGAGCTCCG
Mutated: GTATCACGATGTCATCATCAA, 4, 0
Mutated: GGATCGGAAGACCACCCTCTG, 7, 1
Mutated: CTATCAGCAGAAGTTGCTCCG, 10, 2
Mutated: GCCTACGGAGTGGAAGCTCCG, 13, 3
Mutated: GCCTAGGCATGGGGAGCTCCG, 14, 4
Mutated: CTGTAGGAATCGGGAGCTCCG, 15, 5
Mutated: TGGTAAGCACCGGGAGCTCCG, 16, 6
Mutated: ATATATGTACCGGGAGCTCCG, 19, 7
Mutated: AGATATGTACCGGGAGCTCCG, 19, 8
Mutated: AACTATGTACCGGGAGCTCCG, 20, 9
Mutated: AACTATGTACCGGGAGCTCCG, 20, 10
Mutated: AAATATGTACCGGGAGCTCCG, 20, 11
Mutated: AATTATGTACCGGGAGCTCCG, 21, 12
Master sequence has been achieved

This accomplishes your first task and gets your desired output in the order of mutated sequence, hamming distance, and generation number. This finds all the positions of the point mutations in the mutation sequence. For each of those positions, it swaps it out with another random nucleotide. Using recursion, I was able to automatically evolve the mutation sequence. I added the condition so it would stop as soon as both sequences were equal. If you wanted to add another chance to the mutation, say a 1/10 chance you can do something like this before the part that actually swaps out each nucleotide.
    for num in list:
        i = random.randint(1, 10)
        if i == 5: # The 5 is a random number that I chose
            y = random.choice(nucleotides)
            mutation[num] = y

This is a very naive answer but it works well. Furthermore, I would make the sequences and random integer a user input to make the function more flexible.


text:
Q: While keeps asking for input. Not skipping to second function This code, more specifically in line 28, ask the users for multiple choices. The code does work, but theres one issue and I cant find an answer that adapts to my case (this wont stop some of you from downvoting this question for some reason), anyways, the thing is that it keeps asking for input even tho I have told it to skip to second function (scenario_exit) which I didnt copy here to keep things simple. So thats the problem, it keeps asking me for input even tho I told the while to stop.
So, too long didnt read? Code loops at "You need to select one option", line 40.
scenario2options =['Approach exit door', 'Check for vital signs']
scenario2options_2 =['Shoot him', 'Let him live']

def scenario2(response):
    print response
    print "Conversation"
    print "Conversation2"
    print "Conversation3"
    print scenario2options

    decision_sc2 = 1

    while decision_sc2 == 1:
        decision_scenario2 = raw_input("> ")

        if 'Approach exit door' in decision_scenario2:
            print "Conversation"
            decision_sc2 = 0
            dead("Conversation")
        elif 'Check for vital signs' in decision_scenario2:
            print "One of them is still alive finish him off, says Lars"

            print scenario2options_2

            decision_sc2_2 = 1

            while decision_sc2_2 == 1:

                decision2_scenario2 = raw_input("> ")

                if 'Shoot him' in decision2_scenario2:
                    decision_sc2_2 = 0
                    scenario2_exit("You deliver him a quick dead.")
                elif 'Let him live' in decision2_scenario2:
                    decision_sc2_2 = 0
                    scenario2_exit("Conversation")

                else:
                    print "You need to select one option"
                    decision_sc2_2 = 1

        else:
            print "You need to select one option"

A: In the 'Check for vital signs' if block you don't set decision_sc2 to anything different, so your outer loop will still repeat.
Consider a function like this to make this stuff easier:
def get_choice(options):
    while True:
        print options
        choice = raw_input('> ').lower()
        for i, opt in enumerate(options):
            if opt.lower() in choice:
                 return i
        print "You need to select one of the given options."

Then you can check:
if get_choice(scenario2options)==0: # first choice, i.e. Approach exit door
    ...
else: # other choice, i.e. Check for vital signs
    ...

without needing a succession of nested while loops.

A: Your outer while-loop will always only evaluate the else-branch. Thus even if after the input decision_sc2_2 (you need to work on your variable naming....) is 0 (no need for the resetting it to 1 all the time in the last else-clause for the input), it will loop through the outer while again, reset decision_sc2_2 to 1, and the "game" continues.


text:
Q: Get list of usernames based on userID I want to make a batch query similar to this:
SELECT name FROM user
WHERE uid IN (userID1, userID2, userID3 ...) and name LIKE '%searchParameter%'

Is this even possible? And how can I achieve this?

A: Yes it is possible
SELECT name, uid from user WHERE uid in (SELECT uid2 FROM friend WHERE uid1=me()) and strpos(lower(name),lower('Zuck')) >= 0
In the case above I'm querying for names from friends that include the letters zuck
http://developers.facebook.com/docs/reference/fql/user/


text:
Q: Split string and display result accordingly using javascript? I have data which contains a combination of repeating strings.
var data = 01.01.2019 11:11:39 Sahil Dhir(K21004)  test1,
    02.01.2019 14:10:02 Rahul Kumar(K210005)  test2,
    03.01.2019 15:52:36 Jhonny Sins(K21006) test3,
04.01.2019 15:52:36 Mahendra Bahubali(K21006) test4

I want to display the data in a table or div format.

This is what I have tried so far.

var data = `01.01.2019 11:11:39 Sahil Sharma(K21004)  test1,
    02.01.2019 14:10:02 Rahul Verma(K210005)  test2,
    03.01.2019 15:52:36 Shikha Kappor(K21006) test3,
04.01.2019 15:52:36 Mahendra Bahubali(K21006) test4`;
    var arr = new Array();
    arr = data.split(',');
    var result = " " ;
    for(var i=0; i<arr.length; i++){
    result += ""+arr[i]+"";
    }
    console.log(result);
    var e = "";
    e = result.split(/[]+/);
    document.getElementById('print').innerHTML = ""+e+ "
";

I need to split already split string..

A: With this way, you can split your string as you like. If you want you can split splitArray values separately by space and create table as you want.

var data = `01.01.2019 11:11:39 Sahil Sharma(K21004)  test1,
    02.01.2019 14:10:02 Rahul Verma(K210005)  test2,
    03.01.2019 15:52:36 Shikha Kappor(K21006) test3,
04.01.2019 15:52:36 Mahendra Bahubali(K21006) test4`;

data = data.replace(/\n/g, ' ');
data = data.replace(/\s+/g, ' ');
data = data.replace(/\(/g, ' (');
data = data.replace(/\,\s+/g, ',');

let splitArray = data.split(',');

console.log(JSON.stringify(splitArray))

let text = ''

for(let a = 0; a < splitArray.length; a++ ) {

  text += splitArray[a].split(' ').join(' | ') + '
';

}

document.getElementById('print').innerHTML = text

A: If the data is all the same - you can take liberties with the splitting and get the elements. If the data structure changes - this will not work. Note that I have amended the datas - to remove the leading spaces and the newline characters from your code.
The following creates an aray of objects which can then be iterated over to give the table structure - with each object containing the portions of the data item.

var data = `01.01.2019 11:11:39 Sahil Sharma(K21004)  test1,02.01.2019 14:10:02 Rahul Verma(K210005)  test2,03.01.2019 15:52:36 Shikha Kappor(K21006) test3,04.01.2019 15:52:36 Mahendra Bahubali(K21006) test4`;
  var newArr = [];

    var  arr = data.split(',');

    arr.forEach(function(item){
      var newObj = {};
      var portions = item.split(' ');
      newObj['date'] = portions[0];
      newObj['time'] = portions[1];
      newObj['firstName'] = portions[2];
      newObj['lastName'] = portions[3].split('(')[0];
      newObj['code'] = portions[3].split('(')[1].split('\)')[0];
      newObj['test'] = item.split(')')[1].trim();
      newArr.push(newObj)
    });

    var tableStr = '';

    newArr.forEach(function (item){
    tableStr += '
';
      tableStr += '' + item.date + '	';
      tableStr += '' + item.time + '	';
      tableStr += '' + item.firstName + '	';
      tableStr += '' + item.lastName + '	';
      tableStr += '' + item.code + '	';
      tableStr += '' + item.test + '	';
    tableStr += '
';

    })

    document.querySelector('#data-table tbody').innerHTML = tableStr;
table {
  border-collapse: collapse;
}

table, th, td {
  border: 1px solid black;
  text-align: left;
  padding: 5px 10px;
}

      Date
      Time
      First name
      Last Name
      PID
      Test No.

A: Split and join on (

var data = '01.01.2019 11:11:39 Sahil Sharma(K21004)  test1, 02.01.2019 14:10:02 Rahul Verma(K210005)  test2,03.01.2019 15:52:36 Shikha Kappor(K21006) test3,04.01.2019 15:52:36 Mahendra Bahubali(K21006) test4';
    var arr = new Array();
    arr = data.split(',');
    var result = " " ;
    for(var i=0; i<arr.length; i++){
    var e = "";
    e = " "+arr[i].split('(').join(" (")+" ";

    document.getElementById('print').innerHTML+= ""+e+ "
";
    }

A: Split data on , space and (.
processedArray will contain purified elements that you can iterate over to add them to your table.
let data = `01.01.2019 11:11:39 Sahil Sharma(K21004)  test1,
    02.01.2019 14:10:02 Rahul Verma(K210005)  test2,
    03.01.2019 15:52:36 Shikha Kappor(K21006) test3,
04.01.2019 15:52:36 Mahendra Bahubali(K21006) test4`;
let rows = data.split(",")
let array = [];
let elem;
let processedArray = [];
rows.forEach(function(row){
    array.push(row.trim().split(" "));
});
array.forEach(function(i){
    for(j = 0; j < i.length; j++){
        if(i[j] !== ""){
            elem = i[j].split("(");
            elem.forEach(function(k){
                processedArray.push(k.replace(")",""));
            });
        }
    }
});
console.log(processedArray);

A: try something like this to add the content in a table:

content


text:
Q: Android :How to getText from Edittext in side ListView? i have problem getting text from edittext inside listview when im in last edittext in the list problem in getting data of that edittext ,because when change focus of that edittext onfocuschangelistner is not getting call and data of that edittext is not store in my collection variable .
So any one have any solution plz suggest me
My code is here
    public class YourAdapter extends SimpleAdapter {

    protected static final String TAG = null;
    ArrayList<HashMap<String, String>> c = new ArrayList<HashMap<String, String>>();
    Context context;
    JSONArray getArray_Meter_Reading;
    HashMap<String, String> previous_Meter_Reading;
    ArrayList<HashMap<String, Integer>> getReading = new ArrayList<HashMap<String, Integer>>();
    Map<String,Integer> CurrentReading  = new HashMap<String, Integer>();
    int i, previousMeterReading, CurrentMeterReading, Cumulative;
    View v;
    EditText Caption;
    public static HashMap<Integer, String> myList = new HashMap<Integer, String>();

    public YourAdapter(Context context, int layout,
            ArrayList<HashMap<String, String>> c, String[] from, int[] to,
            JSONArray getArray_Meter_Reading) {
        super(context, c, layout, from, to);
        this.c = c;
        this.context = context;
        this.v = null;
        this.Caption = null;
        this.getArray_Meter_Reading = getArray_Meter_Reading;

        for (i = 0; i < getArray_Meter_Reading.length(); i++) {
            myList.put(i, "");
        }

    }

    public View getView(int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);
        final EditText ed_Current = (EditText) view
                .findViewById(R.id.ed_Current);
        ed_Current.setTag(position);

        ed_Current.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            public void onFocusChange(View arg0, boolean arg1) {

                int tag1 = (Integer) arg0.getTag();
                myList.put(tag1, ed_Current.getText().toString().trim());
                previous_Meter_Reading = new HashMap<String, String>();

                if (v == null) {
                    v = arg0;

                    int tag = (Integer) arg0.getTag();
                    Caption = (EditText) arg0;

                    previous_Meter_Reading = c.get(tag);
                    String getPreviousReading = previous_Meter_Reading
                            .get("previousMeterReading");
                    String CumulativeIndex = previous_Meter_Reading
                            .get("Cumulative");
                    previousMeterReading = Integer.parseInt(getPreviousReading);
                    Cumulative = Integer.parseInt(CumulativeIndex);
                }

                if (v != arg0) {

                    if (!Caption.getText().toString().equals("")
                            && Cumulative == 1) {

                        int tag = ((Integer) arg0.getTag());
                        CurrentMeterReading = Integer.valueOf(Caption.getText()
                                .toString());

                        //CurrentReading.put("Tag"+ tag, CurrentMeterReading);
                        //if(CurrentReading.containsKey("Tag"+ tag)){
                         //
                        //  Log.d("Contains","Tag"+ tag );
                        //  CurrentReading.remove("Tag"+ tag);
                        //}
                    //  }else{
                        //
                             CurrentReading.put("Tag"+ tag,CurrentMeterReading);
                        //}
                        //getReading.add(CurrentReading);
                             Log.d("CurrentReading",CurrentReading.toString() );
                        if (CurrentMeterReading < previousMeterReading) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(
                                    context);
                            builder.setTitle("WARNING");
                            builder.setIcon(android.R.drawable.ic_dialog_alert);
                            builder.setMessage("Current value cannot be less than Previous value for metre");
                            builder.setPositiveButton("ok",
                                    new DialogInterface.OnClickListener() {

                                        public void onClick(
                                                DialogInterface dialog,
                                                int which) {

                                            //Caption.requestFocus();

                                        }
                                    });

                            AlertDialog diag = builder.create();
                            diag.show();

                            // Caption.requestFocus();
                            // v = null;
                            // Caption = null;
                        }
                    }else {
                            if (Cumulative == 0

                                && !Caption.getText().toString().equals("")) {
                                int tag = ((Integer) arg0.getTag());
                            // int tag1 = ((Integer) arg0.getTag());
                            CurrentMeterReading = Integer.valueOf(Caption
                                    .getText().toString());

                            CurrentReading.put("Tag" +tag, CurrentMeterReading);
                            if(CurrentReading.containsKey("Tag"+ tag)){
                                CurrentReading.put("Tag"+ tag,CurrentMeterReading);
                            }
                            //getReading.add(CurrentReading);
                        }
                        }

                    //Caption.requestFocus();
                    v = null;
                    Caption = null;
                }

            }
        });

        ed_Current.setText(myList.get(position));
        return view;
    }
}

and my xml which im binding with listview using simpleadapter

    <?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:paddingBottom="6dip"
    android:paddingTop="4dip" >

    <TextView
        android:id="@+id/txt_Meter_Name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:width="140dp" />

    <TextView
        android:id="@+id/txt_Previous"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:width="100dp" />

    <EditText
        android:id="@+id/ed_Current"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:imeOptions="actionNext|actionDone"
        android:inputType="number"
        android:numeric="integer"
        android:singleLine="true"
        android:width="100dp" >
    </EditText>

</LinearLayout>

Thanks in advance

A: Go through below link you will get the Idea :
http://vikaskanani.wordpress.com/2011/07/27/android-focusable-edittext-inside-listview/


text:
Q: Remove entire row given certain condition Pandas I wanted to know if there's a way for me to remove an entire row of a dataframe given a condition (An outlier) in one column?
Df

Name
Value

Tree
300

Orange
50

Apple
75

Mango
60

Cherry
1

In this case I would want to remove Cherry and Tree since they're outliers.

A: Quite a subjective question. There is not a single definate way to do it. In fact there are multiple ways to do it. Use descriptive stats to build logic and then code it.
In this case I define the upper and lower limit and then filter using pandas mask. Code below
lower_limit=1
Upper_limit=100

df=df.assign(Value=df['Value'].where(df['Value'].between(lower_limit,Upper_limit))).dropna()

    Name  Value
1  Orange   50.0
2   Apple   75.0
3   Mango   60.0
4  Cherry    1.0

A: df[df.apply(lambda row: row['Value'] > lower_limit and row['Value'] < upper_limit, axis=1)]

apply() returns a boolean Series representing whether each df['Value'] value is outliers. df['Value'].between(lower_limit, upper_limit) has the same effect.
Dataframe can accept a boolean indexing. The effect is to drop the coresponding False row, keep the coresponding True row.


text:
Q: I'm building a SFTP/FTPS plugin for my app that can login to FTPS or SFTP servers. What authentication properties are different for FTPS and SFTP? My application needs to access files from a remote FTPS or SFTP server depending on what my app user wants to connect to. I need to be able to access file content in a folder or create a folder.
1) What login properties differ for an FTPS and SFTP server that a user must enter?
2) Is there any way I can detect if it is an SFTP or FTPS server?

A: *

*SFTP doesn't have any authentication. SFTP protocol is supposed to be used over SSH connection, thus it relies on SSH for authentication. So all authentication mechanisms of SSH apply. The list of such mechanisms is extensive - you can authenticate using password, a private key ("public-key authentication"), X.509 certificate (not a popular option), keyboard-interactive (challenge-response) dialog, also via GSS-API you can use Kerberos and possibly other mechanisms. FTPS as FTP-over-TLS can also use various mechanisms. FTP uses username/password by default, but potentially one can implement some tricky mechanisms using SITE command. TLS protocol includes client-side authentication using X.509 certificates, pre-shared symmetric keys, plain PKI keys, OpenPGP keys.

*SFTP and FTP/FTPS are completely different protocols. Servers run on different ports. If you want to implement protocol autodetection, you can try the following: connect to the server, and if it sends a welcome SSH message within 200-500 ms, you know that it's an SSH (and potentially SFTP) server. If it sends a welcome FTP message, it's an FTP server (this includes explicit TLS mode of FTPS). If it sends nothing, then it can be a TLS server and you can have implicit FTPS over this connection.


text:
Q: How to tell a common cathode vs a common anode full color led? Is there a way to visually tell if it has common cathode or a common anode on a full color LED?

A: If you can see the internal structure you can tell from whether the dies are on a common leadframe or whether the wire bonds go to a common leadframe (possibly it will be 2 of 3).
As to which is which (which you didn't ask), I don't keep that in my skull but it's easy enough to figure out.
Failing that, a battery, resistor and a couple jumper wires will allow you to 'visually' see which way the LEDs swing.


text:
Q: Is there any intuitive way to check whether a function is continuous at a given point? In my exams, the questions on continuity of multivariable functions are framed like "Discuss the continuity of $f(x,y)$ at $(a,b)$..." or "Is $f$ continuous at $(a,b)$...?", and likewise. If I know beforehand that the given function is discontinuous at a given point $(a,b)$, then I just need to find out two paths where the the value of $\lim_{(x,y)\to (a,b)} f(x,y)$ are different or not equal to $f(a,b)$. On the other hand, if I know that the function is continuous at the given point, then I can use the $\varepsilon-\delta$ definition of continuity to prove continuity. But since the questions don't seem to be giving much away about the continuity of the function at the given point, I'm not sure which approach should I take first while trying to solve the question.
Is there any quick and intuitive way to figure out whether a given multivariable function is continuous or not? At least in the cases where the given function is of the form $\frac{p(x,y)}{q(x,y)}$, where $p$ and $q$ are polynomials in $x$ and $y$? (Exceptions are fine. Just a generic and practically useful trick would do.)
For example, the function
$$f(x,y) =\begin{cases} \frac{x^{4}-y^{4}}{x^{4}+y^{4}} & (x,y)\neq (0,0) \\  0 & (x,y)=(0,0) . \end{cases}$$
is discontinuous at $(0,0)$, while the function
$$g(x,y) =\begin{cases} \frac{x^{2}y^{2}}{x^{2}+y^{2}} & (x,y)\neq (0,0) \\  0 & (x,y)=(0,0) . \end{cases}$$
is continuous at $(0,0)$. Is there any easy way to pick this just by looking at the functions?
The same issue exists with finding a limit and proving the existence of the limit.

A: Since you asked for heuristics: the degree being higher in the numerator than the denominator suggests continuity; being equal or less suggests discontinuity. (This is a heuristic and not a theorem, there are trivial counter-examples like $x/x$.)

A: This is how I would proceed:

*

*First of all, you only need to inspect the singularities, i.e. $(x,y)$ where $q(x,y)=0$.

*At each singularity, $(x_0,y_0)$ check the function along the direction $(u,v)\in \mathbb R^2 \setminus \{(0,0)\}$, i.e. calculate
$$
\lim_{t\searrow 0} f\big((x_0,y_0) + (u,v)t\big),
$$
and check if the limit is equal to $f(x_0,y_0)$ regardless of the choice of $(u,v)$. This should be very fast to do, so I don't see a reason not to do this calculation. If this condition is not satisfied, you found a contra-example. If not, it can give you an idea how to lead the proof of continuity.

*There are functions that are continuous in all directions, but yet not continuous. For example the function
$$
  f(x,y) = \begin{cases}
0 & \text{ if } y=0\\
1 & \text{ if } y=x^2 \neq 0 \\
\frac{xy}{y-x^2} & \text{otherwise}.
\end{cases}
$$
To detect a more complicated case of discontinuity like this one could evaluate
$$
  \lim_{t\searrow 0} f\big((x_0,y_0) + (u,v)t+(w,z) t^2 \big),
$$
for any $(u,v,w,z)\neq 0$.
Usually the steps 1 and 2 can be done just by looking at the function and doing a brief calculation in your head. Step 3 is already more complicated, but usually you would be able to guess for which $(u,v,w,z)$ something "will go wrong".

A: I want to warn that english is not my math-primary language so some things might be expressed incorrectly. Maybe you can use the fact that norms are equivalent in $\mathbb{R}^2$.

*

*Modify the function so you have to find if the obtained function is continuous on $(0,0)$.

*Separate the numerator polynomial into a sum of more simple functions

*Find the smallest upper bound norm $k$ for both numerator and demoninator (the norm $k$ is $\|(x,y)\|_k = (x^k+y^k)^{1/k}$)

*If the numerator has "more" norms than the denominator then it is continuous.

For example in your given examples:

*

*$x^4-y^4 \leq x^4+y^4 = (\|(x,y)\|_4)^4$ and $f(x,y) \leq \frac{(\|(x,y)\|_4)^4}{(\|(x,y)\|_4)^4} = 1 \neq 0$ Note that $4$ is the smallest norm we could find as an upper bound (because the numerator is at the power 4) so it is very likely that the function is not continuous at $(0,0)$

*$x^2y^2 \leq (\|(x,y)\|_2)^2(\|(x,y)\|_2)^2$ and $x^2 + y^2 = (\|(x,y)\|_2)^2$ so $f(x,y)\leq (\|(x,y)\|_2)^2$ and for any norm, $\|(x,y)\|\rightarrow 0$ when $(x,y)\rightarrow (0,0)$ (note that norms are also continuous)

Please note that:

*

*$x^k \leq (\|(x,y)\|_k)^k$ and $y^k \leq (\|(x,y)\|_k)^k$ for any $(x,y)$

*For each norms it exists $N \in \mathbb{R_+}$ such as $\|(x,y)\|_i\leq N\|(x,y)\|_j$
To sum up, the idea is to find the smallest norms possible for the numerator so that it cancels out the denominator if $f$ is continuous and otherwise, otherwise, the numerator is the one canceled out.
You can ask for more examples if you want.


text:
Q: Re-directing URLs with dates to URLs without dates When I first started writing entries I decided to include the month and day in the URL's, thinking I might need them. In the end turns out I didn't.
I found that I can access a particular entry as
http://myblog.com/2013/02/16/my-entry
http://myblog.com/my-entry

Typing in the second one would simply lead to a 301 redirect to the first.
Is there a way to make it so that typing in the long form with the date would re-direct to the second without breaking any permalinks?

A: You just have to set your permalinkstructure to /%postname%/.
Special rewrite rules do not need to be done here, as this is a simple setting WordPress handles on it's own.


text:
Q: Manifolds with nonpositive radial curvature How can one construct examples of Riemannian manifolds which have nonpositive radial curvature about some point, but are not nonpositively curved everywhere? (I presume that they exist, but  do not know for sure.) The question may be formulated precisely as follows.
A (complete) Riemannian manifold $M$ has a pole at a point $p$, provided that the exponential map $exp_p \colon T_p M\to M$ is a diffeomorphism. The radial curvatures of $M$ (with respect to $p$) are the sectional curvatures with respect to the planes tangent to geodesics emanating from $p$. If all the radial curvatures are nonpositive, then how can $M$ have any positive curvature?
It is easy to show that such examples cannot be constructed by means of a warped product metric on $S^{n-1}\times[0,\infty)$. So $M$ cannot be too symmetric with respect to $p$. I would be particularly interested in $3$-dimensional examples.


text:
Q: Is there any way to get data type of XMLHttpRequest on base controller in .net core 3.1 Here is any Jquery ajax POST request;
$.ajax({
    type: "POST",
    url: "/Customers/GetAll",
    contentType: "application/json",
    dataType: "json",
    success: function(response) {
        console.log(response);
    },
    error: function(response) {
        console.log(response);
    }
});

Here is my Controller Action Method which requested by ajax above;
public IActionResult GetAll()
{
    //Method body...
}

How can I get the dataType of any ajax request in base controller or action method?

A: Try to get accept in headers:

action:
 public IActionResult GetAll()
        {
            string dataType = HttpContext.Request.Headers["accept"].ToString();
            //Method body...
        }

A: The headers can be retrieved on the HttpContext object.
if(HttpContext.Request.Headers.TryGetValue("accept", out var acceptHeaders)) {
   var firstAcceptHeader = acceptHeaders.FirstOrDefault();
}

You can also access the header value using indexing Headers["accept"], but be aware, that if there is no accept header, for whatever reason, this will throw a NullReferenceException.


text:
Q: Linux command to get location of env file What command can I use to find out which file lists environment variables, as a user? It is not in ~/.bash_profile  or ~/.bashrc.
Thanks

A: Most of these things are going to be dynamic.  You can get a look at the current environment by doing:
env | less

You can add environment variables into your session on bash startup by modifying ~/.bashrc and placing variables at the end of the file.
export PATH=$PATH:/home/user/custom_path
export CUSTOM_ENV_VARIABLE=somevalue


text:
Q: Smallest ID from an Undirected graph Working with Oracle 11g, I'm trying to find the smallest ID in a undirected graph of ID pairs.
Using the following pairs:
create table unique_pairs ( ID1 INT, ID2 INT );
insert all
    into unique_pairs (ID1,ID2) VALUES ( 1, 2 )
    into unique_pairs (ID1,ID2) VALUES ( 1, 3 )
    into unique_pairs (ID1,ID2) VALUES ( 4, 2 )
    into unique_pairs (ID1,ID2) VALUES ( 4, 5 )
    into unique_pairs (ID1,ID2) VALUES ( 7, 6 )
    into unique_pairs (ID1,ID2) VALUES ( 8, 10 )
    into unique_pairs (ID1,ID2) VALUES ( 10, 7 )
select * from dual;
commit;

I'm using a union of two connect by queries to try and travel in two directions of the map:
select distinct a.ID1, a.ID2, min(a.ultimate_parent_id ) as ultimate_parent_id
from
(SELECT distinct ID1, ID2,
    connect_by_root(ID2) ultimate_parent_id
  FROM unique_pairs
CONNECT BY ID2 = prior ID1 AND ID2 != PRIOR ID2
union
SELECT distinct ID1, ID2,
    connect_by_root(ID1) ultimate_parent_id
  FROM unique_pairs
CONNECT BY ID1 = prior ID2 AND ID1 != PRIOR ID1) a
group by a.ID1, a.ID2
order by 3;

I get this:
   ID1        ID2 ULTIMATE_PARENT_ID

     1          2                  1
     1          3                  1
     4          2                  2
     4          5                  4
    10          7                  6
     7          6                  6
     8         10                  6

and should be this:
   ID1        ID2 ULTIMATE_PARENT_ID

     1          2                  1
     1          3                  1
     4          2                  1
     4          5                  1
    10          7                  6
     7          6                  6
     8         10                  6

My problem I think relates to the fact that the connect by function is implying a hierarchical structure when my data is non directional.  Any help would be great, thank you!

A: Collapsar has a very lengthy description, but here's a very brief solution that matches your requirements.  I'm too far removed from my graph theory days to explain it as he does, but the simple explanation is that since your unique_pairs represents the edges in an undirected graph it can be represented in a directed graph as the union of ID1, ID2 with ID2, ID1 hence my first common table expression.  With that directed graph you can compute all connected pairs of nodes as in my second common table expression. Finally you can join your original unique_pairs table to my connected pairs CTE on ID1 and take the minimum root node as your ULTIMATE_PARENT_ID:
with dg1 as (
  select id1, id2 from unique_pairs
  union all
  select id2, id1 from unique_pairs
), cp as (
select id1
     , CONNECT_BY_ROOT id1 root
  from dg1
connect by nocycle prior id1 = id2
)
select dg1.*
     , min(root) ULTIMATE_PARENT_ID
  from unique_pairs dg1
  join cp
    on cp.id1 = dg1.id1
  group by dg1.id1, dg1.id2
order by 1,2

See the SQL Fiddle
| ID1 | ID2 | ULTIMATE_PARENT_ID |
|-----|-----|--------------------|
|   1 |   2 |                  1 |
|   1 |   3 |                  1 |
|   4 |   2 |                  1 |
|   4 |   5 |                  1 |
|   7 |   6 |                  6 |
|   8 |  10 |                  6 |
|  10 |   7 |                  6 |

A: Concept
Your problem basically consists of 3 steps:

*

*identify the connected components of an undirected graph G

*represent each connected component by its vertex with the minimal id

*map each edge of the graph to the representative of the connected component it belongs to.

The task is solved by:

*

*considering an 'equivalent' directed graph D_1 based on the natural numerical ordering of G's vertex ids.

*reducing D_1 to a bipartite graph B containing all candidate ids by abstracting away chains in the ordering represented by D_1.

*determining minimal representative ids in B.

*establishing a mapping from G's edges onto B's edges and thus its weakly connected components (WCCs).

Details
The edge set of G is precisely the set of pairs (id1, id2) given by the records of unique_pairs. The vertex set of G matches the set of values from both id columns of unique_pairs. As G is undirected, it does not matter whether to represent an edge by the record (id1, id2) or (id2, id1); henceforth we assume wlog that id1 < id2 holds for each record (id1, id2) in unique_pairs.
We tackle the task by constructing an auxiliary structure based on the digraph D_1 derived from G by orienting each edge of the undirected graph according to the numerical order of the ids of its incident vertices. Let D_2 be D_1 with all edge orientations reversed. Identifying the connected components of the original graph amounts to identifying the WCCs in either D_1 or D_2. Observe that D_1 is acyclic by construction.
The assisting auxiliary structure is a mapping of the set of edges in G onto the powerset of maximal chains ( = a path not contained in another path ) in D_1, such that all chains in the image of an edge e contain e and maximize the difference between the numerical id of its terminals ( = start and end vertices ). The use of powersets is a technicality as otherwise the mapping might not be well-defined when two maximal chains share the same terminals but follow 'alternative routes' (usually the image will contain a single element).
In the next step we coarsen the mapping: instead of sets of maximal chains the image will be the pair of terminal ids of any maximal chain from the original mapping's image.
Given this mapping, we build an auxiliary bipartite graph B whose edges precisely represent the ordered pairs of terminal ids. The graph is bipartite since no end vertex of a maximal chain can be a start vertex of another maximal chain and vice versa - if this happened, said chains wouldn't have been maximal.
However, by construction, B forms a part of D_1's transitive closure. Therefore, the vertex sets of B's WCCs are subsets of the vertex sets of D_1's WCCs. We are ultimately interested in the vertex with the minimal id in each of the latter WCCs. As no terminal id contained in a maximal chain can be smaller than the start vertex id, all of these vertices must be contained in B's vertex set. So we have to consider B's WCCs only taking the minimum terminal id of each of them. Together with the auxiliary mapping of all G edges onto B edges and thus onto B's WCCs, we solve the original problem.
SQL implementation
In a preprocessing step, G's edges are normalized to the natural ordering of its incident vertices. Assuming that the orientation of the edges is id1 -> id2, test_unique_pairs also represents D_1.
update test_unique_pairs
   set id1 = id2
     , id2 = id1
 where id1 > id2
     ;

The first query maps the edges of D_1 to the edges of B, ie. the pairs of terminal ids of maximal chains in D_1. These chains are acyclic by construction and will be computed by a hierarchical query on the test_unique_pairs and they will be represented by their start and end vertices, these pairs also representing edges in B. This mapping occurs modulo alternative chains sharing both terminals - different maximal paths are considered equivalent if they share both terminals. Hierarchical queries in oracle allow for easy extraction of the maximal elements. The minimal elements, however, are the maximal elements of the hierarchy with parent-child relationships reversed (to cater for this computation is the reason for considering both digraphs D_1, D_2).
In order to ease the second processing stage, the query id wrapped into a view definition:
  create or replace view test_up_chains as
           select *
             from ( -- collect minimal/maximal reachable id for each edge in G
                          select distinct
                                 inter.id1
                               , inter.id2
                               , min(minelt)   chainstart
                               , max(maxelt)   chainend
                            from ( -- collect minimum/maximum terminal id for chains starting/ending with any of G's edges
                                         select distinct
                                                inter_min.id1
                                              , inter_min.id2
                                              , inter_min.minelt
                                              , inter_max.maxelt
                                           from ( -- hierarchical query for maximal chains in D_1
                                                        select distinct
                                                               hup.ID1
                                                             , hup.ID2
                                                             , CONNECT_BY_ROOT hup.id2   maxelt
                                                          from test_unique_pairs hup
                                                    connect by nocycle prior hup.id1 = hup.id2
                                                    start with hup.id2 in (
                                                                 select ref1.id2
                                                                   from test_unique_pairs ref1
                                                                  where not exists (
                                                                           select 1
                                                                             from test_unique_pairs ref2
                                                                            where ref2.id1 = ref1.id2
                                                                        )
                                                               )
                                                 ) inter_max
                                            join ( -- hierarchical query for maximal chains in D_2 ( = D_1 with reversed edge orientations )
                                                        select distinct
                                                               hup.ID1
                                                             , hup.ID2
                                                             , CONNECT_BY_ROOT hup.id1   minelt
                                                          from test_unique_pairs hup
                                                    connect by nocycle prior hup.id2 = hup.id1
                                                    start with hup.id1 in (
                                                                 select ref1.id1
                                                                   from test_unique_pairs ref1
                                                                  where not exists (
                                                                           select 1
                                                                             from test_unique_pairs ref2
                                                                            where ref2.id2 = ref1.id1
                                                                        )
                                                               )
                                                 ) inter_min
                                              on ( inter_min.id1 = inter_max.id1 AND inter_min.id2 = inter_max.id2 )
                                  ) inter
                         group by grouping sets ( (inter.id1, inter.id2) )
                   ) base
          order by base.id1
                 , base.id2
;

Next the edges of B are coalesced into WCCs and their respective minimal ids extracted. The following hierarchical query, lacking a STARTS WITH clause, builds the complete transitive closure wrt the edge incidence relation, and for each edge in B produces root paths to all other edges in the same WCC. Thus minimizing over the start vertex of all hierarchy 'root's given an edge in G finds the minimal reachable id in G.  Cycles are suppressed by the NOCYCLE directive.
                 select *
                   from (
                          select distinct
                                 id1
                               , id2
                               , min(chainlim)   chainrep
                            from (
                                         select distinct
                                                id1
                                              , id2
                                              , connect_by_root chainstart chainlim
                                           from test_up_chains
                                     connect by nocycle ( ( prior chainstart = chainstart and prior chainend != chainend ) OR ( prior chainstart != chainstart and prior chainend = chainend ) )
                                 ) base
                          group by grouping sets ( ( base.id1, base.id2 ) )
                        )
               order by id1
                      , id2
     ;


text:
Q: Not able to connect with SignalR hub using websockets transport type I have an angular6 / Material design application . I'm trying to connect to a webservice(Service Fabric + .net core) using signalR . But i get the following error ( i've tried in Firefox and in Chrome) :

"Error: Failed to start the transport 'WebSockets': undefined"
"Error: Failed to start the connection: Error: Unable to initialize any of the available transports."

In Chrome , I also have this error in addition to the 2 previous ones ( in the example i replaced the token by xxx):

WebSocket connection to 'wss://localhost:20003/supervisor?id=xxxx&access_token=xxxx' failed: HTTP Authentication failed; no valid credentials available

Here is my angular code :
//Creating Connection
this.hubConnection = new HubConnectionBuilder()
            .withUrl(this.hubUrl, {
                accessTokenFactory: () => {
                  return window.localStorage.getItem('token'); }
                  , transport: (HttpTransportType.WebSockets)})
            .configureLogging(LogLevel.Information)
            .build();
//Starting Connection
 this.hubConnection
        .start()
        .then(() => {
            console.log('connection succeeded')
        })
        .catch((e) => {
            console.log('Error while establishing connection  ', e);
        });

In my webservice , i have added in startup.cs the following code:
services.AddCors(options => options.AddPolicy("CorsPolicy", builder =>
        {
            builder
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowAnyOrigin()
                .AllowCredentials();
        }));

//in configure() method
app.UseCors("CorsPolicy");
app.UseWebSockets();
app.UseAuthentication();

Please let me know if there is a way to fix this issue


text:
Q: EmguCV filter image for certain colors For a current medical project I want to filter vaskularisation images to only show red and blue color. If possible I would also like to only show colored blobs over a certain size. In the following Images I have an example for one of these pictures I would like to analyse:
Vaskularisation.
I managed to filter it sofar that most of the noise is gone:
Filtered Image
. Now I would like to count the colored blobs in this image and display all which are bigger that a custom defined threshold. I am using EmguCV in C# for the image editing, but I have not found a way to select only the colored blobs. I would be grateful for any suggestions!


text:
Q: __autoload() doesn't work in included files I have a index.php file where the function __autoload() is on top.
The function looks like this (I'm using smarty):
function __autoload($classname) {

    echo "Loading classname.\n";

    if (substr($classname, 0, 15) == "Smarty_Internal") {
        $classname = "./libs/sysplugins/" . strtolower($classname);
        require_once $classname . ".php";
    }
    else {
        include $classpath.$classname.'.php';
    }
}

This works fine in this file.
Further down I have included another file with
include './files/otherfile.php';

In this file, I'm trying to load a class with
$bla = new ClassName;

But whenever i load the page i get this message:
Fatal error: Class 'ClassName' not found in ...

It doesn't even try to load the class with autoload, I don't get a "Loading classname." message which should be there.
Does anyone know why this doesn't work?


text:
Q: Throwing custom exceptions and error messages in Google Sheets custom function? In Google Sheets (as with Excel, etc) if a user enters bad input into a formula, an error code will be printed in the offending cell and a small pop-up provides more detail about the error.  So if I enter '=SQRT(-1)', '#NUM!' is printed in the cell and the pop-up explains that the value needs to be equal to or greater than 0.
How can I replicate this with a custom function in Google Sheets?  Throwing an exception mostly works.  For example, if I catch an out-of-bounds input value and then throw a custom exception, "#ERROR!" is printed in the offending cell (which is fine) and the exception's accompanying string is printed in the corresponding pop-up (which is also fine).  The problem is that the Google Apps Script engine also appends to the exception message the corresponding source code line that generated the exception.  So instead of the pop-up simply reading "The input value must be between 0.0 and 1.0", it will read "The input value must be between 0.0 and 1.0 (line 199)".
Is there any way to suppress the printing of the line number, or to overwrite the pop-up's message?  I want to be able to throw custom errors and provide detailed error messages for my users.  But I don't want them to be confused by a reference to a line number that is irrelevant to them.

A: if (some_condition)
{
  // will end execution with error
  throw 'Error. My custom error description.';
}

A: This is a reported problem.
Visit Issue 4422, star it to vote and for updates.

A: Use try...catch and the message property of the error object, then return the error message instead of throwing an error. I.E.:
/**
 *
 * @customfunction
 */
function myDiv(dividend,divisor){
  var quotient;
  try{
     quotient = dividend / divisor;
  } catch(error) {
     quotient = error.message;
  } finally {
     return quotient;
  }

}

Reference

*

*https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch

*https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/Error


text:
Q: ClassName has not been declared compiler error, with an inherited cyclic dependence after using pragma once I have three classes: Person, Family and Graph. There is a cyclic dependence between Person and Family and I forward declared Person within Family. They are both included within Graph. When compiling, I am getting a g++ error that states (for every instance of Graph::* within graph.cpp)
" 'Graph' does not name a type " and all data members within graph.h are saying they aren't declared in this scope. (They are all public)
The problem is fixing the compiler error and understanding how to handle this cyclic inherited dependency so that the Graph class is compiled.
I have tried forward declaring Person and Family within Graph as well as using #pragma once.
Family.h
#pragma once
//...

class Family{
   int foo;
};

Family.cpp
#include "person.h"
//...
void Family::functions(){}

Person.h
#pragma once
#include "family.h"
//...
class Person{
   int foo;
};

Person.cpp
#include "family.h"
void Person::functions(){}

Graph.h
#pragma once
#ifndef GRAPH_H
#define GRAPH_H
#include "person.h"
#include "family.h"

class Graph{
   Person * people[NUM_PEOPLE];
   Family * families[NUM_FAMILY];
};

Graph.cpp
//...
class Family;
//...
Graph::Graph(){}
//Here Graph does not name a type

void Graph::GraphFunc1(int someParams){
//Here Graph does not name a type

   //implementation...
   //Lets say somewhere in this function we use people[] and families[]

   people[0] = something;
   families[1] = something;

   //Here families and people are not defined in this scope
   //Although they are declared PUBLICLY in Graph.h
}

I expect the array of object pointers people and families to be defined in the scope of graph.cpp since they are defined publicly in its header. Does this have anything to do with Graph not naming a type? FWIW, the 'Graph does not name a type' compiler error comes up before the others.


text:
Q: How to remove old entries from object I have a JS object that looks like this:
{
'abc': {'time': 1, 'data': 100},
'wad': {'time': 3, 'data': 200},
'gfd': {'time': 2, 'data': 700},
'qwe': {'time': 4, 'data': 344},
}

how can I easily remove the "oldest" X (2 in this case) entries (time 1 & 2) and get the following object:
{
'wad': {'time': 3, 'data': 200},
'qwe': {'time': 4, 'data': 344},
}

A: Sort by time, slice off the first N elements:

const result = Object.fromEntries(Object.entries({
'abc': {'time': 1, 'data': 100},
'wad': {'time': 3, 'data': 200},
'gfd': {'time': 2, 'data': 700},
'qwe': {'time': 4, 'data': 344},
}).sort((a, b) => a[1].time - b[1].time).slice(2))

console.log(result);

A: You can use a method to make your solution dynamic:
Method 1 is:
const removeOldItems = (obj, numbItems) => {
   const keys = Object.keys(obj);
   if(numbItems > keys.length) return; // you can handle this error here
   const updatedKeys = keys.sort((a, b)=>obj[a].time - obj[b].time).slice(numbItems);
   const newObj = {};
   updatedKeys.forEach(k => Object.assign(newObj, {[k]:obj[k]}));
   return newObj;
}

Or method 2 as derived from @dave's answer - if you prefer shortened form:
const removeOldItems = (obj, numbItems) => {
    const keys = Object.keys(obj);
    if(numbItems > keys.length) return; // handle this error here if needed
    return Object.fromEntries(Object.entries(obj).sort((a, b) => a[1].time - b[1].time).slice(numbItems))
  }

Then just call it with any number of old items you want to get rid of:
const obj = {
'abc': {'time': 1, 'data': 100},
'wad': {'time': 3, 'data': 200},
'gfd': {'time': 2, 'data': 700},
'qwe': {'time': 4, 'data': 344},
}
// Using object copies
console.log(removeOldItems({...obj}, 1)) //remove 1 old item
console.log(removeOldItems({...obj}, 2)) //remove 2 old item
console.log(removeOldItems({...obj}, 3)) //remove 3 old item


text:
Q: Compare two same databases and get missing or not actual data in tables I have very specific problem with export Firebird database to another system. Full export takes very long time. My plan is a create copy of database and start with export to new system. Users can continue to write and change data to an uncopied database.
My problem is how to solve missing or updated data in copied database. Is possible to compare those databases and get third database only with new or updated data? After compare missing or updated data, import them to new system. Is there any tool, or command to achieve this?


text:
Q: What happens if an inverter neutral is bonded to earth? My question is similar to this question.
Let's say I bond a true sine DC to AC inverter's neutral wire to my subpanel's neutral (which is bonded to earth in my main panel).
I know most DC to AC inverters don't really generate a negative current for half the AC cycle. 85 V is alternately applied to both the hot and neutral leg.
What will happens if the 85 V energized leg is grounded?
Does a flow of current between my inverter AC outlet neutral and the ground will be observed? Can this damage the unit or will everything be fine and will the potential between the hot and neutral leg be as expected?

A: It's not OK to back-drive your panels like you show without a specialized disconnect (called a "transfer switch").   Reason is, if you are driving power backwards, then the guy working on your pole during a blackout could get electrocuted.  The power company does not trust you to shut off the main breaker first.
It's not safe, don't do it.

A: Most inverters now these days have the FG or G connection as well as a neutral for internal ground fault protection. I am going to assume that the above circuit is simplified, because the normal isolation control circuit is not included in the drawing. Otherwise, the Neutral wire from the inverter would reference its potential to the Utility Neutral and ground. This is a standard affair with earth bonded neutral utility installation.


text:
Q: Building an Autocomplete Form Element with Atlas Search and Django I want to build an autocomplete form in a Django webapp. I have already been able to do the search bar where I query my MongoDB database but how can I add an autocomplete? I tried to adapt an official tutorial that does it with Javascript:
search_similar.html:
{% extends "todo/base.html" %}

{% block content %}

      <form action="{% url 'search_results' %}" method="get">
        <input name="q" type="text" placeholder="Perfume name...">
        <input id="perfumename" type ="submit" value="Find Similar Perfumes" autocomplete="nope"/>
      </form>
      <form class="login-form" action = "similar_results/" method="POST">
        <input type="text" placeholder="perfume name"/>
        {% csrf_token %}
        <input id="perfumename2" type ="submit" value="Find Similar Perfumes" autocomplete="nope"/>
      </form>

{% endblock %}

Even when I have autocomplete="nope" the first search bar still shows up the default autocomplete by chrome and doesn't show up the one I built in MongoDB. The second doesn't show up anything, even when I link the id to the script.


text:
Q: Problems with managing shared ownership of IDisposable objects [There is a similar question Shared ownership of IDisposable objects in C# but the accepted answer suffers from similar design problems which my solution has]
I have been trying to think around this problem having seen many designs taking a blind leap of faith in garbage collector when working in c#. Reason being many times its easy to ignore that one need to handle the IDisposable rather carefully making them close equivalent of resource allocation in c++. I understand that pedantically speaking Dispose is not the equivalent of c++ destructor but if you are holding on to native resources which needs to be cleaned in a deterministic manner it becomes very similar.
But if the object is shared by multiple resources (for eg. an HttpClient object which is meant to be created and used concurrently for performance), who owns the responsibility of calling Dispose since there is no single owner? To solve this problem I came up with a SharedOwner library which has a similar interface as shared_ptr.
Code snippet:
SharedOwner:
public static SharedHandle<T> MakeSharedHandle(Func<T> createSharedOwner)
{
    var obj = new SharedHandle<T>(createSharedOwner());
    return obj;
}

public SharedHandle(T obj)
{
    AddReference();
    m_object = obj;
}

public Handle<T> GetHandle()
{
    AddReference();
    return new Handle<T>(this);
}

internal void Decrement()
{
    if (Interlocked.Decrement(ref m_refCounter) == 0)
    {
        m_object.Dispose();
        m_object = default(T);
    }
}

internal T GetInternalHandler() { return m_object; }

private void AddReference()
{
    Interlocked.Increment(ref m_refCounter);
}

~SharedHandle()
{
    m_object.Dispose();
}

Handle
is a transparent wrapper that manages the ref counting calls keeping that abstracted from consumers.
public sealed class Handle<T> : IDisposable where T : IDisposable
    {
        private SharedHandle<T> m_handle;
        bool disposed = false;
        internal Handle(SharedHandle<T> handle) { m_handle = handle; }

        public void Dispose()
        {
            if (!disposed)
            {
                m_handle.Decrement();
                GC.SuppressFinalize(this);
                disposed = true;
            }
        }

        ~Handle()
        {
            if (!disposed)
            {
                m_handle.Decrement();
            }
        }

The typical usage pattern that I imagined would be:
using (var sharedClient = this.m_sharedClient.GetHandle()) // m_sharedClient is the SharedHandle passed
{
     var httpClient = (HttpClient)sharedClient;
     // use httpClient
}

Now I see two issues with this approach which deviate it from the original motivation of simulating shared_ptr behavior:

*

*The first reference is held by SharedHandle itself. So even when all Handles are out of scope one reference would still be held by SharedHandle thereby making the if block in Decrement unreachable.

*The final Dispose happens when the SharedHandle dies which in lot of sense is no better than not calling Dispose on the underlying object itself. Hence making the solution much less valuable.
I am thinking of moving the reference counting to Handle and using SharedHandle as the control block in shared_ptr but then that means that one may end up with a valid SharedHandle object holding on to a Disposed internal object.
Another alternative that I can think of is making SharedHandle derive from IDisposable and just call Decrement in Dispose. But then this brings other set of design issues. Is there anything that can be done to solve this problem in a more elegant way?


text:
Q: Saving PDF to a Directory I am having trouble saving all my created PDF's in another directory. How can i point it to save all my PDF's in the path of my choosing? I dont understand what i am doing wrong. I have my parameter set to "SavirToDir" but its not saving there. It is saving in the filename_l path.
import os

def makePdf(filepath_l, filename_l,SaveToDir):
        try:
            for fn in filename_l:
                fname, fext = os.path.splitext(fn)
                newfilename = fname + ".pdf"
                im = Image.open(fname + fext)
                os.chdir(SaveToDir)
                im.save(newfilename, "PDF", resolution=100.0)
                print(f"{newfilename} created succesfully!")
                logging.info(f"{newfilename} created succesfully!")
        except Image.UnidentifiedImageError:
            print( f"{fname + fext} found. Skipping UnidentifiedImageError error because this library cannot open a .db file "
            f"and convert it to pdf.")

makePdf(filepath_l,filename_l,r'C:\Users\TEST\COA\misc.fof')

A: Use os.path.join()
def makePdf(filepath_l, filename_l,SaveToDir):
        try:
            for fn in filename_l:
                fname, fext = os.path.splitext(fn)
                newfilename = fname + ".pdf"
                im = Image.open(fname + fext)
                os.chdir(SaveToDir)
                im.save(os.path.join(SaveToDir,newfilename),"PDF", resolution=100.0)
                print(f"{newfilename} created succesfully!")
                logging.info(f"{newfilename} created succesfully!")
        except Image.UnidentifiedImageError:
            print( f"{fname + fext} found. Skipping UnidentifiedImageError error because this library cannot open a .db file "
            f"and convert it to pdf.")

makePdf(filepath_l,filename_l,r'C:\Users\TEST\COA\misc.fof')


text:
Q: macro keystrokes via input file? I am thinking of writing one up but i'll ask first.
Are there any apps that will do keystrokes to an application via an input file? i have a list of 1400 keystrokes i need to do. Basically its 4 numbers a right click, down arrow a few times and enter. I generated the input file so i can easily regenerate it in a way the macro app wants. What app can i use?

A: If you're in Windows you should be able to create an AutoHotkey script that incorporates your keystrokes.
Plus, assign a hotkey, watch for events like a specific window being opened, etc.

A: For BSD/Linux Xnee will do that.


text:
Q: recv_into a numpy array I am transmiting images by sockets from a camera that runs wince :(
The images in the camera are just float arrays created using realloc for the given x * y size
On the other end, I am receiving these images in python.
I have this code working doing
img_dtype = np.float32
img_rcv = np.empty((img_y, img_x),
                   dtype = img_dtype)

p = sck.recv_into(img_rcv,
                  int(size_bytes),
                  socket.MSG_WAITALL)

if size_bytes != p:
    print "Mismatch between expected and received data amount"

 return img_rcv

I am a little bit confused about the way numpy creates its arrays and I am wondering if this img_rcv will be compatible with the way recv_into works.
My questions are:

*

*How safe is this?

*Does the memory allocation for the numpy array will be known for recv_into?

*Are the numpy arrays creation routines equivalent to a malloc?

*It is just working because I am lucky?

A: The answers are:

*

*safe

*yes, via the buffer interface

*yes, in the sense that you get a block of memory you can work with

*no


text:
Q: How to determine the scale of an Image I have an image that I'm using which is 960x1280.  I have coordinates for a rectangle of x:391 y:772, x:574 y:772, x:574 y:870, x:391 y:870 which allows me to put the rectangle in the proper spot IF the image is still 960x1280.  Of course, when I'm in Xcode, the screen size is 375x667.
When drawing the rectangle with the above coordinates, the rectangle is no longer visible.  If just use the screen scale of 3 (UIScreen.main.scale) it's not accurate either.
I create a UIImageView that has constraints of 0 for all four sides and using aspect .fit or .fill.  How do I now know the proper scale of the image so the rectangle is drawn in the right spot?
Thanks


text:
Q: how to export Visual Studio 2013 project into sourcecode Could anyone please help and tell me how to export visual studio project into source code. My client has asked me if they can see a file with source code, so that they are able to recreate the application by using the source code only.
Could you please advise and tell me how I can export the visual studio project into source code, which will include all of the files, code and etc.

A: Are you sure they don't mean check it into source code control?
For example you can link your Visual Studio project up to TFS, check in your code and other developers can download and work on it in Visual Studio
https://www.visualstudio.com/products/visual-studio-team-services-vs
Just a thought


text:
Q: Vcc drops on connecting variable resistor between it and ground I have a VFD with a control board I am trying to fix. It requires an external variable resistor to be connected between the +10V terminal, analog reference terminal and ground. I found that on connecting the VR between the +10V terminal and ground, the voltage at the +10V terminal drops from 10V to around 8.78V. However, a similar board did not behave in this manner. What could possibly be the cause of this?
Many thanks in advance.

A: I can't say what the cause is without more information, but since you ask "What could possibly be the cause of this?" I'll bite...
The cause is that more current is being drawn than the supply can give, so the voltage is drooping. You say that a "similar" board doesn't have the problem--do you mean a board with an identical schematic and layout? If so, the problem is less likely to be with the design, and more likely to be a flaw in the physical board or components.
Start by checking the actual resistance across the resistor. Also, look for things like soldering problems that could cause a partial short between VDD and GND.


text:
Q: How can I block many lines of code in Hive? Hive sql - Is there a way to block out thousands of lines of code without having to put dashes at the beginning of every line?

A: Right now. It doesn't appear so. It is listed as a pending improvement for a future version.
https://issues.apache.org/jira/browse/HIVE-19692


text:
Q: Keep.both example in Akka Stream I would like to understand the Keep.both in akka stream but I could not find an easy on the internet.
Could someone please provide a very simple example about Keep.right and Keep.both.
I tried:
   implicit val system = ActorSystem("KafkaProducer")
    implicit val materializer = ActorMaterializer()

    val source = Source.single("Hello")_
    val sink = Sink.fold[String, String]("")(_ + _)

    val runnable: RunnableGraph[Future[String]] = source.toMat(sink)(Keep.left)
    runnable.run()

I know, it is maybe not a good example and hopefully, someone provide a better example.

A: Simplest scenario, you need a stream to process a bunch of elements that you are going to (1) provide from outside the stream and you need to know when the (2) stream finish processing all elements.
For (1) you could use a Source.queue that is materialized into a queue and you can push elements to it via offer.
val source = Source.queue[String](100,OverflowStrategy.backpressure)

For (2) you could use a Sink.foreach that is materialized into a Future[Done] which will be completed with Success when reaching the normal end of the stream, or completed with Failure if there is a failure signaled in the stream.
val sink = Sink.foreach[String](println)

Then you need to connect source and sink and Keep.both materialized values.
val materializedValues: (SourceQueueWithComplete[String], Future[Done]) = source.toMat(sink)(Keep.both).run()


text:
Q: Regex that gets only initials Is there a way to create a regex for initials without using back references?  For example, say I want initials for

New.York

And the regex to output

N.Y. (or n.y)

So far I have the following:
.\.[a-zA-Z]+

This outputs the last the initial of the first word instead of the first initial: w.y.
UPDATE**
I'm also assigned the RegExp to variable and using the =~ to test some things.

A: You could remove all the lowercase letters using gsub function,
irb(main):004:0> str = "New.York"
=> "New.York"
irb(main):006:0> str.gsub(/[a-z]+/, "")
=> "N.Y"

A: A ruby way to do this given your input of "New.York" could be:
str.split('.').collect { |s| s[0] }.join('.')

which would return 'N.Y'

A: Use this regex and you should only output the groups \1 and \2.
([a-zA-Z])[^.]*\.([a-zA-Z]).*?\b

DEMO
If you want to do a replacement you should use \1.\2

A: You could use the capital letters to dictate the regex match using something like this:
[15] pry(main)> str
=> "New.York"
[16] pry(main)> str.scan(/[A-Z]+/).join('.')
=> "N.Y"


text:
Q: Is it safe to keep Angular 2 and not upgrade? We have a legacy app and it's been using Angular 2.4 since the beginning. Currently package.json is having overrides for many packgages and for our build, we are using npm install --force because of multiple conflicting peer dependency, cannot resolve dependency of some packages, etc. I can foresee that we would keep using override for other dependency update and expanding the package.json.
I'd like to understand:

*

*the risks if we don't upgrade Angular version and keep using Angular 2.4?

*Is it okay to use npm install --force in build/release pipeline in production?

A: Short answer is no
Older versions of packages "decay" over time.

*

*Sometimes because a version of a package had dependencies which are no longer maintained

*or (the worse) because their n-th level dependency is no longer maintained.

*once a version is out of the LTS terms (or deprecated like angular v2 and older are) you also start to loose its documentation.

Then there is the unknowns of having your locked version of a package having to run with newer versions of its dependencies. And you would having to provide some of the fixes yourself.
There are plenty of security issues that the 100's of dependencies a package like angular has and can only be addressed by upgrading.
Your app might still work with forcing dependencies to update. But it would certainly be exposed to a fair bit of know issues which newer versions have already addressed.


text:
Q: Format encrypted/corrupted HDD I got a hard drive which I think is either encrypted or corrupted. When I tried to connect it to my other desktop, my desktop was unable to identify it. Is there any powerful way to detect and format it?

A: I believe GParted Live CD can do the job. You should also try Control Panel -> Administrative Tools->Computer Management.

A: Encrypted disk or partition is not the same as damaged device, it's a total different thing and you can surely see that in any partitioning tool. I don't know what OS you are using, but I'm using debian, and I also have some encrypted volumes on it. Look at the following picture:

So as you can see, you can simply delete or reformat each encrypted volume like it was a normal partition. But if you have no disk at all in your partitioning tool, then device is probably damaged, and you can do nothing.