text:
Q: How to sort a suffix array? I am looking at example suffix arrays and longest common prefixes, but I do not understand the criteria for how the the suffix array is sorted. I am looking at the example on wikipedia where they use banana$ Can someone please explain how a suffix array is sorted?
My first instinct was to sort by length, but that is clearly not the case here.
(Here is the example they used http://en.wikipedia.org/wiki/Suffix_array)
These suffixes can be sorted:
Suffix  i
$       7
a$      6
ana$    4
anana$  2
banana$ 1
na$     5
nana$   3

A: Here is my code template on acm/icpc, using DA algorithm
/*
rank[0...7]: 4 6 8 1 2 3 5 7
string:      a a b a a a a b
-------------------------------------------
 sa[1] = 3 : a a a a b         height[1] = 0
 sa[2] = 4 : a a a b           height[2] = 3
 sa[3] = 5 : a a b             height[3] = 2
 sa[4] = 0 : a a b a a a a b   height[4] = 3
 sa[5] = 6 : a b               height[5] = 1
 sa[6] = 1 : a b a a a a b     height[6] = 2
 sa[7] = 7 : b                 height[7] = 0
 sa[8] = 2 : b a a a a b       height[8] = 1
*/

const int MAXN = 200010;
int r[MAXN],sa[MAXN];
int ua[MAXN],ub[MAXN],uv[MAXN],us[MAXN];
int cmp(int *r,int a,int b,int l)
{return r[a] == r[b] && r[a+l]==r[b+l];}

void da(int *r,int *sa,int n,int m)
{
    int i,j,p,*x = ua,*y = ub,*t;
    for(i=0; i<m; i++)  us[i] = 0;
    for(i=0; i<n; i++)  us[x[i] = r[i]]++;
    for(i=1; i<m; i++)  us[i] += us[i-1];
    for(i=n-1; i>=0; i--)   sa[--us[x[i]]] = i;
    for(j=1,p=1; p<n; j<<=1,m=p)
    {
        for(p=0,i=n-j; i<n; i++)    y[p++] = i;
        for(i=0; i<n; i++)  if(sa[i]>=j) y[p++]=sa[i]-j;
        for(i=0; i<n; i++)  uv[i] = x[y[i]];
        for(i=0; i<m; i++)  us[i] = 0;
        for(i=0; i<n; i++)  us[uv[i]]++;
        for(i=1; i<m; i++)  us[i]+=us[i-1];
        for(i=n-1; i>=0; i--) sa[--us[uv[i]]] = y[i];
        for(t=x,x=y,y=t,p=1,x[sa[0]]=0,i=1; i<n; i++)
           x[sa[i]] = cmp(y,sa[i-1],sa[i],j)?p-1:p++;
    }
}

int rank[MAXN], height[MAXN];
void calh(int *r, int *sa, int n)
{
    int i, j, k = 0;
    for(i=1; i<=n; ++i) rank[sa[i]] = i;
    for(i=0; i<n; height[rank[i++]] = k)
        for(k?k--:0,j=sa[rank[i]-1]; r[i+k]==r[j+k];k++);
}

the time above is O(nlogn)
There is also time in O(n)
You can refer this article: http://www.cs.cmu.edu/~guyb/realworld/papersS04/KaSa03.pdf

A: I also struggled to understand suffix array stuff then I found this intuition behind suffix array and how suffix array with LCP works.
Hope it helps! If you need additional explanation, I will provide here.

A: There is a tutorial on suffix array at http://discuss.codechef.com/questions/21385/a-tutorial-on-suffix-arrays
This tutorial contains things like what is a suffix array? How is it constructed? What is the most efficient way to construct suffix array ? What are its application?
hopefully you will get What you are seeking for..


text:
Q: How to get Python to use a list of answers I give it, to decide if it should go on to the next function I am starting out, so this code may not be as efficient as it could be, but I try. This is a text based game, something happens and the player must decide if he wants to continue or not.
but Everyone is different. so everyone is going to answer with some variation of "yes". How can I get the program to move on if someone types any variation of "yes" the commas give me a syntax error, and i don't know how else to get it to separate the possible answers.
def continueyn():

    option1_des1 = raw_input("> ")

    if option1_des1 == "yes", "Yes", "forward", "Forward", "Full impulse", "Full Impulse", "yeah", "yup", "Yup", "Yeah":
        gravityp1()
    elif option1_des1 == "no":
        bearing(), userinput()
    else:
        print "Sorry Captain, I didn't get that. What did you say?"
        continueyn()

A: Using 'or', as pointed out in the comments is incorrect. The correct way to go ahead through this would be either using lists and a loop, or iterating using "in":
Method 1:
option1_des1 = raw_input("> ")
if option1_des1 in {"yes", "Yes", "forward"} :
    print "yes"
elif option1_des1 == "no":
    print "no"
else:
    print "Sorry Captain, I didn't get that. What did you say?"

Method 2:
You can also make a list and then go across values of the list like this-
flag=True
yesList = ['yes', 'Yes', 'forward']
option1_des1 = raw_input("> ")

for element in yesList:
    if option1_des1 == element:
        print "yes"
        flag=False
        break;

if option1_des1 == "no" and flag:
    print "no"
elif flag:
    print "Sorry Captain, I didn't get that. What did you say?"

Even better, you can use regex to match several variations of one type instead of figuring out every permutation. The xample below only covers "yes", but you can make a list of words like in method 2.
import re

pattern = 'yes'
option1_des1 = raw_input("> ")
matchObj = re.search(pattern, option1_des1, re.I)
if matchObj:
    print "yes"
elif option1_des1 == "no":
    print "no"
else:
    print "Sorry Captain, I didn't get that. What did you say?"

A: Similar to sbhatla's answer you could use a list and use the built in "in" function which returns as a boolean.
yesoptions = ["yes", "Y", "etc"]
if option_des1 in yesoptions:
    #runs actions for a yes answer
elif option in:
    etcetc
else:
    etc..

redpajama_set_name: RedPajamaStackExchange


text:
Q: 80's alien movie: young boy finds and protects a glowing alien green rock which becomes his friend I've been trying to remember the name of this movie that I watched when I was really young. It's a kids movie about a young boy who finds a green rock/stone, which is an alien, and then has to run from the bad guys in order to protect his alien/rock friend.
It was a glowing green stone and I think somehow it communicated with the boy and it had some sort of powers.
The only other thing I remember is that the alien leaves in the end and the boy gets really sad.
It's definitely not E.T., I don't think the movie was a huge hit. It's also possible the movie is from the 70's.

A: "The Magic Crystal" (1986)?
This sounds like the one. You didn't say if it was an Asian film but this one was made in Hong Kong. Here is a plot summary from IMDb:

Looking to cash in on the popularity of Steven Spielberg's mega-hits
E.T. and Raiders of the Lost Ark, Hong Kong schlockmeister Wong Jing
directs this yarn about Andy who, along with buddies Pin-pin and
Pancho ventures to Greece to find his long lost friend Shen. They soon
discover Shen is being tailed both by the KGB and by Interpol after
discovering some rare gems in an archaeological dig. After a unkindly
series of events, Andy winds up back in Hong Kong with the stones,
which, it turns out, is not gems but rather an alien life form.
Meanwhile Karov, an evil magician, is hell bent on getting his hands
on the gem/alien no matter what.


text:
Q: Python, numpy, matrix A=[['2' '7' 'fas']
 ['4' '8' 'sda']
 ['1' '5' 'daf']
 ['2' '24' 'gag']]

How can I get just matrix A, instead last "atribute" in each row:
A=[['2' '7']
 ['4' '8']
 ['1' '5' ]
 ['2' '24']]

I know that last element in row is [:-1]
I tried with numpy:
A[:,  ?? ]

Matrix A is random elements, so I was thinking somethin in this way: A[:,end-1], but numpy don't know what is end

A: >>> arr=np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> arr[:,:-1]
array([[1, 2],
       [4, 5],
       [7, 8]])

A: >>> A = [ ['2', '7', 'fas']
        , ['4', '8', 'sda']
        , ['1', '5', 'daf']
        , ['2', '24', 'gag']
        ]

>>> [ x[:-1] for x in A ]
[['2', '7'], ['4', '8'], ['1', '5'], ['2', '24']]


text:
Q: How do you know when to return false from a jQuery function? "return false" seems to work in the submitHandler but I'm not sure why.
function submitHandler() {
    $.post($(this).attr('action'), $(this).serialize(), null, "script");
    return false;
}

$(document).ready(function () {

    $('#top_cat').submit(submitHandler);

    $("#tip_click").click(function() {
        $("#high_hat").submit(submitHandler);
    });

});

I'm also not sure if I need to add a "return false" in the #tip_click function so that it reads like this:
    $("#tip_click").click(function() {
        $("#high_hat").submit(submitHandler);
        return false;
    });

What's the rule to follow here regarding when to "return false"?

A: You should return false when:

*

*You want to prevent the default event action

*

*The onsubmit event for example, the default action of this event is send the form data to the server, or an onclick event on an anchor element, the default event action is to follow the anchor's HREF.

*You want to stop the event bubbling.
Returning false from an event handler, is like executing both event.preventDefault(); and event.stopPropagation();.


text:
Q: tar append to file in archive Good morning,
I have a tar compressed archive tar.bzip2 (created using tar jcf), which contains a file named data.txt (1).
On the other side, I have another file also named data.txt (2).
Is there a way to append file (2) to the end of file (1) without untar bz2 archive, append file and then tar it back again?
By the way, I already did the three steps, I'm asking just for curiosity (or 'out of curiosity'... not sure about this expression in English).
I've been looking for the right option, but I cannot find it out:

*

*-r option tells me 'abort', I guess because I tried to append a file which already exists in archive.

*-u cannot update compressed archives, although I think it will only replace (1) by (2).

*-A also tells me 'abort'. I'm not really sure what this option does. It seems to add the files in one archive to another existing archive. So it's not what I want.

I'm using GNU tar 1.15.1 over Linux.
Note:
I think I didn't explain it well enough, so I better use an example:
I have a file named data.tar.bz2 which contains a file named data.txt (1). Its contents could be

A

I have another file also named data.txt (2). Its contents could be

B

My purpose is that the file contained in data.tar.bz2 has both (1) and (2) file contents in one file named, of course, data.txt:

A
  B

In other words do this using one command, without decompressing, untar, create temporal directories, etc...:
mkdir $tempDir
tar jxf data.tar.bz2 -C $tempDir
cat data.txt >> $tempDir/data.txt
tar jcf data.tar.bz2 -C $tempDir data.txt
rm -r $tempDir

Yes, I want to append, but -r option won't work because, if I'm not wrong, it appends files to archive, but it does not append the contents of an existing file in the archive. Hope this clarifies... not sure at all xD

A: If data.txt is the only file in the tar archive, you could append directly, simply by not using tar at all:
$ echo Hello | bzip2 > data.txt.bz2
$ echo Stack | bzip2 >> data.txt.bz2
$ echo Exchange | bzip2 >> data.txt.bz2
$ bunzip2 < data.txt.bz2
Hello
Stack
Exchange

A: You can append files to a non-compressed tar archive with the --append switch, for example:
$ tar --append --file=tarfile.tar data.txt

Beware the consequences of adding multiple files of the same name to an existing archive :
http://www.gnu.org/software/tar/manual/html_node/append.html
You cannot, as far as I am aware, append or update files in a compressed archive without first decompressing it.

A: I can think only of the Archivemount utility to do that.
1) Install archivemount (if its not already available on your machine). Its available in the EPEL repo.
2) Use the archivemount command to mount your tar file on any of the directories in your machine.
archivemount xyz.bzip2 /path/to/a/directory/
Once mounted, you will be able to browse through the archive as if it is a regular directory. From there, you can edit/update or append content to your file which is in the archive.
Here you have more details about using archivemount and below is a snippet from my server when I archivemounted a bzip2 file.
[root@server usr]# df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/xvda1       15G  9.0G  5.1G  64% /
none            245M     0  245M   0% /dev/shm
[root@server usr]# archivemount puppet_codes.bzip2 /usr/local/archtest/
[root@server usr]# df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/xvda1       15G  9.0G  5.1G  64% /
none            245M     0  245M   0% /dev/shm
archivemount   1000G     0 1000G   0% /usr/local/archtest
[root@server usr]# ls /usr/local/archtest
puppet_codes
[root@server usr]# cat /usr/local/archtest/puppet_codes/emaillist.txt
sreewave@example.com
sreewave@example.org
[root@server usr]#

The following is the package I have installed on my server.
[root@server ~]# rpm -qi archivemount-0.8.1-2.el6.x86_64
Name        : archivemount                 Relocations: (not relocatable)
Version     : 0.8.1                             Vendor: Fedora Project
Release     : 2.el6                         Build Date: Sun Oct 13 17:06:30 2013
Install Date: Wed Dec 17 13:45:01 2014         Build Host: buildvm-04.phx2.fedoraproject.org
Group       : System Environment/Libraries   Source RPM: archivemount-0.8.1-2.el6.src.rpm
Size        : 70774                            License: LGPLv2+
Signature   : RSA/8, Sun Oct 13 18:43:34 2013, Key ID 3b49df2a0608b895
Packager    : Fedora Project
URL         : http://www.cybernoia.de/software/archivemount/
Summary     : FUSE based filesystem for mounting compressed archives
Description :
Archivemount is a piece of glue code between libarchive and FUSE. It can be
used to mount a (possibly compressed) archive (as in .tar.gz or .tar.bz2)
and use it like an ordinary filesystem.


text:
Q: Disable WiFi from Multi Peer Connectivity I have gone over the documentation, but there isn't much information on Multipeer Connectivity related to choosing a possible medium for peers to connect.
Multipeer Connectivity automatically discovers peers based on WiFi, or Bluetooth. Is there a way to limit this to only Bluetooth?

A: As @kdogisthebest correctly states, there's no way to force Multipeer Connectivity to use a particular network technology, but as your question relates to a particular problem with WiFi, this answer details what I'm doing to work around that.
I've worked around the issue of 'phantom' peers over WiFi by sending a shortened timestamp in the discoveryInfo when creating the MCNearybyServiceAdvertiser. There are several caveats here:
1) This solution assumes both devices have the same time. I ensure this by using a modified version of ios-ntp as the app's time source.
2) It also assumes that Advertising and Browsing do not run for too long. I have a set length of 60 seconds for discovery phases, and I completely re-init the browser/advertiser on each restart.
3) MPC doesn't seem to like too many bytes in the discoveryInfo so sending an NSTimeInterval based on epoch doesn't work. I had to truncate them.
So when my app enters discovery mode, it starts browsing and advertising simultaneously. The advertising code looks like:
- (void)startAdvertising {

    if (_advertising){
        NSLog(@"Already advertising");
        return;
    }

    self.acceptedPeerIDNameMap = [NSMutableDictionary dictionary];

    NSInteger timeStamp = [self shortenedNetworkTimeStamp];
    NSDictionary *discoveryInfo = @{kAdvertisingDiscoveryInfoTimestampKey:[NSString   stringWithFormat:@"%ld",(long)timeStamp]};

    NSLog(@"Starting advertiser");

    self.serviceAdvertiser = [[MCNearbyServiceAdvertiser alloc] initWithPeer:_myPeerID
                                                           discoveryInfo:discoveryInfo
                                                             serviceType:kServiceType];
    _serviceAdvertiser.delegate = self;

    [_serviceAdvertiser startAdvertisingPeer];

    self.advertising = YES;
}

The method shortenedNetworkTimestamp just takes an NSTimeInterval (either using the ntp framework or timeIntervalSinceReferenceDate and removing 1400000000 from it.
Then when the browser discovers a peer, it checks whether the advertiser's timestamp is within the known discovery duration (in my case 60 seconds):
- (void)browser:(MCNearbyServiceBrowser *)browser foundPeer:(MCPeerID *)peerID withDiscoveryInfo:(NSDictionary *)info {

    DLog(@"Browser found peer ID %@",peerID.displayName);

    //Only one peer should invite the other
    BOOL shouldInvite = [peerID.displayName compare:_myPeerID.displayName]==NSOrderedAscending;

    //Don't re-send invitations
    if (_peerInfoDisplayNameMap[peerID.displayName]){
        DLog(@"Already connected to peerID %@",peerID.displayName);
        shouldInvite = NO;
    }
    else if (_invitedPeerIDNameMap[peerID.displayName]){
            DLog(@"Already invited peerID %@",peerID.displayName);
            shouldInvite = NO;
    }

    //Invite if discovery info is valid
    if (shouldInvite && [self discoveryInfoIsValid:info]) {

        DLog(@"Inviting");

        _invitedPeerIDNameMap[peerID.displayName] = peerID;

        MCSession *session = [self availableSession];
        [_serviceBrowser invitePeer:peerID toSession:session withContext:nil timeout:0];
    }
    else {
        DLog(@"Not inviting");
    }
 }

The discovery info validity check is pretty simple - just make sure the timestamp sent in the info is inside of the discovery time range (in my case kDiscoveryPhaseDuration is 60 seconds):
- (BOOL)discoveryInfoIsValid:(NSDictionary *)info {

    BOOL isValid = YES;

    NSString *infoTimeStamp = info[kAdvertisingDiscoveryInfoTimestampKey];
    NSTimeInterval sentTimeStamp = (infoTimeStamp) ? [infoTimeStamp doubleValue] : -1;
    NSTimeInterval currentTimeStamp = [self shortenedNetworkTimeStamp];

    if (sentTimeStamp==-1 || (currentTimeStamp - sentTimeStamp) > kDiscoveryPhaseDuration){
        DLog(@"Expired discovery info (current=%f, sent=%f)",currentTimeStamp,sentTimeStamp);
        isValid = NO;
    }

    return isValid;
}

Hopefully this helps. There are many other quirks in MPC that I'm handling in my own code but I think the above covers this specific problem.

A: This isn't possible with Multipeer Connectivity. There are no methods Apple puts in place to limit the connection to Bluetooth.
One answer here: Multipeer connectivity over Bluetooth? states "There is no explicit setting for bluetooth or Wifi, It will connect devices in whatever possible way they are available."


text:
Q: How to create my own probability density function and get a random retrun of x in Python I'm now trying to create a function which will return a random x based on my own probability function:
y = m/pow(x,n)
m and n are values determined by user.
x belongs to [m,m+2]
I wish it can return a random number x based on the posibility.
Just as calling:
from numpy.random import exponential
temp = exponential(scale = 5)

temp will be a random number.
As my funciton is not a standerd function, so I try to use scipy.stats.rv_continuous to create a PDF function.
Here is my code:
from scipy import stats
m = 0.1
n = 2.3
class DK(stats.rv_continuous):
def _pdf(self, x, m,n):
   return m/pow(x,n)

mydist = DK(moment = 0,a = m,b = m + 2)

And as you can see, I don't know how to send the parameters: m and n into the function
I take a look at the scipy.stats.rv_continuous instuctions but can't find the solution.
Does anyone know how to send the parameters into the function?
Or anyone know other ways to reach my goal? Thanks a lot.

A: Use Inverse transform sampling to do the work.
[1] :https://en.wikipedia.org/wiki/Inverse_transform_sampling


text:
Q: Strange cache of an output file I've got a specific problem in my C# solution. There are three projects: MainProgram, Install, FileBrowser (Output type: Class Library - DLL).
When I rebuild the FileBrowser, VS generates a new, up-to-date file FileBrowser.dll in the output directory, everything's OK.
But (here begins the problem), when I rebuild an entire solution, or even just one of the other projects (both require building FileBrowser first), FileBrowser.dll restores to the earlier version from 2015-04-11 4:54 PM. Exactly this datetime is in the file's "Last modified" property.
I really do not remember if that day I did something really "special" so VS cached the output file from then and now it still annoys me with its copies.
How can I fix this? Where this old file FileBrowser.dll could be stored? I did use a Windows search option (Win 7) but it seems that file must have another name in the cache.

A: This should fix your problem:

*

*Remove the reference of FileBrowser.dll

*Add reference for FileBrowser project.

How did it happen?
Initially you were adding a reference to FileBrowser.dll, the ide cashed that dll in one of the directories of your solution and copying it to the output directory. what you really needed is a reference to the output of the FileBrowser Project which is again FileBrowser.dll - but a reference to the project so you can get the latest complied version each time you build the solution.


text:
Q: Determining if a file exists and finding a string in a line of a file (.txt) and returning true or false if found Java HW This is my first time asking a question on stackoverflow. I've been stumped with this question for the longest time now and I do know what's wrong with my code. Any help/suggestions would be much appreciated. Thank you.
Q1: Write a public static method named q1 that takes no parameters and has return type boolean. This method will attempt to open a file named school.txt and returns true if the file exists and contains the String "test" as a sub-String on any line, and false if "test" is not found. This method will also return false if "school.txt" does not exist.
public static boolean q1() {

    try{
        String fileName = "";

        if(fileName == "school.txt");{
            for(String line : Files.readAllLines(Paths.get("school.txt"))){
                String[] data = line.split(",");{

                    for(int i = 0; i< data.length; i++) {
                        if(data[i].contains("test"));{
                            return true;
            }
        }
                }
            }
        }
    } catch (IOException ex){
          ex.printStackTrace();
    }
    return false;
}

A: Besides having the semicolon by the end of your if (which means if is not gonna be used), you have used contains(). If your file is just words being separated by colons, you should use data[i].equals("test"). So if your file is like the below file, equals() will do the charm.

hello, world, test, bye,

But if your file is something like this:

hello world, test is in progress, viva la vida, bye,

you need to examine each word separately, so you need to write a method to check each data[i] for the word test.
In any of the cases above, use trim() method so your String will not contain any white spaces so it could be compared with test.

A: why used ; after if statement it will terminate the condition and when you will set the file name as you initialize with String filename=""; so better to pass the name of file in q1() method
comparing the string with == is not recommended use equals method instead
public static boolean q1(String fileName) {

        try{
            //String fileName = "";

            if(fileName.equals("school.txt")){/*no need to put ; otherwise it will terminate here*/
                for(String line : Files.readAllLines(Paths.get("school.txt"))){
                    String[] data = line.split(",");

                    for(int i = 0; i< data.length; i++) {
                        if(data[i].contains("test")){
                            return true;
                        }
                    }

                }
            }
        } catch (IOException ex){
            ex.printStackTrace();
        }
        return false;
    }

A:     public static boolean q1()
    {
        try
        {
            String fileName = ""; //you create this, but never set it to anything else, and only use it once, in an operation that does nothing.  might as well not be here

            if (fileName == "school.txt") ; //you have an if statement that will never evaluate to "true" followed by a ; this line essentially does nothing and might as well not be here
            {//unnecessary bracket
                for (String line : Files.readAllLines(Paths.get("school.txt")))// You are reading in all the lines, don't see a logic problem here
                {
                    String[] data = line.split(",");//why are you splitting the lines?  The problem statment says nothing about that.
                    {

                        for (int i = 0; i < data.length; i++)// iterating through each line
                        {
                            if (data[i].contains("test")) ;// another semicolon directly after the if, line might as well not be here
                            {// unnecessary bracket
                                return true;
                            }//closing of unnecessary bracket
                        }
                    }
                }
            }//closing of unnecessary bracket
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
        return false;
    }

So let's clean this up, remove all the stuff that does nothing, and see if you can find the bug
public static boolean q1()
{
    try
    {
        for (String line : Files.readAllLines(Paths.get("school.txt"))) // You are reading in all the lines, don't see a logic problem here
        {
            String[] data = line.split(","); //why are you splitting the lines?  The problem statment says nothing about that.
            {
                for (int i = 0; i < data.length; i++) // iterating every line
                {
                    return true; //returning true
                }
            }
        }
    }
    catch (IOException ex)
    {
        ex.printStackTrace();
    }
    return false;
}


text:
Q: Paging async iterator protocol is not available (Azure SDK for Python) What I'm trying to achieve
I'm trying to automate subscription and resource group creation on Azure using the Python SDK.
To do that, I need a Service Principal Account (Client Id; Client Secret; Tenant Id) with Permissions to at least retrieve Enrollment Accounts and create the subscriptions and resource groups.

How I'm trying to achieve it
I tried listing the enrollment accounts without success (yes, I'm importing azure.mgmt.billing, azure.mgmt and azure.common, among others)

*

*First I instantiate the client:
billing_client = azure.mgmt.billing.BillingManagementClient(credentials, subscription_id)

*Then I tried printing the results in two different ways:
# A
print(list(billing_client.enrollment_accounts.list()))

# B
for enrollment_account in billing_client.enrollment_accounts.list():
    print(enrollment_account)

What problem am I facing?
The problem I'm experiencing is that I get the following error:

Paging async iterator protocol is not available for EnrollmentAccountPaged

This also happens with other list() methods, like when I retrieve resource groups using something like
rm_client = ResourceManagementClient(credentials, subscription_id)
resource_groups = rm_client.resource_groups.list()

Then, I get the error:

Paging async iterator protocol is not available for ResourceGroupPaged

How would I consider my problem solved?
I'd love to know why I'm getting this error, and how to fix it. The example code from Azure doesn't use the methods or objects in a different way.

How's the environment?
Python version: Python 3.7
Packages:
Package Version Latest Version
PyJWT   1.6.4   1.6.4
adal    1.1.0   1.1.0
asn1crypto  0.24.0  0.24.0
azure-common    1.1.16  1.1.16
azure-mgmt  4.0.0   4.0.0
azure-mgmt-advisor  1.0.1   1.0.1
azure-mgmt-applicationinsights  0.1.1   0.1.1
azure-mgmt-authorization    0.50.0  0.50.0
azure-mgmt-batch    5.0.1   5.0.1
azure-mgmt-batchai  2.0.0   2.0.0
azure-mgmt-billing  0.2.0   0.2.0
azure-mgmt-cdn  3.0.0   3.0.0
azure-mgmt-cognitiveservices    3.0.0   3.0.0
azure-mgmt-commerce 1.0.1   1.0.1
azure-mgmt-compute  4.3.0   4.3.0
azure-mgmt-consumption  2.0.0   2.0.0
azure-mgmt-containerinstance    1.2.0   1.2.0
azure-mgmt-containerregistry    2.2.0   2.2.0
azure-mgmt-containerservice 4.2.2   4.2.2
azure-mgmt-cosmosdb 0.4.1   0.5.0
azure-mgmt-datafactory  0.6.0   0.6.0
azure-mgmt-datalake-analytics   0.6.0   0.6.0
azure-mgmt-datalake-nspkg   2.0.0   3.0.0
azure-mgmt-datalake-store   0.5.0   0.5.0
azure-mgmt-datamigration    1.0.0   2.0.0
azure-mgmt-devspaces    0.1.0   0.1.0
azure-mgmt-devtestlabs  2.2.0   2.2.0
azure-mgmt-dns  2.1.0   2.1.0
azure-mgmt-eventgrid    1.0.0   1.0.0
azure-mgmt-eventhub 2.1.0   2.1.0
azure-mgmt-hanaonazure  0.1.1   0.2.1
azure-mgmt-iotcentral   0.1.0   0.2.0
azure-mgmt-iothub   0.5.0   0.6.0
azure-mgmt-iothubprovisioningservices   0.2.0   0.2.0
azure-mgmt-keyvault 1.1.0   1.1.0
azure-mgmt-loganalytics 0.2.0   0.2.0
azure-mgmt-logic    3.0.0   3.0.0
azure-mgmt-machinelearningcompute   0.4.1   0.4.1
azure-mgmt-managementgroups 0.1.0   0.1.0
azure-mgmt-managementpartner    0.1.0   0.1.0
azure-mgmt-maps 0.1.0   0.1.0
azure-mgmt-marketplaceordering  0.1.0   0.1.0
azure-mgmt-media    1.0.0   1.0.0
azure-mgmt-monitor  0.5.2   0.5.2
azure-mgmt-msi  0.2.0   0.2.0
azure-mgmt-network  2.2.1   2.2.1
azure-mgmt-notificationhubs 2.0.0   2.0.0
azure-mgmt-nspkg    3.0.2   3.0.2
azure-mgmt-policyinsights   0.1.0   0.1.0
azure-mgmt-powerbiembedded  2.0.0   2.0.0
azure-mgmt-rdbms    1.3.0   1.3.0
azure-mgmt-recoveryservices 0.3.0   0.3.0
azure-mgmt-recoveryservicesbackup   0.3.0   0.3.0
azure-mgmt-redis    5.0.0   5.0.0
azure-mgmt-relay    0.1.0   0.1.0
azure-mgmt-reservations 0.2.1   0.3.0
azure-mgmt-resource 2.0.0   2.0.0
azure-mgmt-scheduler    2.0.0   2.0.0
azure-mgmt-search   2.0.0   2.0.0
azure-mgmt-servicebus   0.5.2   0.5.2
azure-mgmt-servicefabric    0.2.0   0.2.0
azure-mgmt-signalr  0.1.1   0.1.1
azure-mgmt-sql  0.9.1   0.9.1
azure-mgmt-storage  2.0.0   3.0.0
azure-mgmt-subscription 0.2.0   0.2.0
azure-mgmt-trafficmanager   0.50.0  0.50.0
azure-mgmt-web  0.35.0  0.40.0
azure-nspkg 3.0.2   3.0.2
certifi 2018.8.24   2018.8.24
cffi    1.11.5  1.11.5
chardet 3.0.4   3.0.4
cryptography    2.3.1   2.3.1
idna    2.7 2.7
isodate 0.6.0   0.6.0
msrest  0.6.0   0.6.0
msrestazure 0.5.0   0.5.0
oauthlib    2.1.0   2.1.0
pip 10.0.1  18.1
pycparser   2.19    2.19
python-dateutil 2.7.3   2.7.3
requests    2.19.1  2.19.1
requests-oauthlib   1.0.0   1.0.0
setuptools  39.1.0  40.4.3

A: This is a log warning to tell you that this package is not ready to support async syntax, and this is true, we released the first part of the runtime in msrest 0.6.0, but we didn't released any packages with async support yet.
For reference that it's just a warning:
https://github.com/Azure/msrest-for-python/blob/master/msrest/async_paging.py#L40
It will not impact any code and will not raise any exception. You will get a problem only if you try to use async for of async syntax (because as the warning tells you, it's not ready for).
When we'll start shipping async compatible packages by the end of this year, this warning will disappear automatically as more and more package becomes ready.
If this warning is really a problem for you, you can disable the logger "msrest.async_paging" or pin msrest to 0.5.5 (before async core support).
Feel free to open an issue on our tracker if you feel this is really a massive problem, and depending on how many people I get bad feedback, I might change it to debug for a few months. But once async packages will be released, it will be an important source of feedback and I truly think it would deserve a warning.
https://github.com/Azure/azure-sdk-for-python/issues
Thank you for your feedback!
(I own this code at Microsoft).
Edit: Being that you're not the only one with questions about this, I released a 0.6.1 that removes this warning.


text:
Q: How Thread works in java? I have written this code in Java but I can't understand why the output isn't what I expect.
Can anyone explain why Apples and Oranges are cluttered and they are not listed one by one?
package first_experiment;

class Orange extends Thread{

    public void run (){
        for ( int i=1 ; i<21 ; i++)
            System.out.println( i + " - Orange");
    }
}

class Apple extends Thread{

    public void run(){
        for (int i =1 ; i <11 ; i++)
            System.out.println( i + " - Apple");
    }
}

public class one{
    public static void main (String args[]){
        Thread O = new Orange();
        Thread A = new Apple();

        O.start();
        A.start();
    }
}

A: The two threads run at the same time.  It's up to the JVM to decide which order they get printed out in, and you cannot rely on the order being predictable.

A: You are creating 2 threads that run concurrently. The order of execution is unknown (since both have the same priority). Note that if PrintStream#println() is not synchronized then the output would be something like:
12 - - A ppOranlgee
// and so on

A: If you want the results to appear in a particular order, use one thread in a loop.
If you use multiple threads you want them to start and run in any order as much as possible.
Your threads are so short lived, they are running to completion before the other one can start.
BTW: You PC can perform 100,000,000 operations in the time it takes you to blink, and starting a new thread takes time.

A: Threads run as seperate and indipendant streams of execution.  You might loop through several Apples before the first Orange gets some CPU time.  Also, if you are on a multiprocessor system, it is possible for both to be running concurently.
If you want them to coordinate their output, you would need to use wait() and notify().

A: Threads in java are processes running independently when started, one line of started thread code is executed a time with no specific order of execution between threads.
The above code will display in console count - Orange and count - Apple randomly.

A: The threads may start in any order but the results will be cluttered because System.out.println synchronizes the Thread access to it and as such then are executed one after another for printing.
To see truly random output, save the data in a List and then later print the contents of the List.


text:
Q: how to debug jsp and javascript file in eclipse? My project containing java files, applets, jsp and javascript file. I am able to debug applet and java files But not able to configure the debug setup for jsp and javascript files in eclipse.
I tried debug using F12 tools throw browser IE10 but those files are not coming under the project.
please mention the steps for configuring the debug setup
Thanks,

A: Since the Javascript is executed on browser, Eclipse won't be able to debug it, unless it has some way to connect to the browser. You can try using AJAX Toolkit Framework, however, it's best to use internet browser's built-in debugger. You can also have a look at Aptana.
If your javascript files are not appearing in the IE debugger:

*

*Check if the javascript files are included properly.

*Try debugger on Chrome or Firefox (or with Firebug extension on
Firefox)

Also, you will not be able to place a debug pointer in JSP file unless it's placed in JAVA scriptlet part of JSP.


text:
Q: Who is Data's creator? I am kind of new to Star Trek: The Next Generation, and when I discovered Data and wondered: who is his creator? I haven't watched all the episodes and would like to know who created Data. Just a bonus, what is Data made of/or what is his programming?

A: Technically speaking, there were two creators
In TNG 'Datalore', we learn from Lore and some pretty strong evidence down on Omicron Theta that Data was created by Dr Noonien Soong.  And in TNG 'Inheritance', we learn there was another:

JULIANA: Oh, Data, I was there, right at the beginning on Omicron Theta. I helped create you. Now look at you.

(Source)
So, technically speaking, Data was created by two people: Dr Noonien Soong and Dr Juliana Tainer (then Soong).

A: Memory Alpha (Star Trek Wiki site) is your best resource for all things Star Trek.
MA's Data article tells you what you need:

Data was the fifth of six known androids designed by Dr. Noonian Soong. He was built on the planet Omicron Theta around 2336, after Lore was deactivated, and over the protests of Soong's wife Juliana. Soong claimed he built Data to perfect his design of his androids, and when Data was perfected, apply his improvements to Lore.

Bonus answers (but you should never post >1 question per post on SE, so I will only answer one):

He was composed of 24.6 kilograms of tripolymer composites, 11.8 kilograms of molybdenum-cobalt alloys and 1.3 kilograms of bioplast sheeting. (TNG: "The Most Toys") ... All told, he weighed approximately one hundred kilograms. (TNG: "Inheritance") Data's upper spinal support was a polyalloy designed to withstand extreme stress. His skull was composed of cortenide and duranium. (TNG: "The Chase")

Further details on Data and similar androids are on http://en.memory-alpha.org/wiki/Soong-type_android


text:
Q: prevent user from creating password from his last 4 passwords I'm working on rails in mvc framework and i want to prevent user to create password from last 4 passwords.
here is what i have done so far,actually I was following that code of someone from github but it seems he didn't have mentioned encrypted_password_changed function and encrypted_password function.
Password Histories Table
class CreatePasswordHistories < ActiveRecord::Migration
  def self.up
    create_table(:password_histories) do |t|
      t.integer :user_id
      t.string  :encrypted_password
      t.timestamps
    end
  end

  def self.down
    drop_table :password_histories
  end
end

User Model
class User < ApplicationRecord
  include ActiveModel::Validations

  has_many :password_histories
  after_save :store_digest
  validates :password, :unique_password => true

  private

  def store_digest
    if encrypted_password_changed?
      PasswordHistory.create(:user => self, :encrypted_password => encrypted_password)
    end
  end
end

Custom Validator
require 'bcrypt'
class UniquePasswordValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    record.password_histories.each do |ph|
      bcrypt = ::BCrypt::Password.new(ph.encrypted_password)
      hashed_value = ::BCrypt::Engine.hash_secret([value, Devise.pepper].join, bcrypt.salt)
      record.errors[attribute] << "has been used previously." and return if hashed_value == ph.encrypted_password
    end
  end
end


text:
Q: Posting data from one page to another I am using VueJS for the first time and enjoying it.  I am trying to POST to a page, GET works fine
In my routing file I have all the routes mapped out, I am trying to post to Contracts
{ path: '/contract/:id',
      name: 'Contract2',
      component: Contract,
      props: true
    },

If I do a GET /contract?id=1 or /contract/1 both work with GET
But POST (Postman for instance)  I get
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Error</title>

Cannot POST /contract/

My VueJS posting code (the redirect is not working either)
loadContract: function(contractId) {

      axios
        .post("/contract", {
          id: contractId
        })
        .then(function(response) {
          console.log(response);
          //REDIRECT TERE
          //router.go("/contract");
        })
        .catch(function(error) {
          console.log(error);
        });
    },

A: What do you mean post to another page? If you're talking about passing data between pages with vue-router, you can actually pass params when you do a programmatic navigation. Please read up on it here
Example:
router.push({ name: 'contract', params: { contractId: 123 }})


text:
Q: What is the purpose of constructor references in Kotlin I am reading the book Kotlin in action and I ask myself what is the purpose of "creating an instance of a class using a constructor reference" (page 112 if anyone is interested and has the book at home).
Here is the code example from the book:
data class Person(val name: String, val age: Int)

val createPerson = ::Person
val p = createPerson("Alice", 29)

println(p) // Person(name=Alice, age=29)

I think it looks like an factory method call, but I dont think that this is the (only) purpose of the method reference here.

A: A constructor when referenced this way is just like any other function reference. It has inputs (the parameters) and a return value (a new instance of the class). You can pass it to a higher-order function that has a function parameter or some kind of factory.
For example:
class MessageWrapper(val message: String)

val someStrings = listOf("Hello world")

You could convert your list to have the wrapper type like this by using a lambda:
val someMessages: List<MessageWrapper> = someStrings.map { MessageWrapper(it) }

but it is possibly clearer to skip wrapping your function in another function by passing the constructor directly.
val someMessages: List<MessageWrapper> = someStrings.map(::MessageWrapper)

The improvement in clarity is more apparent with functions and parameters than it is with constructors, though. It also can help avoid shadowed its by avoiding nested lambdas.

A: References to constructors are the part of Kotlin Reflection API. You can create an instance of a class through constructor reference even if that class is not even in your project (you get that reference from outside). Reflection is widely used by many libraries and frameworks (for example, GSON) that know nothing about your code but still are able to create instances of your classes.


text:
Q: IndentationError when running manage.py runserver Django When I run python manage.py runserver on PowerShell, I got the following error:
File "C:\Python27\lib\site-packages\django\utils\importlib.py", line
__import__(name)
IndentationError: unexpected indent

However, I have NEVER touched that file before and when I opened that file in Notepad++ it shows
this:
if name.startswith('.'):
    if not package:
        raise TypeError("relative imports require the 'package' argument")
    level = 0
    for character in name:
        if character != '.':
            break
        level += 1
    name = _resolve_name(name[level:], package, level)
    __import__(name)  #LINE 35
return sys.modules[name]`

What seems to be problematic? I am working on Windows Vista x32 with Python 2.7 and Django 1.4.2
I appreciate your help.
Here's the database information under settings.py:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'demo',                      # Or path to database file if using sqlite3.
        'USER': '****',                      # Not used with sqlite3.
        'PASSWORD': '*****',                  # Not used with sqlite3.
        'HOST': '127.0.0.1',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '3306',                      # Set to empty string for default. Not used with sqlite3.
    }
}

I also uncommented 'django.contrib.admin' in same file. I uncommented url(r'^admin/', include(admin.site.urls)),
in "urls.py" to enable admin. And here is the urls.py , which I got from python manage.py startproject
from django.conf.urls import patterns, include, url

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
# Examples:
# url(r'^$', 'demo.views.home', name='home'),
# url(r'^demo/', include('demo.foo.urls')),

# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),

)

A: Using tab in Django is a bad practice. In order to fixed your problem you must use spaces only, I think 4 spaces. Try to backspace your codes and you'll see that it's tab indention, use only spaces.

A: I ran into the same error today.
Just like Dombey python -m tabnanny -v * reported a Clean bill of health for all my files.
I am using git so I tried running the master branch (which used to run fine) but I got the same result.
I don't know what triggered the error but uninstalling-reinstalling Django solved it for me.


text:
Q: Drm protected Video lagging when played offline on 2x speed I am trying to play drm protected video which is downloaded. It is working fine on most of the device. It is lagging on tablet devices specifically on Samsung A7 tab(Smt-500).
When I am playing file from server the lagging very less visible but when I play offline video on 2x speed lagging is quite visible.
I am using exoplayer - 2.10.2. I am using following datasource factory.
For online:
val defaultHttpDataSourceFactory =
    DefaultHttpDataSourceFactory(userAgent, defaultBandwidthMeter)

val mediaDataSourceFactory = DefaultDataSourceFactory(
    context,
    defaultBandwidthMeter,
    defaultHttpDataSourceFactory
)

dashMediaSource=DashMediaSource.Factory(mediaDataSourceFactory)
    .createMediaSource(videoViewModel.uri)

for offline:
cacheDataSourceFactory = CacheDataSourceFactory(cache, factory)

dashMediaSource = DashMediaSource.Factory(videoViewModel.cacheDataSourceFactory)
                        .createMediaSource(videoViewModel.uri

)


text:
Q: Output sum of decimal/float array rails I have the following which i thought would get me the sum of the array but doesnt:
<% @orders.each do |order| %>
   <% if Product.exists?(sku: order.line_items.where().map {|li| li.sku }) %>
      <%= order.line_items.where(vendor_name: @vendor.vendor_name).map do |li| %>
          <% if Product.exists?(sku: li.sku) %>
              <% product = Product.find_by(sku: li.sku ) %>
              <% ((li.store_price.to_d * li.store_fulfillable_quantity) - (product.production_price * li.store_fulfillable_quantity)) * (0.70) %>
          <% end %>
       <% end.compact.sum %>
   <% end %>
<% end %>

The output is something like:
25.21 25.21 12.66 5.33 12.66 9.01
I need to add these numbers.  How can I do this with the decimals/floats?
When I use
<%= @orders.each do |order| %>

I get undefined method + for nilclass for the line that is on, and it's not nil but obviously I'm missing some factor on how sum works.

A: <%= @orders.map do |order| %>
   <% if Product.exists?(sku: order.line_items.where().map {|li| li.sku }) %>
      <% order.line_items.where(vendor_name: @vendor.vendor_name).map do |li| %>
          <% if Product.exists?(sku: li.sku) %>
              <% product = Product.find_by(sku: li.sku ) %>
              <% ((li.store_price.to_d * li.store_fulfillable_quantity) - (product.production_price * li.store_fulfillable_quantity)) * (0.70) %>
          <% end %>
       <% end.compact.sum %>
   <% end %>
<% end.compact.sum %>

Is how i got it to work

A: method reduce in arrays designed for getting reduced value of collection:
array.compact.reduce(:+)
# => Sum of array

more info about reduce


text:
Q: Aspose, how to measure a Font? I'm using the Aspose Imaging library and my intention is to insert a centered watermark into an image, the library provides a custom Font class.
How I can measure the Width and Height of this kind of Font to center the text in the image?
What I've tried:
Dim font As New Aspose.Imaging.Font("Times New Roman", 64, FontStyle.Bold)

TextRenderer.MeasureText("Hello World!", TryCast(font, System.Drawing.Font)

I would like to know if exist a "direct" way to measure the text of a Aspose.Imaging.Font instead of creating a secondary System.Drawing.Font to measure it.

A: 'Create an instance of Image and load an existing image
Using image As Aspose.Imaging.Image = Aspose.Imaging.Image.Load("c://temp//sample.bmp")
    'Create and initialize an instance of the Graphics class
    Dim graphics As New Aspose.Imaging.Graphics(image)
    'Creates an instance of Font
    Dim font As New Aspose.Imaging.Font("Times New Roman", 16, Aspose.Imaging.FontStyle.Bold)

    'Create an instance of SolidBrush and set its various properties
    Dim brush As New Aspose.Imaging.Brushes.SolidBrush()
    brush.Color = Aspose.Imaging.Color.Black
    brush.Opacity = 100

    'Draw a String using the SolidBrush object and Font, at specific Point
    graphics.DrawString("Aspose.Imaging for .Net", font, brush, New Aspose.Imaging.PointF(image.Width/2, image.Height/2))

    ' Export to PNG file format using default options.
    image.Save("out.bmp",New Aspose.Imaging.ImageOptions.PngOptions())
End Using

 Adding a Watermark to an Image

A: A solution written by me:
''' <summary>
''' Adds a watermark into an image, at the specified position.
''' </summary>
''' <param name="img">Indicates the image.</param>
''' <param name="text">Indicates the watermark text.</param>
''' <param name="fnt">Indicates the watermark text font.</param>
''' <param name="color">Indicates the watermark text color.</param>
''' <param name="position">Indicates the watermark text position.</param>
''' <returns>Aspose.Imaging.Image.</returns>
Private Function AddWatermark(ByVal img As Aspose.Imaging.Image,
                              ByVal text As String,
                              ByVal fnt As Aspose.Imaging.Font,
                              ByVal color As Aspose.Imaging.Color,
                              ByVal position As Aspose.Imaging.PointF) As Aspose.Imaging.Image

    Using brush As New Aspose.Imaging.Brushes.SolidBrush With {.Color = color, .Opacity = 100.0F}

        ' Create and initialize an instance of Graphics class.
        Dim g As New Aspose.Imaging.Graphics(img)

        ' Draw a String using the SolidBrush object and Font, at specific Point and with specific format.
        g.DrawString(s:=text, font:=fnt, brush:=brush, point:=position)

    End Using

    ' Return the modified image.
    Return img

End Function

''' <summary>
''' Adds a watermark into an imag, at a prefedined position.
''' </summary>
''' <param name="img">Indicates the image.</param>
''' <param name="text">Indicates the watermark text.</param>
''' <param name="fnt">Indicates the watermark text font.</param>
''' <param name="color">Indicates the watermark text color.</param>
''' <param name="position">Indicates the watermark text position.</param>
''' <param name="verticalmargin">Indicates the watermark text vertical margin.</param>
''' <param name="horizontalmargin">Indicates the watermark text horizontal margin.</param>
''' <returns>Aspose.Imaging.Image.</returns>
Private Function AddWatermark(ByVal img As Aspose.Imaging.Image,
                              ByVal text As String,
                              ByVal fnt As Aspose.Imaging.Font,
                              ByVal color As Aspose.Imaging.Color,
                              ByVal position As WatermarkPosition,
                              Optional ByVal verticalmargin As Single = 0.0F,
                              Optional ByVal horizontalmargin As Single = 0.0F) As Aspose.Imaging.Image

    Dim textformat As New Aspose.Imaging.StringFormat
    Dim textposition As Aspose.Imaging.PointF = Aspose.Imaging.PointF.Empty

    Select Case position

        Case WatermarkPosition.Top ' Note: horizontalmargin value is ignored.
            textposition = New Aspose.Imaging.PointF(x:=(img.Width \ 2), y:=verticalmargin)
            textformat.Alignment = Aspose.Imaging.StringAlignment.Center
            textformat.FormatFlags = Aspose.Imaging.StringFormatFlags.MeasureTrailingSpaces

        Case WatermarkPosition.TopLeft
            textposition = New Aspose.Imaging.PointF(x:=horizontalmargin, y:=verticalmargin)
            textformat.Alignment = Aspose.Imaging.StringAlignment.Near
            textformat.FormatFlags = Aspose.Imaging.StringFormatFlags.MeasureTrailingSpaces

        Case WatermarkPosition.TopRight
            Dim f As New System.Drawing.Font(fnt.Name, fnt.Size, DirectCast(fnt.Style, System.Drawing.FontStyle))
            Dim measure As System.Drawing.Size = TextRenderer.MeasureText(text, f)
            textposition = New Aspose.Imaging.PointF(x:=(img.Width - measure.Width - horizontalmargin), y:=verticalmargin)
            textformat.Alignment = Aspose.Imaging.StringAlignment.Near
            textformat.FormatFlags = Aspose.Imaging.StringFormatFlags.MeasureTrailingSpaces

        Case WatermarkPosition.Middle ' Note: verticalmargin horizontalmargin and values are ignored.
            textposition = New Aspose.Imaging.PointF(x:=(img.Width \ 2), y:=(img.Height \ 2))
            textformat.Alignment = Aspose.Imaging.StringAlignment.Center
            textformat.FormatFlags = Aspose.Imaging.StringFormatFlags.MeasureTrailingSpaces

        Case WatermarkPosition.MiddleLeft ' Note: verticalmargin value is ignored.
            textposition = New Aspose.Imaging.PointF(x:=(horizontalmargin), y:=(img.Height \ 2))
            textformat.Alignment = Aspose.Imaging.StringAlignment.Near
            textformat.FormatFlags = Aspose.Imaging.StringFormatFlags.MeasureTrailingSpaces

        Case WatermarkPosition.MiddleRight ' Note: verticalmargin value is ignored.
            Dim f As New System.Drawing.Font(fnt.Name, fnt.Size, DirectCast(fnt.Style, System.Drawing.FontStyle))
            Dim measure As System.Drawing.Size = TextRenderer.MeasureText(text, f)
            textposition = New Aspose.Imaging.PointF(x:=(img.Width - measure.Width - horizontalmargin), y:=(img.Height \ 2))
            textformat.Alignment = Aspose.Imaging.StringAlignment.Near
            textformat.FormatFlags = Aspose.Imaging.StringFormatFlags.MeasureTrailingSpaces

        Case WatermarkPosition.Bottom ' Note: horizontalmargin value is ignored.
            Dim f As New System.Drawing.Font(fnt.Name, fnt.Size, DirectCast(fnt.Style, System.Drawing.FontStyle))
            Dim measure As System.Drawing.Size = TextRenderer.MeasureText(text, f)
            textposition = New Aspose.Imaging.PointF(x:=(img.Width \ 2), y:=(img.Height - measure.Height - verticalmargin))
            textformat.Alignment = Aspose.Imaging.StringAlignment.Center
            textformat.FormatFlags = Aspose.Imaging.StringFormatFlags.MeasureTrailingSpaces

        Case WatermarkPosition.BottomLeft
            Dim f As New System.Drawing.Font(fnt.Name, fnt.Size, DirectCast(fnt.Style, System.Drawing.FontStyle))
            Dim measure As System.Drawing.Size = TextRenderer.MeasureText(text, f)
            textposition = New Aspose.Imaging.PointF(x:=(horizontalmargin), y:=(img.Height - measure.Height - verticalmargin))
            textformat.Alignment = Aspose.Imaging.StringAlignment.Near
            textformat.FormatFlags = Aspose.Imaging.StringFormatFlags.MeasureTrailingSpaces

        Case WatermarkPosition.BottomRight
            Dim f As New System.Drawing.Font(fnt.Name, fnt.Size, DirectCast(fnt.Style, System.Drawing.FontStyle))
            Dim measure As System.Drawing.Size = TextRenderer.MeasureText(text, f)
            textposition = New Aspose.Imaging.PointF(x:=(img.Width - measure.Width - horizontalmargin), y:=(img.Height - measure.Height - verticalmargin))
            textformat.Alignment = Aspose.Imaging.StringAlignment.Near
            textformat.FormatFlags = Aspose.Imaging.StringFormatFlags.MeasureTrailingSpaces

    End Select

    Using brush As New Aspose.Imaging.Brushes.SolidBrush With {.Color = color, .Opacity = 100.0F}

        ' Create and initialize an instance of Graphics class.
        Dim g As New Aspose.Imaging.Graphics(img)

        ' Draw a String using the SolidBrush object and Font, at specific Point and with specific format.
        g.DrawString(s:=text, font:=fnt, brush:=brush, point:=textposition, format:=textformat)

    End Using

    textformat.Dispose()

    ' Return the modified image.
    Return img

End Function

''' <summary>
''' Specifies a Watermark position
''' </summary>
Public Enum WatermarkPosition As Short

    ''' <summary>
    ''' Top position.
    ''' horizontalmargin value is ignored.
    ''' </summary>
    Top = 0S

    ''' <summary>
    ''' Top-Left position.
    ''' </summary>
    TopLeft = 1S

    ''' <summary>
    ''' Top-Right position.
    ''' </summary>
    TopRight = 2S

    ''' <summary>
    ''' Middle-Left position.
    ''' verticalmargin value is ignored.
    ''' </summary>
    MiddleLeft = 3S

    ''' <summary>
    ''' Middle position.
    ''' verticalmargin and horizontalmargin values are ignored.
    ''' </summary>
    Middle = 4S

    ''' <summary>
    ''' Middle-Right position.
    ''' verticalmargin value is ignored.
    ''' </summary>
    MiddleRight = 5S

    ''' <summary>
    ''' Bottom position.
    ''' horizontalmargin value is ignored.
    ''' </summary>
    Bottom = 6S

    ''' <summary>
    ''' Bottom-Left position.
    ''' </summary>
    BottomLeft = 7S

    ''' <summary>
    ''' Bottom-Right position.
    ''' </summary>
    BottomRight = 8S

End Enum

Usage:
Imports Aspose.Imaging

Public Class Form1

Private Sub Form1_Load() Handles MyBase.Load

    ' Load an image to add a watermark.
    Dim img As Aspose.Imaging.Image = Aspose.Imaging.Image.Load("C:\sample.bmp")

    ' Set the watermark text.
    Dim text As String = "ElektroStudios"

    ' Set the watermark text color.
    Dim color As Aspose.Imaging.Color = Aspose.Imaging.Color.White

    ' Set the watermark text font.
    Dim fnt As New Aspose.Imaging.Font("Lucida Console", 32, FontStyle.Bold)

    ' Add the watermark into the image.
    img = Me.AddWatermark(img:=img, text:=text, fnt:=fnt, color:=color,
                          position:=WatermarkPosition.BottomRight)

    ' Or...
    ' Dim position As New Aspose.Imaging.PointF(x:=10, y:=10)
    ' img = Me.AddWatermark(img:=img, text:=text, fnt:=fnt, color:=color,
    '                       position:=position)

    ' Save the image to disk.
    img.Save("C:\Watermark.bmp")

    ' See the resulting image.
    Process.Start("C:\Watermark.bmp")
    Application.Exit()

End Sub

End Class


text:
Q: Link to a hidden jquery anchor from a separate page I've used the code below to set up some scrolling to anchors on my site but I've run into an issue where I would like to come from a link on another page to a specific anchor that is hidden (section2). I pieced this together from some other questions/anwsers
var sectionhash = window.location.hash.substring(1)
jQuery(document).ready(function(){
jQuery.scrollTo('a[name=' + '#section2' + ']')

});

but I can't get it to work.
If any one has any ideas on how to make it happen I would love to know.
var currentSection = '#section1';
var currentPos = 0;
jQuery(document).ready(function(){
  jQuery('.drop_down').find('a').bind('click', function(e) {
    e.preventDefault();
    var slidingSection = this.getAttribute('href');
    if(slidingSection == currentSection) return false;
    var slidingPos = jQuery(this).parent().index();
    var targetSlide = jQuery('#scroller').children().eq(slidingPos);

    jQuery('#scroller').children().not(currentSection).hide();
    targetSlide.show();
    var offset = 820;
    if(slidingPos < currentPos) offset = -820;
    targetSlide.css({top: offset});

    jQuery(slidingSection).animate({top: 0});
    jQuery(currentSection).animate({top: -offset});

    currentSection = slidingSection;
    currentPos = slidingPos;
  });
});

 content

 different content


text:
Q: how to avoid long sql in clickhouse As ClickHouse can run complex SQL efficiently, we now write hundred-lines-in-one SQL to get the real time analysis results(join lots of source table). And it brings a problem is that it's so hard to maintain and reuse.
And we are using mybatis to write the sql in our Java Application. We try to use Mybatis's global parameter to define some sql for reuse, but not helps a lot in such huge lines SQL.
Is there any way to avoid such long sql or  make the sql more readable and make this work more engineerable?

<select id="brandAnalysis" resultType="java.util.HashMap">
        SELECT gmvRank.id_code,
            gmvRank.rank,
            gmvRank.lastRank,
            gmvRank.gmv as sale_money,
            member.dealerMembers as dealer_turnover,
            member.teamMembers,
            case
                when member.dealerMembers = 0 then 0
                when member.teamMembers = 0 then 0
                else member.dealerMembers/member.teamMembers end AS dealer_turnover_active
        FROM (
            SELECT id_code,
            <choose>
                <when test="monthQuarter == 3">
                    case
                        when max(`quarter`) = #{quarter} then argMax(${sqlRankField},`month`)
                        else null end as rank,
                    case
                        when max(`quarter`) = #{quarter} then argMax(${sqlGmvField},`month`)
                        else null end as gmv,
                    case
                        when min(`quarter`) = #{compareQuarter} then argMin(${sqlRankField},`month`)
                        else null end as lastRank
                </when>
                <otherwise>
                    case
                        when max(`month`) = #{month} then argMax(${sqlRankField},`month`)
                        else null end as rank,
                    case
                        when max(`month`) = #{month} then argMax(${sqlGmvField},`month`)
                        else null end as gmv,
                    case
                        when min(`month`) = #{compareMonth} then argMin(${sqlRankField},`month`)
                        else null end as lastRank
                </otherwise>
            </choose>
            FROM
                tengju.dws_crm_brand_analysis_rank_dd_m
            <choose>
                <when test="monthQuarter == 3">
                    PREWHERE quarter in (#{quarter},#{compareQuarter})
                    and insert_time in (
                        SELECT MAX(insert_time)
                        FROM tengju.dws_crm_brand_analysis_rank_dd_m
                        PREWHERE quarter in (#{quarter},#{compareQuarter})
                        GROUP BY quarter
                    )
                </when>
                <otherwise>
                    PREWHERE month in (#{month},#{compareMonth})
                    and insert_time in (
                        SELECT MAX(insert_time)
                        FROM tengju.dws_crm_brand_analysis_rank_dd_m
                        PREWHERE month in (#{month},#{compareMonth})
                        GROUP BY month
                    )
                </otherwise>
            </choose>
            <if test="dominationIdCode != null and dominationLevel != null">
                and id_code in (
                    SELECT id_code
                    FROM tengju.dwd_user_domination_relation_map_all
                    PREWHERE visit_date >= formatDateTime(yesterday(),'%F')
                    AND insert_time in (
                        SELECT max(insert_time)
                        FROM tengju.dwd_user_domination_relation_map_all
                        PREWHERE visit_date >= formatDateTime(yesterday(),'%F')
                    )
                    AND domination_star_level = #{dominationLevel}
                    AND domination_id_code = #{dominationIdCode}
                    <if test="starLevels != null and starLevels.size() > 0">
                        AND star_level in
                        <foreach collection="starLevels" item="item" index="index" open="(" close=")" separator=",">
                            #{item}
                        </foreach>
                    </if>
                    <if test="isDirect != null and isDirect > 0">
                        AND parent_id_code = #{dominationIdCode}
                    </if>
                )
            </if>
            <if test="idCodes != null and idCodes.size() > 0">
                AND id_code in
                <foreach collection="idCodes" item="item" index="index" open="(" close=")" separator=",">
                    #{item}
                </foreach>
            </if>

            AND brand_id = #{brandId}
            GROUP BY id_code
        ) as gmvRank
        GLOBAL LEFT JOIN (
            <choose>
                <when test="crmRankCrowdPerspective == 4">
                    <include refid="smallTeamDealer" />
                </when>
                <when test="crmRankCrowdPerspective == 1">
                    <include refid="KATeamDealer" />
                </when>
                <otherwise>
                    <include refid="ecOrCityTeamDealer" />
                </otherwise>
            </choose>
        ) as member
        on (gmvRank.id_code = member.id_code)
        where 1=1
        <if test="saleMoneyFrom != null">
            AND gmvRank.gmv >= toDecimal128(#{saleMoneyFrom},2)
        </if>
        <if test="saleMoneyTo != null">
            AND toDecimal128(#{saleMoneyTo},2) >= gmvRank.gmv
        </if>
        order by ${sortType}
        LIMIT #{offset},#{pageSize}

  </select>

A: User common table expressions to get rid of nested operations. Each make and version of database server has its own style of SQL. Not all have common table expressions. All have views though. SQL queries can be insanely verbose, for sure there is no other option.


text:
Q: Next line matching the regex in bash I have a file in the format:
Port Number
IP address
Port Number
IP address

(Not sure how the output will be displayed here but let me tell you they are on separate lines)
and so on....
I use the command grep -C 1 'port number' file.txt
i.e. I want all IP addresses corresponding to a particular port. Making it simple, I want the next line matching a regular expression. Like if my regular expression matches line 2,4 and 6 then I want lines 3, 5 and 7 to be printed. How to do that?

A: use awk. Its simpler to understand than sed.
awk '/port number/{getline;print }' file

'getline' gets the next line after /port number/ is matched.

A: sed -n '/^port$/{n;p}' < file.txt
-n tells sed not to print the input text as it processes it.  You want this since you only want to see the lines which match your criteria.
/^port$/ restricts which lines {n;p} will operate on to those matching the specified port.
In {n;p}, the n means to read the next line of input into sed's pattern space.  This will be the line that contains your IP address.  The p then tells sed to print its pattern space, so the IP address line is printed.

A: Give this a try:
sed -n '/Port Number/{n;p}' file.txt

In GNU sed case insensitive:
sed -n '/Port Number/I{n;p}' file.txt


text:
Q: Scraping Job Descriptions off of LinkedIn I've created a python script that uses Selenium's library to scrape:

*

*Job Titles

*Company Name

*Location of Job

*Job Description (which I need help getting!), off of LinkedIn jobs search section.

I've created a for loop to iterate over the (25) jobs to pull out the description of each job using the same class name each description uses. I've been able to successfully pull out (1) description, but haven't been able to scrape out the other descriptions of the remaining (24) jobs. I'm assuming its the loops incapability to parse through each section, however if its able to pull out (1) description successfully, why aren't the other descriptions coming up?

import pandas as pd
import re
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

# This will open a new Chrome page to test specified url on (for scraping)
browser=webdriver.Chrome("My Chrome Path")
browser.get("https://www.linkedin.com")

# Requires user to enter username and password
username=browser.find_element_by_id("session_key")
username.send_keys("ENTER USERNAME")
password=browser.find_element_by_id("session_password")
password.send_keys("ENTER PASSWORD")

# Once username and password are entered, this will automatically click the submit button to login into LinkedIn
login_button=browser.find_element_by_class_name("sign-in-form__submit-button")
login_button.click()

# This is the URL to test the jobs I want to scrape from
browser.get("https://www.linkedin.com/jobs/search/?keywords=software%20developer")

# This will scrape and display (25) job titles from page (1)
job_title=browser.find_elements_by_class_name("job-card-list__title")
company_title=[]
for i in job_title:
    company_title.append(i.text)
print(company_title)
print()
print(len(company_title))

# This will scrape and display (25) company names from page (1) - correspondent to company_title above
job_company=browser.find_elements_by_class_name("job-card-container__company-name")
company_name=[]
for i in job_company:
    company_name.append(i.text)
print(company_name)
print()
print(len(company_name))

# This will scrape and display (25) location names from page (1) - correspondent to company_title and company_name above
job_location=browser.find_elements_by_class_name("job-card-container__metadata-item")
location_name=[]
for i in job_location:
    location_name.append(i.text)
print(location_name)
print()
print(len(location_name))

# At this point, I am trying to iterate over each of the (25) jobs to pull out the description. I've successfully been able to pull out (1) description, but haven't been able to pull out the other descriptions of the remaining (24) jobs.
job_description=browser.find_elements_by_class_name('jobs-search__right-rail')
description_name = []
for i in job_description:
    description_name.append(i.text)
print(description_name)
print()
print(len(description_name))

A: The problem has to do with how the pages are loaded.
Every time you click a new Job container, it sends a different GET request to the server.
This link, by default, has the first job selected.
https://www.linkedin.com/jobs/search/?keywords=software%20developer

When you click another page, it changes the job id.
Example:
https://www.linkedin.com/jobs/search/?currentJobId=2512009247&keywords=software%20developer

So you can either emulate a click on the container or change the currentJobId by scraping the id from the page and reloading the page with the new link.
# Example of scraping the currentJobId for each item.
job_containers = browser.find_elements_by_class_name('job-card-container relative job-card-list job-card-container--clickable job-card-list--underline-title-on-hover jobs-search-results-list__list-item--active jobs-search-two-pane__job-card-container--viewport-tracking-0')
job_ids = []
for job_container in job_containers:
    job_ids.append(job_container.get_attribute("data-job-id"))

Function to grab the descriptions
def get_descriptions(browser, job_ids):
    job_descriptions = []
    for job_id in job_ids:
        browser.get(f'https://www.linkedin.com/jobs/search/?currentJobId={job_id}&keywords=software%20developer')
        job_description = browser.find_elements_by_class_name('jobs-search__right-rail')[0].text
        job_descriptions.append(job_description)

    return job_descriptions


text:
Q: Sum of each values of Guava Multimap I created a Guava Multimap
ListMultimap<String,String> sampleMultimap = ArrayListMultimap.create();
And added some values which I take from a text file.
Now as an output I have
{Football=[10], Basketball=[1210, 1210, 1210, 120], Tennis=[1, 10, 100, 1000]}

I would like to sum each of the sports and find the highest sum. So expected result is
Basketball: 3750

Somehow I am stuck because I cant get the each one with samleMultimap.get(x) because key values are unknown and comes form text file.
Is there any way to get the expected result?

A: In the end you want Map<String, Integer> where values are sums of original multimap. You can use couple views:

*

*Multimap#asMap() to have Map<K, Collection<V>> view of your multimap,

*Maps#transformValues(Map, Function) - to create a view of a map where each value is transformed by a function.
Map<String, Integer> map = Maps.transformValues(multimap.asMap(), ints ->
        ints.stream().mapToInt(Integer::intValue).sum());

Note that if you want to perform many operations on resulted map, read caveat in documentation and for example do ImmutableMap.copyOf(map):

The function is applied lazily, invoked when needed. This is necessary for the returned map to be a view, but it means that the function will be applied many times for bulk operations like Map.containsValue(java.lang.Object) and Map.toString(). For this to perform well, function should be fast. To avoid lazy evaluation when the returned map doesn't need to be a view, copy the returned map into a new map of your choosing.

A: With a ListMultimap you can call asMap() to get a view as a java.util.Map, then do normal map things.
If you change sampleMultimap to be an ArrayListMultimap instead of ListMultimap, then you can call keySet() directly (skip the asMap() call) and iterate over the resulting keys.
Here's an example showing how you could get each key from a ListMultimap (even if the underlying implementation is an instance of ArrayListMultimap), then get each associated value:
ListMultimap<String,String> sampleMultimap = ArrayListMultimap.create();
Map<String,String> mapView = sampleMultimap.asMap();
for (String key : mapView.keySet()) {
    String value = mapView.get(key);
    // do something with value
}


text:
Q: What's the difference between @Bean and @Component? I'm learning Spring Boot recently, But I'm quite confused by @Bean annotation and @Component annotation.
Now I want to change the page language by clicking on language buttons. So I create a LocaleResolver:
public class MyLocaleResolver implements LocaleResolver {

    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        String lang = httpServletRequest.getParameter("lang");
        Locale locale = Locale.getDefault();
        if(lang != null && lang.length() !=0){
            String[] splitted = lang.split("-");
            locale = new Locale(splitted[0], splitted[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {}
}

And in the configuration class MyMvcConfig:
@Configuration
public class MyMvcConfig {
    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResolver();
    }
}

And it works properly, my own implementation replaces the default LocaleResolver in WebMvcAutoConfiguraion. But if I remove the configuration class and add @Component annotation to MyLocaleResolver class, then the container will still use the default LocaleResolver. Why this happen?


text:
Q: "Early Access" - What does this mean? What does this tag mean? I purchased a shotgun at level 6 because it said when you purchase with Zen you get "Early Access", but I can't use it. Have I read this wrong or have I just been conned out of my money and now have to get to level 20 when everyone else can use the same thing and it won't be fun?

A: "Early Access" means that you can use Zen to bypass the level restriction on certain gear. For example, this means that even if you're level 10, you can spend Zen to use equipment like a Shotgun receiver, which requires level 20.  Time restrictions still apply, so not all Zen purchases are permanent.


text:
Q: Using Mockito's generic "any()" method I have an interface with a method that expects an array of Foo:
public interface IBar {
  void doStuff(Foo[] arr);
}

I am mocking this interface using Mockito, and I'd like to assert that doStuff() is called, but I don't want to validate what argument are passed - "don't care".
How do I write the following code using any(), the generic method, instead of anyObject()?
IBar bar = mock(IBar.class);
...
verify(bar).doStuff((Foo[]) anyObject());

A: This should work
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;

verify(bar).DoStuff(any(Foo[].class));

A: As I needed to use this feature for my latest project (at one point we updated from 1.10.19), just to keep the users (that are already using the mockito-core version 2.1.0 or greater) up to date, the static methods from the above answers should be taken from ArgumentMatchers class:
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.ArgumentMatchers.any;

Please keep this in mind if you are planning to keep your Mockito artefacts up to date as possibly starting from version 3, this class may no longer exist:
As per 2.1.0 and above, Javadoc of org.mockito.Matchers states:

Use org.mockito.ArgumentMatchers. This class is now deprecated in order to
  avoid a name clash with Hamcrest  * org.hamcrest.Matchers
  class. This class will likely be removed in version 3.0.

I have written a little article on mockito wildcards if you're up for further reading.

A: Since Java 8 you can use the argument-less any method and the type argument will get inferred by the compiler:
verify(bar).doStuff(any());

Explanation
The new thing in Java 8 is that the target type of an expression will be used to infer type parameters of its sub-expressions. Before Java 8 only arguments to methods where used for type parameter inference (most of the time).
In this case the parameter type of doStuff will be the target type for any(), and the return value type of any() will get chosen to match that argument type.
This mechanism was added mainly to be able to compile lambda expressions, but it improves type inferences generally.

Primitive types
This doesn't work with primitive types, unfortunately:
public interface IBar {
    void doPrimitiveStuff(int i);
}

verify(bar).doPrimitiveStuff(any()); // Compiles but throws NullPointerException
verify(bar).doPrimitiveStuff(anyInt()); // This is what you have to do instead

The problem is that the compiler will infer Integer as the return value type of any(). Mockito will not be aware of this (due to type erasure) and return the default value for reference types, which is null. The runtime will try to unbox the null return value by calling the intValue method on it before passing it to doStuff, and the exception gets thrown.

A: You can use Mockito.isA() for that:
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.verify;

verify(bar).doStuff(isA(Foo[].class));

http://site.mockito.org/mockito/docs/current/org/mockito/Matchers.html#isA(java.lang.Class)


text:
Q: What are the unique use cases for the any and all operators? I am currently studying for the Oracle 1Z0-071 certified associate exam.
I am learning about multiple row subqueries that use ANY or ALL
SELECT first_name, last_name, salary
FROM employees
WHERE salary >= any (select salary from employees where department_id='90')

SELECT first_name, last_name, salary
FROM employees
WHERE salary >= all (select salary from employees where department_id='90')

These are tables from the built-in HR-schema with Oracle 19c.
It seems to me I could replace
'any' with (select min(salary) from employees where department_id='90')
'all' with (select max(salary) from employees where department_id='90')
for the example queries above.
Inputting this in sqlplus does indeed return the same output. From my limited perspective, this makes any and all seem redundant and something I could potentially afford to forget after cramming for the exam.

Is there any use case for 'any' or 'all' that can't be expressed just as easily with a MIN or MAX function?

A: You can't replace the conditions with "min" and "max" conditions in the straightforward way you did - not if null is possible.
The comparison  > all (... ) will fail automatically if null is present in the column in the subquery. On the other hand, max ignores null.
Compare:
select 1 as result from dual where 2000 > all (select comm from scott.emp);

no rows selected

select 1 as result from dual where 2000 > (select max(comm) from scott.emp);

    RESULT
----------
         1

Of course, you can use "max" in a rewrite of the "all" query, but it will be more complicated. It's not that you can't avoid "all" (you can!), it's just not as trivial as you think.


text:
Q: Undefined Index (Laravel) I'm bashing my head against my desk trying to figure out why this PHP code is causing this error: Undefined index: arr. I'm using Laravel, and this code works like gold outside of it, but inside Laravel, it's returning the undefined index error.
Here's the code:
function set_pilots_array($line_array)
{
    $airports = $this->airports;
    $pilots = $this->pilots;
    foreach($airports as $airport)
    {
        if($airport == $line_array[11] || $airport == $line_array[13])
        {
            if($airport == $line_array[11])
            {
                $deparr = "dep";
            }
            if($airport == $line_array[13])
            {
                $deparr = "arr";
            }
            $this->pilots[$deparr][] = array($line_array[0], $line_array[11], $line_array[13], $line_array[7], $line_array[5], $line_array[6], $line_array[8]);
        }
    }
}

function get_pilots_count()
{
    $count = count($this->pilots['dep']) + count($this->pilots['arr']);
    return $count;
}

This sort of goes with my other question: Grab and Explode Data  It's pulling the data from the data file using this code:
elseif($data_record[3] == "PILOT")
{
    $code_obj->set_pilots_array($data_record);
}

Which later does this:
$code_count = $code_obj->get_pilots_count();

A: You do not have $this->pilots['arr'] set. In other words, if you look at the output of var_dump($this->pilots);, you shall see there is no arr key-value pair. I suggest you this fix:
$count = count((isset($this->pilots['dep']) ? $this->pilots['dep'] : array())) + count((isset($this->pilots['arr']) ? $this->pilots['arr'] : array()));

Actually, this is not a fix - this is more like a hack. To make your code correct i suggest you to set the default values for those $pilots['arr'] and $pilots['dep'] values:
function set_pilots_array($line_array)
{
    $airports = $this->airports;
    $pilots = $this->pilots;

    foreach (array('dep', 'arr') as $key)
    {
        if (!is_array($pilots[$key]) || empty($pilots[$key]))
        {
            $pilots[$key] = array();
        }
    }

    // ...
}

A: Well there is too little code to really figure out what is going on, but based on what I see:
if($airport == $line_array[13])

this condition is never being met and so $deparr = "arr"; never happens and because of this
count($this->pilots['arr']);

is giving an undefined index error
You can easily suppress this by:
$count = count(@$this->pilots['dep']) + count(@$this->pilots['arr']);

A: your problem is that you are accessing all of your indexes directly without checking if they exist first.
assume that in laravel something is causing the array to not be populated.
in order to fix this, you should either iterate through the array with a foreach, or do a if(!empty($line_array[13])) {} before accessing it.


text:
Q: Wordpress slow query i have a wordpress blog and my shared hosting companny warned me about slow activity.
In my mysql slowlog.log i have essentialy queries that take about 2 an d 3 (i think seconds not milliseconds)
here is the query in the log :
# Query_time: 2  Lock_time: 0  Rows_sent: 25  Rows_examined: 36266
    SELECT l.ID, post_content, post_name, post_author, post_parent, post_modified_gmt, post_date, post_date_gmt
                    FROM (
                        SELECT ID FROM wp_posts
                            WHERE post_status = 'publish'
                            AND post_password = ''
                            AND post_type = 'my_post_type'

                            ORDER BY post_modified ASC
                            LIMIT 25 OFFSET 9925 ) o
                        JOIN wp_posts l
                        ON l.ID = o.ID
                        ORDER BY l.ID;

My questions are : is this query a core query ? in this case is it normal to take 3 seconds ? if not, how can i remedy ?  i mean by a core query if it is not a plugin or a theme function that generate this query, since i have not found it in the theme's function.php
I have another slow query in the log :
# Query_time: 2  Lock_time: 0  Rows_sent: 1  Rows_examined: 29232
SELECT post_modified_gmt FROM wp_posts WHERE post_status IN ('publish','inherit') AND post_type = 'my_post_type' ORDER BY post_modified_gmt ASC LIMIT 1 OFFSET 2999;

same questions here, is it a core query or plugin relatedd one etc...
Please note that i've installed WP super cache, my site loads faster but i still have these slow queries in slowlog.log
PS: I'm on a reliable hsting company (infomaniak), they have put my blog on Dedicated VPS machine for 15 days to let me fix the problem
Thanks for the help and sorry for my very bad english
-------------------------------------------EDIT---------------------------------------
No way still have these queries after installing wp super cache :(
# Query_time: 2  Lock_time: 0  Rows_sent: 25  Rows_examined: 49908
SELECT l.ID, post_content, post_name, post_author, post_parent, post_modified_gmt, post_date, post_date_gmt
                FROM (
                    SELECT ID FROM wp_posts
                        WHERE post_status = 'publish'
                        AND post_password = ''
                        AND post_type = 'my_post_type'

                        ORDER BY post_modified ASC
                        LIMIT 25 OFFSET 23550 ) o
                    JOIN wp_posts l
                    ON l.ID = o.ID
                    ORDER BY l.ID;

A: Okay i've found what was the problem for these queries :
First there are NOT CORE queries they were generated by a plugin which is called "Yoast WordPress SEO" precisally the sitemap part of the plugin. "file : class-sitemaps.php"
When i disabled the sitemap part of the plugin, i didn't had these queries in my slowlog.log file.

A: This two queries are core queries, you can't remove it.
The best way is to use a cache plugin (like wp super cache),

A: I am getting this as slow query where this query will hit
SELECT SQL_CALC_FOUND_ROWS  wp_posts.ID FROM wp_posts  WHERE 1=1  AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish')  ORDER BY wp_posts.post_date DESC LIMIT 0, 10

actually i manually set posts_per_pages to 16,


text:
Q: How to save a reference to a control added programmatically? I added 3 buttons programmatically to my view, then I added the buttons to an array so that I can access them at a later time:
for (i = 0; i < 3; i++)
{
  UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
  [view addSubview:button];
  [_buttons addObject:button];
}

If I reference the button in my array and change the image of the button, it does not change the button on screen.
UIButton* button = [_buttons objectAtIndex: 0];
[button setImage:thumb forState:UIControlStateNormal];

I've found a way to change the image of the button by looping through all the subviews in my view, but is there a better way?
for (UIView* subView in ((UIView*)[self.view.subviews objectAtIndex:0]).subviews){
    if ([subView isKindOfClass:[UIButton class]]){
        UIButton *button = (UIButton*)subView;
        if (button.tag == self.selected){
            [button setImage:thumb forState:UIControlStateNormal];
        }
    }
}

A: A common reason for this is that your array has not been initialized. When this happens, Objective C does not complain or throw excetions: instead, it behaves as if the calls to add elements never happened. It also returns nil when you try getting items back.
Add this line to your viewDidLoad method:
_buttons = [NSMutableArray array];

This should solve the problem.

A: Possible this could help on a click event:
      -(void)clickEvent:(id)sender
      {
           [sender setImage:thumb forState:UIControlStateNormal];
      }

If this is how you are picking up the event.

A: When you do addSubview, view retains subview you are adding. Also addObject retains it. Hence both are different ojbects. Changing properties of object in array will not affect object retained by view.
You can avoid loop by using tags. While adding buttons on view set unique tags to them. And when you want to access them, get it using tag directly.
//set tags for buttons
      UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
      [button setTag:999];
      [view addSubview:button];

//access using tag
      UIButton *button = (UIButton*)[view viewWithTag:999];
      [button setImage:thumb forState:UIControlStateNormal];

A: Add a tag to the button after creating it. And later use that tag to get that button.
for (i = 0; i < 3; i++)
{
  UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
  button.tag = i+1;
  [view addSubview:button];
  [_buttons addObject:button];
}

Then you can access it like:
UIButton *button1 = (UIButton *)[self.view viewWithTag:1];
UIButton *button2 = (UIButton *)[self.view viewWithTag:2];
UIButton *button3 = (UIButton *)[self.view viewWithTag:3];

A: While adding UIControl programatically to use reference later add tag to it which should be different like:
 yourBtn.tag = 111;

Now get reference of UIButton like this:
 UIButton *button = (UIButton*)[yourViewWhereYouAdded viewWithTag:111];


text:
Q: linear binary code problem
Let $\mathcal C$ be a $[n,k,d]$ linear binary code such that $\mathcal C$ has a systematic generator matrix $G=[I_k\mid A]$.
(i) Prove that $u\in (\mathbb F_2)^k$ is coded by $c=(u\mid uA)\in \mathcal C$. $(u\mid uA)$ is concatenation.
(ii) Suppose that $\mathcal C$ can correct $t$ errors and when transmitting $c\in \mathcal C$, an error $e$ with weight $w_H(e)\leq t$ happens, so the received message is $v=c+e$. Set $e=(e'\mid e'')$ where $e'\in \mathbb (F_2)^k$ and $e''\in (F_2)^{n-k}$. Let $s=Sd(v)$ be $v$'s syndrome.
a) Prove that if $w_h(s)\leq t$, then $e'=0, e''=s$ and $c=v-(0\mid s)$.
b) Prove that if $e'=0$, then $w_H(s)\leq t$.

I already proved (i) and (ii), b). I'm missing (ii), a).
What I have so far is this

*

*$d\ge 2t+1$ because $\mathcal C$ corrects $t$ errors.

*let $H=[A^T\mid I_{n-k}]$ be parity check matrix. Then $Sd(v)=vH^T=[c+e]H^T=[u+e'\mid uA+e'']\begin{bmatrix} A\\ I_{n-k}\end{bmatrix}=uA+e'A+uA+e''=e'A+e''+2uA=e'A+e''$

*since $d\ge 2t+1$, any $2t$ columns of $H$ are linearly independent

*I guess that somehow I first need to prove that $e'A=0$ and then $e'=0$ should follow. But does $e'A=0$ imply $e'=0$ here?

what I showed above are just some facts that I think might be useful, although I don't see how. I just need to prove that $e'=0$, the rest is an easy consequence.
Can someone tell me how to prove this?

A: let $p=(0\mid s)$. since $pH^T=s$, then $Sd(p)=Sd(v)$, so $p-v\in \mathcal C$. Since $\mathcal C$ detects $2t$ errors, then $B_{2t}(c)\cap \mathcal C=\{c\}$. But $d_H(c,v-p)=d_H(v-e, v-p)=d_H(e,p)\leq d_H(e,0)+d_H(0,p)=w_H(e)+w_H(p)\leq 2t$, so $v-p\in B_{2t}(c)\cap \mathcal C=\{c\}$. so $v-p=v-e$ and every thing follows.


text:
Q: Android ICS MediaPlayer crashes only on variables meant for simultaneous playback I have two types of playback of MediaPlayer in two different apps. One is a single variable that waits until it is finished to play the next word/sound effect. This seems to work fine. The other is a set of up to 4 MediaPlayer variables that play simultaneously. This works in 2.3.3 and seems to work on a 4.0.3 virtual device, but on my TF101 it crashes in both apps.
On a wrong touch, playse('oops') would be called.
public void playse(String ss){
    MediaPlayer tempse;

    if(tse1 == null){tempse = tse1;}
    else{if(tse2 == null){tempse = tse2;}
    else{if(tse3 == null){tempse = tse3;}
    else{if(tse4== null){tempse = tse4;}}}}

   if(ss == "oops"){ tempse =  MediaPlayer.create(mContext, R.raw.seoops); tempse.start();}
}

In the main loop of the app the 4 variables are handled like this:
        if(tse1 != null){ if(tse1.isPlaying()== false){tse1.release(); tse1=  null;} }

        if(tse2 != null){ if(tse2.isPlaying()== false){tse2.release(); tse2=  null;} }

        if(tse3 != null){ if(tse3.isPlaying()== false){tse3.release(); tse3=  null;} }

        if(tse4 != null){ if(tse4.isPlaying()== false){tse4.release(); tse4=  null;} }

A: You can abbreviate that
MediaPlayer tempse;
if(tse1 == null){tempse = tse1;}
else{if(tse2 == null){tempse = tse2;}
else{if(tse3 == null){tempse = tse3;}
else{if(tse4== null){tempse = tse4;}}}}

to
MediaPlayer tempse = null;

Maybe you should change the == to !=
That's the only thing that I can see without knowing what error you get.


text:
Q: WPML - ICL_LANGUAGE_CODE breaks my template Using IF conditional with WPML should be easy but for some reason my template stops working as soon as i place following code in footer.php or everywhere else
<?php
 if (ICL_LANGUAGE_CODE == 'en') {
     //english here
 } else {
     //other languages
 }
?>

Am I missing something?

A: <?php if (ICL_LANGUAGE_CODE == 'en'): ?>
    <!-- english here -->
<?php elseif (ICL_LANGUAGE_CODE == 'es'): ?>
    <!-- spanish here -->
<?php endif; ?>
<!-- ======== Or ======= -->
<?php if (ICL_LANGUAGE_CODE == 'en'): ?>
    <!-- english here -->
<?php else: ?>
    <!-- spanish here -->
<?php endif; ?>


text:
Q: Safari web inspector will not work I clicked the Layers button in the web inspector to see what it would do. Web inspector immediately closed and will not reopen. When I try to open it, either via the Develop menu or the shortcut key Opt-Cmd-I, there is sometimes a very quick flash where the web inspector would be and then it closes.
Is there a fix for this?
EDIT
btw: should have mentioned this is in a Parallels VM where the guest OS is Monterey.
In trying to recover I did a number of steps.

*

*First "resetting" Safari, which just seems to mean clear cache, cookies, and history. No joy.

*Prepare to reinstall Safari. First step is disable SIP in recovery console.

*When I restarted the Monterey VM to do the uninstall/reinstall, I decided to check web inspector first, just in case. Lo and behold, web inspector is working again, and showing the Layers panel.
Go figure.
It would still be great to have a method of fixing this problem that is more direct, as I am not sure if disabling SIP is even related.


text:
Q: Is This a Counterexample in Hausdorff Space? Consider this topology on space X: $\tau=\{A\subset X:x_0\not\in A\text{ or }X-A\text{ is finite}\}$ where $x_0$ is a fixed point. Observe that this space is Hausdorff. However, singletons $\{u\}$ for u not $x_0$ are open. Aren't all singletons supposed to be closed in Hausdorff?
Thanks.

A: Sets are not doors. Sets can be open and closed at the same time. This in particular is true of $\{u\}$ with $u \neq x_0$ (open because $x_0 \notin \{u\}$; the complement of $\{u\}$ is open because $X\setminus\{u\}$ has a finite complement (namely $\{u\}$ again), so $X\setminus \{u\}$ is open, making the set $\{u\}$ itself closed). These are so-called clopen (closed-and-open) sets and they're not uncommon in topology. Closed just means the complement is open, remember? It's not the opposite of open, despite the naming.


text:
Q: Sendto returning random values I call sendto in my udp socket client side like this:
if((num_w = sendto(cli_udp_sock, buffer, strlen(buffer), 0, (struct sockaddr *) &servaddr, sizeof(servaddr) )) < 0)

but there seems to be no nothing received at the server side and in very strange fashion, num_w, when printed out, gives values like:
-197379208
-1440076936
2054978424
And perror() displays "success"
Client code up till that point:
#include <sys/socket.h>       /*  socket definitions        */
#include <sys/types.h>        /*  socket types              */
#include <arpa/inet.h>        /*  inet (3) funtions         */
#include <unistd.h>           /*  misc. UNIX functions      */
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <netdb.h>
/*  Global constants  */

#define MAX_LINE           (1000)
#define LISTENQ (10)

/*  Function declarations  */
int ParseCmdLine(int argc, char *argv[], char **szPort, char **szAddress, char ** serv_udp_port);

/*  main()  */

int main(int argc, char *argv[]) {

    //
short int cli_port;                  /*  port number               */
short int serv_port;
struct    sockaddr_in servaddr;  /*  socket address structure  */
socklen_t serv_addrlen = sizeof(servaddr);
struct    sockaddr_in cliaddr;
char      buffer[MAX_LINE];      /*  character buffer          */
char     *szAddress;             /*  Holds remote IP address   */
char     *szPort;                /*  Holds remote port         */
char     *serv_udp_port;
char     *endptr;                /*  for strtol()              */
int cli_udp_sock;
/*  Get command line arguments  */

ParseCmdLine(argc, argv, &szPort, &szAddress, &serv_udp_port);

/*  Set the remote port */

cli_port = strtol(szPort, &endptr, 0);
serv_port = strtol(serv_udp_port, &endptr, 0);

if ( *endptr )
{
    printf("ECHOCLNT: Invalid port supplied.\n");
    exit(EXIT_FAILURE);
}

/*  Set all bytes in socket address structure to zero, and fill in the relevant data members   */

memset(&cliaddr, 0, sizeof(cliaddr));
cliaddr.sin_family      = AF_INET;
cliaddr.sin_port        = htons(cli_port);
cliaddr.sin_addr.s_addr = htonl(INADDR_ANY);

memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family      = AF_INET;
servaddr.sin_port        = htons(serv_port);

/*  Set the remote IP address  */

if ( inet_aton(argv[2], &servaddr.sin_addr) <= 0 )
{
    printf("ECHOCLNT: Invalid remote IP address.\n");
    exit(EXIT_FAILURE);
}

int list_s;
if ( (list_s = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
{
    fprintf(stderr, "ECHOCLNT: Error creating listening socket.\n");
    exit(EXIT_FAILURE);
}
if (listen(list_s, LISTENQ) < 0)
{
    printf("Failed to called listen.\n");
}
if( ((cli_udp_sock = socket(AF_INET, SOCK_DGRAM, 0) )< 0))
{
    printf("UDP socket was not successfully created. Exiting...\n");
    exit(0);
}

//if(bind(cli_udp_sock, (struct sockaddr *) &cliaddr, sizeof(cliaddr)) > 0);

char command[100];
    /*  Get command from user  */
printf("==============================================\n");

do
{
    if(strcmp(command, "s\n") == 0)
    {
        printf("______________________________________________\n");
            printf("'s' entered, \nEnter the string to request\n"); //prompt for string to enter
            strcpy(buffer, "CAP\n");                //set first set of characteres to CAP\n
            char bucket[100];                   //space for entered string
            fgets(bucket, sizeof bucket, stdin);
        printf("The string entered is: %s", bucket);
            strcat(buffer, bucket);

            /*  Send string to echo server, and retrieve response  */
            int num_w;
        if((num_w = sendto(cli_udp_sock, buffer, strlen(buffer), 0, (struct sockaddr *) &servaddr, sizeof(servaddr) )) < 0)
        {
            perror("error: ");
            printf("Problem writing data to server, errno: %d", errno);
            exit(0);
        }
        else
        {
            perror("error 2: ");
            printf("num_w: %d\n");
        }

Thanks so much in advance!
(Oh and I'm on Kali linux, virtual machine, Windows 10)

A: You aren't printing num_w. You've left it out of the printf() statement. You're just printing whatever random junk is on the stack.

And perror() displays "success"

So num_w was positive. Calling perror() in that case is pointless.