text:
Q: Derivative of $-\csc(2x)$ Is the following reasoning correct?
$$-\csc2x = -1[\csc(2x)\cdot\cot(2x)] = -1[\csc(2x)\cdot\cot(2x)\cdot2\cdot2]$$
I am unsure whether that is correct so far because I do not know if the derivatives of the $\csc$ and $\cot$ need to be taken again due to the chain rule

A: The derivative of the $\csc(x) = -\cot(x)\cdot\csc(x)$
The answer to your question is $2\cot(2x)\csc(2x)$
Simply, you have to use the chain rule.
First of all take the derivative of $\csc$ , then the $2x$ and multiply them.

A: Why don't you simply use sine and cosine?
The derivative can then be easily calculated using basic differentiation rules:
$$
-\frac{d}{dx}\csc(2x)=\frac{d}{dx}\frac{-1}{\sin(2x)}=\frac{1}{\sin^2(2x)}\cdot \cos(2x)\cdot 2=2\cos(2x)\csc(2x)
$$

"Is the following reasoning correct?" NO. You miss the derivative symbol, not to say other aspects.

A: $$\frac{d}{dx}(-\csc (2x))= -\frac{d}{dx}(\csc (2x)) = -\big(-\csc(2x)\cot(2x)\big)\cdot \frac{d}{dx}(2x)$$
$$ = 2\csc (2x)\cot(2x)$$


text:
Q: linux bash shell script - pass through function array variable So in order to be versatile, I make a lot of functions and i want to define my own variable name when i call on that function.
For basic text, numbers it works and this is how I do it
function func_get_device_hostname
{
    local _device_hostname=$1
    local device_hostname2="TEST"
    eval $_device_hostname="'$device_hostname2'"
}

function func_display_device_hostname
{
    func_get_device_hostname device_hostname
    echo $device_hostname
}

but when i use that same method with an array like so
function func_get_vds_ip
{
    func_get_vds_count vds_count
    local _arr_vds_ip=$1
    arr_vds_ip2=()
    i=1
    while [ $i -le $vds_count ]; do
        local arr_vds_ip2+=($(avahi-browse -rvpc vds._tcp | grep "=;" | cut -d ';' -f8 | sed -n $i' p'))
        i=$(($i+1))
    done
    echo ""
    eval $_arr_vds_ip="'$arr_vds_ip2'"
}

function func_display_vds_ip
{
    func_get_vds_ip arr_vds_ip
    echo -n "VDS IP        "
    for i in "${arr_vds_ip[@]}"
    do
        echo -n "$i"
        echo -n " - "
    done
}

I get the following error
line 339: {arr_vds_ip[@]}=192.168.18.82: command not found

line 339 refers to this part of the code
    eval $_arr_vds_ip="'$arr_vds_ip2'"

what is the best method to do this?
am i using a wrong command?

A: You could be using namerefs (See Shell Parameters and search down for "nameref"). Once you declare a nameref, you just use the local variable like a normal variable, and the contents are reflected in the referenced variable.
For the simple case:
function func_get_device_hostname {
    local -n _device_hostname=$1
    local name=TEST
    _device_hostname=$name
}

testing
$ declare -p foo
bash: declare: foo: not found
$ func_get_device_hostname foo
$ declare -p foo
declare -- foo="TEST"

For the array case:
function func_get_vds_ip {
    local -n _arrname=$1
    local count=10 i
    _arrname=()
    for ((i=1; i<=count; i++)); do
        _arrname+=($RANDOM)
    done
}

testing
$ declare -p bar
bash: declare: bar: not found
$ func_get_vds_ip bar
$ declare -p bar
declare -a bar=([0]="23299" [1]="13876" [2]="24702" [3]="17413" [4]="14999" [5]="16309" [6]="25625" [7]="29001" [8]="7117" [9]="23532")

redpajama_set_name: RedPajamaStackExchange


text:
Q: Correlation of Groups and joining to DataFrame import pandas as pd
d = {'Val1': ['A','A','A','B','B','B','C','C','C','D','D','D'], 'Val2':
[5,4,6,4,8,7,4,5,2,1,1,9] , 'Val3': [4, 5,6,1,2,9,8,5,1,5,9,5]}
df = pd.DataFrame(data=d)
df

Output
Val1 Val2 Val3 Val4+++
0   A   5   4
1   A   4   5
2   A   6   6
3   B   4   1
4   B   8   2
5   B   7   9
6   C   4   8
7   C   5   5
8   C   2   1
9   D   1   5
10  D   1   9
11  D   9   5

It is possible to calculate the correlation of two columns with this code, but I am not sure if it is the best/fastest way.
 vers1=df.groupby('Val1')[['Val2','Val3']].corr().iloc[0::2][['Val3']]
 vers2=df.groupby('Val1')[['Val2','Val3']].corr().iloc[0::2]['Val3']

A    Val2  0.500000
B    Val2  0.385727
C    Val2  0.714575
D    Val2 -0.500000

I am not able to join the data to the original data, so they look like this.
  Val1 Val2 Val3 Val4+++
0   A   5   4  0.500000
1   A   4   5  0.500000
2   A   6   6  0.500000
3   B   4   1  0.385727
4   B   8   2  0.385727
5   B   7   9  0.385727
6   C   4   8  0.714575
7   C   5   5  0.714575
8   C   2   1  0.714575
9   D   1   5 -0.500000
10  D   1   9 -0.500000
11  D   9   5 -0.500000

I am open to other ways of calculating the correlation or measures of association if I am able to join them to the original.

A: I hope you are looking for this:
Using little tweaking on merge function will help.
import pandas as pd
d = {'Val1': ['A','A','A','B','B','B','C','C','C','D','D','D'], 'Val2': [5,4,6,4,8,7,4,5,2,1,1,9] , 'Val3': [4, 5,6,1,2,9,8,5,1,5,9,5]}
df = pd.DataFrame(data=d)
df

corr=df.groupby('Val1')[['Val2','Val3']].corr().groupby('Val1').min()[['Val3']]
corr
Out[42]:
          Val3
Val1
A     0.500000
B     0.385727
C     0.714575
D    -0.500000

out=pd.merge(df,corr,on='Val1',how='inner')
out
out
Out[43]:
   Val1  Val2  Val3_x    Val3_y
0     A     5       4  0.500000
1     A     4       5  0.500000
2     A     6       6  0.500000
3     B     4       1  0.385727
4     B     8       2  0.385727
5     B     7       9  0.385727
6     C     4       8  0.714575
7     C     5       5  0.714575
8     C     2       1  0.714575
9     D     1       5 -0.500000
10    D     1       9 -0.500000
11    D     9       5 -0.500000

A: You can shorten the correlation code a bit by doing the correlation on the series:
df.groupby("Val1")["Val2"].corr(df["Val3"])


text:
Q: An integer is required I'm new in Python 3. I use aiohttp module for Python 3.5.
When I run my project, I have a following error
TypeError: an integer is required (got type str)

The stack-trace is:
Traceback (most recent call last):
  File "/home/santi/tesis/tanner/server.py", line 82, in <module>
    srv = loop.run_until_complete(f)
  File "/usr/lib/python3.5/asyncio/base_events.py", line 373, in run_until_complete
    return future.result()
  File "/usr/lib/python3.5/asyncio/futures.py", line 274, in result
    raise self._exception
  File "/usr/lib/python3.5/asyncio/tasks.py", line 240, in _step
    result = coro.send(None)
  File "/usr/lib/python3.5/asyncio/base_events.py", line 949, in create_server
    sock.bind(sa)

The code is:
if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    f = loop.create_server(
        lambda: HttpRequestHandler(debug=False, keep_alive=75),'0.0.0.0','8090')
    srv = loop.run_until_complete(f)
    print('serving on', srv.sockets[0].getsockname())
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass

*

*What is the error in my code?

*What am I doing wrong?

A: The port number should be an Integer:
f = loop.create_server(
    lambda: HttpRequestHandler(debug=False, keep_alive=75), '0.0.0.0', 8090)


text: Q: Dual booting Windows/Ubuntu, Can't extend Ubuntu Partition into allocated space I am dual booting Windows/Ubuntu, but for some reason can not extend the Ubuntu Partition into allocated space. I tried gpartion and doing it in windows and have the same issue, I can see the disk space but I am not allowed to extend my Ubuntu partion into the unallocated space, any ideas? Thank you all.


text:
Q: python function, json.loads() : No JSON object could be decoded The code is very simple:
import requests
import json

r = requests.get('https://www.baidu.com/')
r.encoding = 'utf-8'
json.loads(r.text,'utf-8')

I always recieve this error information:
Traceback (most recent call last):
File "<pyshell#57>", line 1, in <module>
json.loads(r.text,'utf-8')
File "C:\Python27\lib\json\__init__.py", line 352, in loads
return cls(encoding=encoding, **kw).decode(s)
File "C:\Python27\lib\json\decoder.py", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python27\lib\json\decoder.py", line 382, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

Can anyone help me solving this problem? Thanks!

A: This code will help you to figure out what's going on ;)
import requests
import json

r = requests.get('https://www.baidu.com/')
r.encoding = 'utf-8'

try:
    foo = json.loads(r.text, 'utf-8')
    print "Yay, I got a json from baidu!"
except Exception, e:
    print "Why didn't i get a json from baidu? Maybe it wasn't a json..."
    print "What is it then? It seems is a {0} whose length is {1}".format(
        r.text.__class__, len(r.text)
    )


text:
Q: Change UITextView Font w/o Removing Bold/Underline/Italics Formatting I have a UITextView in an iOS app, and I want to allow the user to bold/italicize/underline/etc at will, so I gave set the allowsEditingTextAttributes property to true on the text view. However, I would also like to allow the user to change things like font and color. Currently, it seems that changing even the color property of the UITextView resets the formatting of the UITextView (i.e. gets rid of the bolding/italics/etc). Is there any way to change this without resetting the formatting? For reference, I am currently doing this to change the color:
self.textView.textColor = colorTheUserPicked //a UIColor picked by the user

EDIT: Actually, this was my bad, I was also resetting the value of the text property itself when I changed the color. Removing that allowed me to change the color as desired. However, I still can't change the font or even the font size without removing the bold/italics/etc. I realize this might be impossible, though...

A: I'll answer with an Objective-C solution since I don't code in Swift, but it should be translated easily into Swift.
NSAttributedString "effects" are stored in a NSDictionary. So it's a Key:Value system (with unicity of Key).
Bold/Italic (from your example) are inside the NSFontAttributedName's value. That's why you can't set it again like this.
The main key is to use enumerateAttributesInRange:options:usingBlock::
[attr enumerateAttributesInRange:NSMakeRange(0, [attr length])
                         options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired
                      usingBlock:^(NSDictionary *attributes, NSRange range, BOOL *stop)
 {
     NSMutableDictionary *newAttributes = [attributes mutableCopy];
    //Do changes
    [attr addAttributes:newAttributes range:range]; //Apply effects
 }];

The following lines are at "//Do changes" place.
So, if you want to change the Font size:
if ([newAttributes objectForKey:NSFontAttributeName])
{
    UIFont *currentFont = (UIFont *)[attributes objectForKey:NSFontAttributeName];
    UIFont *newFont = [UIFont fontWithName:[currentFont fontName] size:[currentFont pointSize]*0.5];//Here, I multiplied the previous size with 0.5
    [newAttributes setValue:newFont forKey:NSFontAttributeName];
}

If you want to bold/italic, etc. the font you may be interested in UIFontDescriptor, and a related question.
It shows you how to get the previous font and change get a new font with some commons with the previous one.
If you want to change the color:
if ([newAttributes objectForKey:NSForegroundColorAttributeName])//In case if there is some part of the text without color that you don't want to override, or some custom- things
{
     UIColor *newColor = [UIColor blueColor];
    [newAttributes setValue:newColor forKey:NSForegroundColorAttributeName];
}

The underline effect is in NSUnderlineStyleAttributeName's value. So analogic changes can be done.

A: Thanks @Larme! Your solution is correct, so I accepted it! Here is the Swift version for reference:
//needs to be a mutable attributed string
var mutableCopy = NSMutableAttributedString(attributedString: textView.attributedText)

//make range
var textRange = NSMakeRange(0, textView.attributedText.length)

//get all the string attributes
textView.attributedText.enumerateAttributesInRange(textRange, options: NSAttributedStringEnumerationOptions.LongestEffectiveRangeNotRequired, usingBlock: { (attributes, range, stop) -> Void in
    //make a copy of the attributes we can edit
    var newAttributes = attributes as [NSObject : AnyObject]
    if newAttributes[NSFontAttributeName] != nil { //if the font attr exists
        //create a new font with the old font name and new size
        let currentFont = newAttributes[NSFontAttributeName] as UIFont
        let newFont = UIFont(name: currentFont.fontName, size: currentFont.pointSize * 0.5) //set new font size to half of old size
        //replace the nsfontattribute's font with the new one
        newAttributes[NSFontAttributeName] = newFont
    }
    //replace the old attributes with the new attributes to the mutable version
    mutableCopy.addAttributes(newAttributes, range: range)
})
//replace the old attributed text with the newly attributed text
textView.attributedText = mutableCopy

A: Implemented similar for C# for Xamarin.IOS.
    NSError error = null;
        var htmlString = new NSAttributedString(NSUrl.FromFilename(
            "About.html"),
            new NSAttributedStringDocumentAttributes {DocumentType = NSDocumentType.HTML},
            ref error);

        var mutableCopy = new NSMutableAttributedString(htmlString);

        htmlString.EnumerateAttributes(new NSRange(0, htmlString.Length),
            NSAttributedStringEnumeration.LongestEffectiveRangeNotRequired,
            (NSDictionary attributes, NSRange range, ref bool stop) =>
            {
                var newMutableAttributes = new NSMutableDictionary(attributes);
                if (newMutableAttributes[UIStringAttributeKey.Font] != null)
                {
                    var currentFont = newMutableAttributes[UIStringAttributeKey.Font] as UIFont;
                    if (currentFont != null)
                    {
                            var newFontName = currentFont.Name;

                            if (currentFont.Name.Equals("TimesNewRomanPS-BoldItalicMT"))
                            {
                                newFontName = "HelveticaNeue-BoldItalic";
                            }
                            else if (currentFont.Name.Equals("TimesNewRomanPS-ItalicMT"))
                            {
                                newFontName = "HelveticaNeue-Italic";
                            }
                            else if (currentFont.Name.Equals("TimesNewRomanPS-BoldMT"))
                            {
                                newFontName = "HelveticaNeue-Bold";
                            }
                            else if (currentFont.Name.Equals("TimesNewRomanPSMT"))
                            {
                                newFontName = "HelveticaNeue";
                            }

                            newMutableAttributes.SetValueForKey(UIFont.FromName(newFontName, currentFont.PointSize * 1.5f), UIStringAttributeKey.Font); //  = newFont;
                    }
                    else
                    {
                        newMutableAttributes.SetValueForKey(UIFont.FromName("HelveticaNeue", 14), UIStringAttributeKey.Font); //  Default to something.
                    }
                }

                mutableCopy.AddAttributes(newMutableAttributes, range);
            });

        aboutTextView.AttributedText = mutableCopy;


text:
Q: My data has comma in the value of the column which is also a delimiter, how to read it by csv.reader in python This is how my data looks,
"id","text"
"416752", "i's ** This year's theme is \"Each for Equal\".**  When: Friday March 6th Time: 10:00am-12:00pm  Where:  HQ 155 Gordon Baker Road, 5th floor, Halifax/Dartmouth Boardoom   Please note there are 2 shifts - one to log your attendance for the event and the other to log your donation, if applicable.    Structure of the Event  10h00am - 10h15am:   Welcome, cupcakes, coffee, social media picture opportunity (#eachforequal)  10h15am – 10h25am:   Intro from WIA, IWD, theme introduction, agenda, community initiative: Dress for Success  10h30am – 11h15am:   Keynote Speaker (Shasta Townsend)  11h30am – 12h00pm:   Panel Stories (Mike Sharun, Dennis Hoffman, Barbara Dahan and Nikki Matarazzo)     **"

Below is the logic i have tried:
import csv
import codecs
file_path=r'C:\data.csv'
f = codecs.open(file_path, encoding = "utf8", errors ='replace')
csvreader = csv.reader(f, delimiter=',')
for row in csvreader:
    print(row)

Output:
['416752', 'i\'s ** This year's theme is \\Each for Equal\\".**  When: Friday March 6th Time: 10:00am-12:00pm  Where:  HQ 155 Gordon Baker Road', '5th floor', 'Halifax/Dartmouth Boardoom   Please note there are 2 shifts - one to log your attendance for the event and the other to log your donation', 'if applicable.     Structure of the Event    10h00am - 10h15am:   Welcome', 'cupcakes', 'coffee', 'social media picture opportunity (#eachforequal)  10h15am – 10h25am:   Intro from WIA', 'IWD', 'theme introduction', 'agenda', 'community initiative: Dress for Success  10h30am – 11h15am:   Keynote Speaker (Shasta Townsend)  11h30am – 12h00pm:   Panel Stories (Mike Sharun', 'Dennis Hoffman', 'Barbara Dahan and Nikki Matarazzo)     **"']

Instead of two values, i am getting more than that as my data is having many commas.

A: The space after the comma is the problem.  Use skipinitialspace=True to remedy this.  Also recommend using built-in open.  With your updated data, you also need doublequote=False and escapechar='\\'.
Double quotes within a string is default-escaped by doubling the character, e.g. "Say, ""Hi!""", but your example uses a backslash to escape, e.g. "Say, \"Hi!\"".  The two additional options disable doubling of the quote, and to use the escape character instead.
import csv

file_path = 'data.csv'
with open(file_path, encoding='utf8', newline='') as f:
    csvreader = csv.reader(f, skipinitialspace=True, doublequote=False, escapechar='\\')
    for row in csvreader:
        print(row)

Output:
['id', 'text']
['416752', 'i\'s ** This year's theme is "Each for Equal".**  When: Friday March 6th Time: 10:00am-12:00pm  Where:  HQ 155 Gordon Baker Road, 5th floor, Halifax/Dartmouth Boardoom   Please note there are 2 shifts - one to log your attendance for the event and the other to log your donation, if applicable.    Structure of the Event  10h00am - 10h15am:   Welcome, cupcakes, coffee, social media picture opportunity (#eachforequal)  10h15am – 10h25am:   Intro from WIA, IWD, theme introduction, agenda, community initiative: Dress for Success  10h30am – 11h15am:   Keynote Speaker (Shasta Townsend)  11h30am – 12h00pm:   Panel Stories (Mike Sharun, Dennis Hoffman, Barbara Dahan and Nikki Matarazzo)     **']

A: As is mentioned in this question Why is the Python CSV reader ignoring double-quoted fields? you'll need to add the skipinitalspace param so that csv.reader will understand the quotes.
import csv
import codecs
file_path=r'C:\data.csv'
f = codecs.open(file_path, encoding = "utf8", errors ='replace')
csvreader = csv.reader(f, delimiter=',', skipinitialspace=True)
for row in csvreader:
    print(row)


text:
Q: Unsure of how to create a particular diagram for slice/coslice categories I'm using Tikz-cd and trying to follow this http://www.jmilne.org/not/Mtikz.pdf but I can't seem to get a diagram like this (taken from Algebra Chapter 0 by Aluffi)

The diagram I'm most concerned with is the morphism diagram below that I cannot figure out.
Much appreciated.

A: It is very simple with tikz-cd:
\documentclass{article}
\usepackage{amsmath,tikz-cd}

\begin{document}

\begin{tikzcd}
&& A \\
Z_1 \arrow[r,"\sigma"]
    \arrow[urr,bend left,"f_1"]
    \arrow[drr,bend right,swap,"g_1"] &
Z_2 \arrow[ur,"f_2"]
    \arrow[dr,swap,"g_2"] \\
&& B
\end{tikzcd}

\end{document}

Left and right refers to the side of the arrow just like when we talk about river banks (from source to end). The label is placed by default on the left side, but swap allows to change this.
The r means "the target is the cell at the right", whereas urr means "the target is the cell two steps on the right and one step up". You have to imagine the objects in a grid like a matrix. In this case a 3 by 3 matrix.

The historic alternative, which probably the author used, is Xy-pic.
\documentclass{article}
\usepackage{amsmath}
\usepackage[all,cmtip]{xy}

\begin{document}

\xymatrix@R-1pc{
&& A \\
Z_1 \ar[r]^\sigma
    \ar@/^1pc/[urr]^{f_1}
    \ar@/_1pc/[drr]_{g_1} &
Z_2 \ar[ur]^{f_2}
    \ar[dr]_{g_2} \\
&& B
}

\end{document}


text:
Q: A duality generalizing Lefschetz duality of a non-compact manifold I am trying to solve out Exercise 3.3.35 of Hatcher's Book on Algebraic Topology:

I have two basic questions:

*

*How to define the long exact sequence in the first row? For example, can we first find a directed system of long exact sequences, which will be the first row after the direct limit is taken?

*After the proceeding question is solved, how to prove that the second vertical mapping is an isomorphism? I am wondering it because it is essential to the application of the five-lemma and any other duality with boundary in the book, e.g., Lefschetz duality, does not apply to it because $M$ now is non-compact.


text:
Q: twilio, sinatra ruby force hangup and then callback I want to call my Twilio number which hangs up immediately and then calls me back. This is similar (but not identical) to a previous question of mine.
The problem lies with forcing Twilio to hang up.
The ruby code is:
    get '/callback' do
    to = params['From']
    from = 'my Twilio number'
    "<Response><Hangup/></Response>"
    sleep 5
    # set up a client to talk to the Twilio REST API
    @client = Twilio::REST::Client.new account_sid, auth_token
    @call = @client.account.calls.create(
    :from => from, # From your Twilio number
    :to => to, # To any number
    # Fetch instructions from this URL when the call connects
    :url => 'https://dl.dropboxusercontent.com/u/85088004/twilio/twilio.xml'
    )
end

This produces a message: "We are sorry but a system error has occurred". The problem lies with the hangup instruction. I have tried as above and also
<Response><Hangup/></Response> #without enclosing double or single quotes

and
Twilio::TwiML::Response.new do |r|
r.Hangup
end.text

Neither produces the desired result of hangup.
What's wrong?
Many thanks in advance!

A: You should check your Twilio Debugger at twilio.com/user/account/debugger. This will give more information about the failure.

A: Definitely go with @Kevin's advice and get in touch with Twilio support. But one comment I would like to add. At the end of your /callback action, the last value is the @call variable you are assigning when you create a call, Ruby will be trying to return this value as the result of the HTTP request.
Ruby returns the last value evaluated at the end of a method. In this case, that value is what Sinatra responds to the HTTP Get request with by default.
Judging by the literal string you have <Response><Hangup/></Response>, I'm guessing you are not using a view, and expect that to be the result of the get request. You should place that at the very end of your method as below. I've also added a content_type which just sets the response header to say the response is XML.
get '/callback' do
    to = params['From']
    from = 'my Twilio number'
    # set up a client to talk to the Twilio REST API
    @client = Twilio::REST::Client.new account_sid, auth_token
    @call = @client.account.calls.create(
      :from => from, # From your Twilio number
      :to => to, # To any number
      # Fetch instructions from this URL when the call connects
      :url => 'https://dl.dropboxusercontent.com/u/85088004/twilio/twilio.xml')
    #ruby returns the last value in a method:
    content_type 'text/xml'
    "<Response><Hangup/></Response>"
end

Make sure that you have your Twilio Voice Callback set to a Get request as well (the default is post).
I've also removed the sleep 5 that you had in there. I can see where you are going with it. Respond with the hangup TwiML, wait a few seconds, then make a new call. Sadly, Sinatra doesn't quite work that way. It will not respond to the HTTP request until the end of the method. So you're just going to have it sit and wait for 5 seconds with no reason.
This does pose a bit of an issue, as you tell Twilio to make an outbound call to the number that you are about to hangup on, so you basically have a race condition. Does the call disconnect first, or does the outbound start ringing to a busy number.
There are a number of ways of doing this, but I'd suggest a thread. It's a little tricky, but this SO answer goes into some detail.


text:
Q: What URL should I use with Expo to redirect to a published app? I am performing some OAuth autentication and I need to redirect from the Expo WebBrowser back to my application. I can do it with the development URL exp://some-code.name.app-name.exp.direct/+/redirect as shown in the example project https://github.com/expo/auth0-example. However, I am not sure what URL to use with the published application. Something like https://exp.host/@name/app-name/+/redirect or exp://exp.host/@name/app-name/+/redirect or something completely different?

A: why you don't just use
 redirectUri = `${Expo.Constants.linkingUri}/redirect`


text:
Q: Flat manifolds and irreducible representations Let $M$ be a compact Riemannian manifold with vanishing curvature of Levi-Civita connection. Such manifolds were classified by Bieberbach; sometimes they are called Bieberbach manifolds. According to this classification, a Bieberbach manifold is a quotient of a torus by a finite group freely acting on it by isometries. Crystallographic group is a fundamental group of a Bieberbach manifold. There is an exact sequence
$$ 0 \rightarrow {\mathbb Z}^n \rightarrow G \rightarrow L\rightarrow 0,$$
where $G$ is a crystallographic group, ${\mathbb Z}^n$ a group of translations in $G$,
and $L$ the holonomy group of the Levi-Civita connection. The group $L$
is naturally embedded to the group $GL(T_xM)$ of automorphisms of the tangent space of the Bieberbach manifold.
Could $T_x M$ be irreducible as a representation of $L$?
I have checked for dimension $\leq 5$, and  $T_xM$
is never irreducible for dimension $\leq 5$.

A: Here is the solution (with thanks to Misha Kapovich
who pointed this out).
Gerhard Hiss, Andrzej Szczepanski,
"On torsion free crystallographic groups",
Journal of Pure and Applied Algebra
Volume 74, Issue 1, 10 September 1991, Pages 39-56
Abstract:
The torsion free crystallographic groups arise as fundamental groups of compact flat Riemannian manifolds. Let R be a crystallographic group with point group G and translation group T. In this paper we consider the G-module T⊗z, for which we prove: If R is torsion free, then G does not act irreducibly on T⊗z. A proof of this theorem for solvable groups G was first given by G. Cliff. The theorem proves a conjecture made by the second author. The proof of the theorem uses the classification of the finite simple groups.


text:
Q: Convert varchar to timestamp on PostgreSQL: ERROR: "TZ"/"tz" not supported I have the following problem. I work on converting timestamps stored in a varchar column:
|    MyTimestamp               |
---------------------------------
|"Thu May 14 00:00:00 CEST 2009"|
|"Fri Aug 31 00:00:00 CEST 2007"|

with the to_timestamp function:
 select
    to_timestamp(myTimestamp, 'Dy Mon DD HH24:MI:SS TZ YYYY'
 FROM
    my_table

but I keep getting:
ERROR:  "TZ"/"tz" not supported

********** Error **********

ERROR: "TZ"/"tz" not supported
SQL state: 0A000

I wonder what I did wrong, is there a better way to convert a varchar to timestamp? Does not PostgreSQL support TZ/tz?

A: try this syntax:
SELECT 'Fri Aug 31 00:00:00 CEST 2007'::timestamp

this would be
SELECT myTimestamp::timestamp FROM my_table


text:
Q: Accessing the current overlay number in beamer For some beamer related code in one of my packages I need to access the current overlay number. I mean the internal number used for things like \only<1>{..}.
\only<1>{ Some internal number must be one in here }
\only<2>{ But 2 in here }
\only<1-5>{\includegraphics[page=(current overlay number)]{...}}

I checked the beamer manual and could find any information about this. I checked the source code and found some related macros/counters but they didn't held always the correct values. \beamerpauses seems not the correct one either. Does anyone now the "offical" counter/macro for this number?

A: You may be looking for the internal counter
\beamer@slideinframe

as defined in beamerbasedecode.sty: It is the value beamer consults when encountering something like \only<1,3-5>{...} to check whether to display or to hide the content.
A small demonstration on how to access this value:
\documentclass{beamer}
\makeatletter
\newcommand*{\overlaynumber}{\number\beamer@slideinframe}
\makeatother
\begin{document}
\begin{frame}
\only<1>{ Some internal number must be \overlaynumber\ in here }
\only<2>{ But \overlaynumber\ in here }

\only<1-5>{Graphic \overlaynumber}
\end{frame}
\end{document}


text:
Q: Triggering click with jQuery to hit code-behind function not working in 1.4 - Worked fine in 1.3.2 I have a gridview in an update panel and am using a jQuery dialog for adding entries.
The dialog calls an AJAX/JSON function that adds the entry.  On success of that function I have jQuery trigger a button click on a hidden button
   ...
       success: function(msg) {
             $("[id$='_btnUpdateGrid']").trigger('click');
             $("#new_dialog").dialog('close');
         },
   ...

which should hit an event handler in the code behind to update the datasource and refresh the gridview.
<asp:Button ID="btnUpdateGrid" runat="server"  OnClick="btnUpdateGrid_Click"
Text=" " Width="1px" Height="1px" Style="background-color:#F5F3E5; border:none;"  />

This has worked just fine with 1.3.2.  Updated to 1.4.1 and it no longer hits the code-behind.  The AJAX still works but I have to manually refresh the page to update the grid.
Also, I can hit client side event handlers (e.g OnClientClick="alert('hello')") so I know the click is still happening just not the code-behind event handler.  It's like jquery is somehow blocking the page from doing just that now.  I have verified this by just changing the version number in the script reference path and seeing the functionality change.
Is this a bug or s there another way I'm supposed to do this now?

A: You might try changing ID to id or vice-versa. It could be a case-sensitive identifier issue.

A: Perhaps try binding the event handler to the buttons using JavaScript, instead of doing it with an onClick attribute in the HTML. jQuery lets you do that using live event bindings:
$("[id$='_btnUpdateGrid']").live("click", btnUpdateGrid_Click);
I'm not sure that'll do anything to solve the problem, but it's worth a try.

A: Turns out it was just the order.  Not sure why 1.3 didn't mind the order but that's all it took.
 ...
   success: function(msg) {
         $("#new_dialog").dialog('close');
         $("[id$='_btnUpdateGrid']").trigger('click');
     },
 ...

works fine.


text:
Q: the sum of values of a second column of a file I have a txt file containing on each line 2 values separated by a space:
x1 y1
x2 y2
x3 y3
...
xn yn

I want to get another file containing:
x1 y1
x2 y1+y2
x3 y1+y2+y3
...
xn y1+y2+y3+...+yn

What is the quickest (I mean easiest) way to do this in python ?

A: This will get you started.
Given data.txt:
1 1
2 2
3 3
4 4

and this code snippet:
with open('data.txt') as inf:
    ysum = 0
    for line in inf:
        line = line.split()
        x, y = [float(i) for i in line]
        ysum += y
        print x, ysum

will give you (using float() above):
1.0 1.0
2.0 3.0
3.0 6.0
4.0 10.0

On the other hand, if you wanted the lines with the +:
with open('data.txt') as inf:
    yline = []
    for line in inf:
        line = line.split()
        x = int(line[0])
        yline = '+'.join(yline + [(line[1])])
        print x, yline
        yline = [yline]

will give you (using int() this time):
1 1
2 1+2
3 1+2+3
4 1+2+3+4

I suspect the above code, esp the 2nd one, could probably be streamlined/optimized more, but should be sufficient to get you started.
You still will have adjust the conversion from string to appropriate type (float or int) and also create the output file and write to it in the format you prefer. These are details you can best decide.

A: The simplest way code-wise is numpy.cumsum() if you already use numpy arrays:
import numpy as np

a = np.loadtxt("input.txt")
a[:,1].cumsum(out=a[:,1]) # accumulate values in the 2nd column
np.savetxt("output.txt", a) #note: you could specify fmt="%d" for integer array

A: with open('input.txt') as inf, open('output.txt','w') as outf:
    datatype = int    # or float
    yy = 0
    for line in inf:
        x,y = line.split()
        yy += datatype(y)
        outf.write('{} {}'.format(x, yy))

A: data.txt:
1 10
2 20
3 30
4 40

code:
with open('data.txt') as f1,open('output.txt','w') as f2:
    lis=[map(int,line.split()) for line in f1]
    for i,z in enumerate(lis):
        f2.write("{0:d} {1:d}\n".format(z[0],sum(lis[j][1] for j in range(i+1))))

output:
1 10
2 30
3 60
4 100


text:
Q: AWS Systems Manager get inventory is not returing everything? I am running a query against our environment using the AWS CLI. My query does not return everything that is listed in the Systems Manager console.
I have compared the output of the above command with what is listed in the Systems Manager console. Some stuff is definitely missing.
aws ssm get-inventory --query 'Entities[].Data[]."AWS:InstanceInformation"[].Content[].[ComputerName, IpAddress, PlatformName]'

My expected results were to get a list of everything that the Systems Manager console shows in inventory.


text:
Q: Google maps Browser very slow & crashing when loading very large data with markers I am building a GPS based tracking application and the idea is to show the total route of the vehicle in the last 24 hours with data coming at an average of every half a minute.
Along with these data, there are all sorts of goefences, route markers, various color codes based based on different conditions of vehicle in transit, different images on routes based on the different angles the GPS device sends the data.
With all these in mind, the data is very large and a lot of logic and conditions in place.
We are loading the google map by creating the xml and rendering on the map as layers and putting the other colour icons
Loading Markers from XML file to Google Map API  approach is the base of the implementation.
We are ajax refreshing the map every 3 seconds and placing the complete xml with layers.
Problems:

*

*The map with icons and images jerks every time the ajax calls are
made and the feel of automated map updating is not happening

*When huge amount of data is present on the map, the application gets very
slow and browser crashes quite a few times

Help needed:

*

*Is XML loading the most optimized way to load the maps?

*Is there other better options - Please suggest

*Lot of forum points to
https://developers.google.com/maps/documentation/javascript/kmllayer
Is this the apprach that needs to be taken

A: I think you need to do some optimization on displaying your data. The XML method is fine, the problem is you just have too many of them.
First thing you can do it to use the getBounds() method in the google.maps.Map class, and only display the markers that are within the user's view. It's like why draw 10,000 data when user can only see 10 of them?

You should also listen to the bounds_changed event so that you can update your view accordingly.
Secondly, you totally don't want to show all the markers even when user are looking at a wide area, not only it is slow, but also it is a horrible experience to have.

Instead you should group your data, just like what the iOS' Photos app's group by area function had do.

Also recycle your markers rather than deleting and creating.


text:
Q: Regarding Vcom on LPC1769 I am using the ARM-based microcontroller LPC1769 and the LPCXpresso IDE. I am using an example project for Vcom using USB Device controller in 1769. By default it works at 9600 baud. But I don't understand how to change the baud rate - I want to use it at higher baud rate.

A: Please define every thing well for better answer, I am providing the computer side answer,
If you are connection with Computer, Its using generic Com port which will be assigned to the device,
now, again if you are using computer, the com port have configuration. go to device manager, and see properties>> Configuration>> there you will see baud rate.
go and change that,
that will do. :)
Edit: Updated with links of support in Driver Side,
I have few link for the same VCP(Virtual Comp Port) Drivers you can use
http://www.ftdichip.com/Drivers/VCP.htm

and Documentation for the same in different different case, please refer documentation first :)
http://www.ftdichip.com/Support/Documents/DataSheets.htm

this is all from my side :)


text:
Q: Load class from war before ear in JBoss 5 I have an ear which contains a war.
Jars are in the ear lib directory.
I need to override a class from a jar and I wrote it in the war.
But when I deploy the ear, the classloader takes the class from the jar and not from the war.
I set this configuration in the jboss-web.xml in the war. I believe it forces the classloader to take classes from war before jar but it doesn't work.
<class-loading java2ClassLoadingCompliance="false">
    <loader-repository>
        com.example:archive=unique-archive-name
    <loader-repository-config>java2ParentDelegation=false</loader-repository-config>
    </loader-repository>
</class-loading>

How can I force the jboss classloader to take classes from war before the jar ?
Thanks.

A: It seems that the jboss-web.xml configuration of the war is ignored when it is embedded in an ear (see
http://www.openscope.net/2010/07/15/setting-up-a-jboss-instance-v5-x-class-loading/).
Have you tried to use jboss-classloading.xml files and to add the top-level-classloader attribute in the war (see http://phytodata.wordpress.com/2010/10/21/demystifying-the-jboss5-jboss-classloading-xml-file/)?


text:
Q: Limit Git Diff to one or more functions? I set *.py diff=python in .git/info/attributes. So Git knows where function boundaries. git diff -W can even make sure the whole function is shown.
But is there a way to limit the output of a git diff to just a particular function (or more than one)?
(Failing that, I guess it's awk...)
EDIT This would also be useful for git log and git rev-list: don't show me every commit that modifies views.py, show me commits that modify a certain function in it. (Yes, in an ideal world, views.py wouldn't be a 2000 line behemoth frequently modified by 8 different developers...)

A: Ok, thanks to Birei, we have a solution.
Use the awk script in that answer, combined with a bit of bash:
~/scripts/grit:
#!/bin/bash
cmd=$1
shift 1
if [ "$cmd" = "" ]; then
  git
# other commands not relevant to this question go here
elif [ $cmd = "funcdiff" ]; then
  git show "$1:$3" | awk -f ~/scripts/getfunc.awk -v f=$4 > /tmp/.tmp1
  git show "$2:$3" | awk -f ~/scripts/getfunc.awk -v f=$4 > /tmp/.tmp2
  git diff -W --no-index /tmp/.tmp1 /tmp/.tmp2

else
  git $cmd $@
fi

Example usage: grit funcdiff 009e75 8b7a14 ./staging.py write_uploaded
This could also be added as a git alias in ~/.gitconfig

A: I didn't find any other option (other than the --function-context or its -W short option, already mentioned) able to restrict a diff output to a single function.
And even that -W option isn't always enough, knowing that a 'function' can vary greatly from language to language, as illustrated in this blog post:

I've found this option rather unreliable, at least within a large PHP class.
  My tests found --function-context often results in displaying almost all of the original file, and git appears ignorant of PHP's function boundaries.
  The number of context lines before and after a change seem random, and the diff doesn't necessarily always show all lines of the function, either.
The original patch message that introduced this change sheds some light:

This implementation has the same shortcoming as the one in grep, namely that there is no way to explicitly find the end of a function.
    That means that a few lines of extra context are shown, right up to the next recognized function begins.

So it appears detecting a function's boundaries is difficult for git.
  It seems in this instance, git never detects a function boundary and gives us the context of the entire file.

As the OP Steve Bennett points out, a potential solution would be to define a git alias which would extract the function in the revision before and after modification, in order to diff on those 2 'temp' files.
Example in "Creating Git Aliases" and "Bash script to select a single Python function from a file".
This is an ad-hoc solution which will be able to parse the specific type of source the OP happens to work with in his repo.


text:
Q: Accessing a Flexible array Member in C I have a struct that looks like this:
typedef struct TestCase TestCase;
typedef struct TestCase {
    char * userName;
    TestCase *c[];    // flexible array member
} TestCase;

And in another File I'm trying to set the flexible array member to NULL, but this doesn't seem to work (I'm not allowed to change how it's been defined)
void readIn(FILE * file, TestCase ** t) {
    *t = malloc(sizeof(TestCase));

    (*t)->c = NULL; //gives the error

}

I'm using double pointers because that's what's been specified for me (This isn't the entire code, but just a snipit). (As there is also code later to free the variables allocated).
Any help would be greatly appreciated.

A: Take a look at this line:
 (*t)->c = NULL;

This tries to assign NULL to an array, which isn't allowed. It would be like writing something like this:
int array[137];
array = NULL; // Not allowed

When you have a flexible array member, the intent is that when you malloc memory for the object, you overallocate the memory you need to make room for the array elements. For example, this code
*t = malloc(sizeof(TestCase) + numArrayElems * sizeof(TestCase*));

will allocate a new TestCase which has an array of numArrayElems pointers.
If you don't know in advance how many pointers you'll need, then you probably should switch away from using flexible array members and just use normal pointers.


text:
Q: pyodbc issue: ODBC driver not found on MacOS My environment

*

*Python: 3.9.7

*pyodbc:  4.0.32

*OS: MacOS 12.0.1, Apple M1 Max

*DB: Azure SQL

*driver: ODBC Driver 17 for SQL Server

Running
import pyodbc

server   = 'myserver.database.windows.net'
database = 'mydb'
username = 'myuser'
password = 'mypassword'
odbc_driver = '{ODBC Driver 18 for SQL Server}'

conn_str = (
    f"Driver={odbc_driver};"
    f"Server=tcp:{server},1433;"
    f"Database={database};"
    f"Uid={username};"
    f"Pwd={password};"
    "Encrypt=yes;"
    "TrustServerCertificate=no;"
    "Connection Timeout=30;")

print(conn_str)

cnxn = pyodbc.connect(conn_str)

outputs
Driver={ODBC Driver 18 for SQL Server};Server=tcp:myserver.database.windows.net,1433;Database=mydb;Uid=myuser;Pwd=mypassword;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;
Traceback (most recent call last):
  File "/Users/....", line 21, in <module>
    cnxn = pyodbc.connect(conn_str)
pyodbc.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 18 for SQL Server' : file not found (0) (SQLDriverConnect)")

Using the same connection string in isql:
isql -v -k "Driver={ODBC Driver 18 for SQL Server};Server=tcp:<server>,1433;Database=<db>;Uid=<user>;Pwd=<pw>;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;"

returns Connected and queries are possible
Drivers are on my machine, I tried first with ODBC Driver 17 for SQL Server, then installed ODBC Driver 18 for SQL Server with same result.

How can I fix this? Created a GitHub issue as well here

A:
Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib
'ODBC Driver 17 for SQL Server' : file not found (0)
(SQLDriverConnect)")

According to the Above Error drivers are properly not installed .However, for ODBC Driver 17 for SQL server ,Please follow the official document Installing the Microsoft ODBC Driver for SQL Server on MacOS.
Another way to Solve an Error, check whether your driver is installed or not then, follow the driver path
Example : "/user/local/lib/libmsodbcsql.17.dylib" , Replace Driver value as shown in below code.
cnxn = pyodbc.connect('DRIVER={/user/local/lib/libmsodbcsql.17.dylib};SERVER=ServerName,1433;DATABASE=DatabaseName;UID=Username;PWD=password')

Reference:
https://docs.snowflake.com/en/user-guide/odbc-mac.html#installing-and-configuring-the-odbc-driver-for-macos

A: /bin/bash -c "$(curl -fsSL
https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
brew tap microsoft/mssql-release https://github.com/Microsoft/homebrew-
mssql-release
brew update
brew install msodbcsql@13.1.9.2 mssql-tools@14.0.6.0

These commands is for MacOS exactly. You can check here https://learn.microsoft.com/en-us/sql/connect/odbc/linux-mac/install-microsoft-odbc-driver-sql-server-macos?view=sql-server-ver16


text:
Q: genealogytree add uncle's wife and cousins I would like to add a wife for the uncle in the family tree shown below and to add their children (self's cousin). While this seems to be an extremely simple task, I have struggled unsuccessfully to do it.

The code for my MWE is as follows:
\documentclass{article}
\usepackage[all]{genealogytree}
\begin{document}

\begin{tikzpicture}
  \genealogytree[template=signpost,
    highlight/.style={pivot,box={colback=yellow!20,no shadow,fuzzy halo}}
  ]{
    parent{
        g[female]{sister}
        c[highlight,male]{Self}
        c[male]{brother}
        c[female]{sister}
        parent{
            c[male]{uncle}
            g[highlight,male]{father}
            parent
              {
                g[highlight,male]{grandfather}
                p[highlight,male]{great grandfather}
                p[female]{great grandmother}
              }
            parent{
                g[female]{grandmother}
              }
          }
        parent
          {
            g[female]{mother}
          }
      }
  }
\end{tikzpicture}

\end{document}

A: This should suit your requirement

MWE
\documentclass{standalone}
\usepackage[all]{genealogytree}
\begin{document}

\begin{tikzpicture}
  \genealogytree[template=signpost,
    highlight/.style={pivot,box={colback=yellow!20,no shadow,fuzzy halo}}
  ]{
        child{ g{ggf} p{ggm}
                child{ g{gf} p{gm}
                        child{ g{father}p{mother}
                                c{sister}c{self}c{brother}c{sister}}
                        child{ g{uncle}p{uncle wife}
                                c{child1}c{child2}c{child3}}}}}
\end{tikzpicture}

\end{document}

EDIT
Maybe the OP wanted the color version -- since there is nothing to do else in the lock-down here is color version

MWE
\documentclass{standalone}
\usepackage[all]{genealogytree}
\begin{document}

    \begin{tikzpicture}
    \genealogytree[template=signpost,
    highlight/.style={pivot,box={colback=yellow!20,no shadow,fuzzy halo}}
    ]{
        child{ g[male, highlight]{great gramps} p[female]{great grandma}
            child{ g[male, highlight]{gramps} p[female]{grandma}
                child{ g[male, highlight]{father}p[female]{mother}
                    c[female]{sister}c[male, highlight]{self}c[male]{brother}c[female]{sister}}
                child{ g[male]{uncle}p[female]{uncle wife}
                    c[male]{cousin1}c[male]{cousin2}c[female]{cousin3}}}}}
    \end{tikzpicture}

\end{document}


text:
Q: disabled bootstrap button can be accessed from tabbing So by doing the below the button is supposed to be disabled, but you can actually access the button using tabbing:
<button type="submit" class="btn btn-primary disabled">Submit</button>

So to prevent that from happening do I have to add tabindex="-1" to all of the elements I want to be disabled? I thought by using the disabled class this will be taken care of, but it seems not.
Is there any other way to do this?

A: Yes, that is annoying but also rather logical. Tabbing and focus is a different browser-task; CSS is (with a few exceptions) mostly about visual behaviour. Adding tabindex="-1" would become hellish, since you most likely also want to get the button focused through tabbing once it is no longer disabled.
I would suggest a handler that moves focus to either the previous or next element, if the button is receiving focus and it is disabled :
$('button').focus(function(e) {
  if ($(this).hasClass('disabled')) {
    e.currentTarget.nextElementSibling.focus()
    //or e.currentTarget.previousElementSibling.focus()
  }
})


text:
Q: MongoDB: Is second index useless? In MongoDb, I have an index {a:1,b:1}.
Is creating another index {a:1} useless as it is already covered by the other one?
My queries are following the patterns: findOne({a:"...",b:"..."}) or find({a:"..."}).

A: Check out MongoDB docs Create a compound index.
The following operation creates an ascending index on the item and stock fields:
db.products.createIndex( { "item": 1, "stock": 1 } )

In addition to supporting queries that match on all the index fields,
  compound indexes can support queries that match on the prefix of the
  index fields. That is, the index supports queries on the item field as
  well as both item and stock fields:

db.products.find( { item: "Banana" } )
db.products.find( { item: "Banana", stock: { $gt: 5 } } )

For a compound index, MongoDB can use the index to support queries on the index prefixes.
By the way,if you create a compound index:
{ "item": 1, "location": 1, "stock": 1 }

MongoDB can use the index for queries on the following fields:

*

*the item field,

*the item field and the location field,

*the item field and the location field and the stock field.

But it would not be as efficient on item and stock.
Hope this helps.

A: I think you don't need to create another index {a:1}, because of prefixes.

Index prefixes are the beginning subsets of indexed fields. For example, consider the following compound index:
{ "item": 1, "location": 1, "stock": 1 }

The index has the following index prefixes:
{ item: 1 }
{ item: 1, location: 1 }

For a compound index, MongoDB can use the index to support queries on the index prefixes. As such, MongoDB can use the index for queries on the following fields:

*

*the item field,

*the item field and the location field,

*the item field and the location field and the stock field.

And creating a compound index is more efficient [1].
And MongoDB can use an intersection of either the entire index or the index prefix [2].


text:
Q: numpy group rows from large array group the rows having same first element and find max according to last column.
Like row 0 and 1 have same starting element so go to last column and find max from it
and return that row without looping .
utl = np.array ([[ 21. ,            0.01      ],
                 [ 21. ,            0.02      ],
                 [ 26. ,            0.04      ],
                 [ 26. ,            0.03      ],
                 [ 26. ,            0.03      ],
                 [ 34. ,            0.03      ],
                 [ 34. ,            0.09      ],
                 [ 26. ,            0.03      ]])

output must be
[ 21. ,            0.02      ]
[ 34. ,            0.09      ]
[ 26. ,            0.04      ]

A: If the final order of the rows is not important:
# sort by first and second column
a = utl[np.lexsort((utl[:,1], utl[:,0]))]

# get positions of group change
# as we want the max, we take the last row per group
_, idx = np.unique(a[:,0], return_index=True)
idx2 = (idx-1)%a.shape[0]  # or idx2 = np.r_[idx[1:]-1, [a.shape[0]-1]]

# split
a[idx2]

output:
array([[21, 0.02],
       [26, 0.04],
       [34, 0.09]])

solution for the min
a = utl[np.lexsort((utl[:,1], utl[:,0]))]
_, idx = np.unique(a[:,0], return_index=True)
a[idx]

A: If you use np.lexsort, you can get the maximum by index:
sort_idx = np.lexsort(utl.T[::-1])

The differences in the sorted first column are going to tell you which index to grab from the second:
max_idx = np.r_[np.flatnonzero(np.diff(utl[idx, 0])), len(idx) - 1]
min_idx = np.r_[0, np.flatnonzero(np.diff(utl[idx, 0])) + 1]

The results can be extracted immediately:
minima = utl[idx[min_idx], 1]
maxima = utl[idx[max_idx], 1]


text:
Q: Check if value is between a range of numbers I am trying to check if values from a text box are between 4 and 80 but cant
I can do this but its not what i need
 final String checkage = age.getText().toString();
    if(checkage.equals(4)   || checkage.equals(80) ) {
        Toast.makeText(this, "You must be older than 4 and younger than 80", Toast.LENGTH_SHORT).show();
        return;
}

A: Use this:
final String checkage = age.getText().toString();
int value = Integer.parseInt(checkage);

if(value >= 4 && value <= 80) {
      Toast.makeText(this, "You must be older than 4 and younger than 80", Toast.LENGTH_SHORT).show();
      return;
}

'||' won't be useful for you in this case.

A: your logic is wrong. you need to do something like this.
final String checkage = age.getText().toString();
if (i > 4 && i < 80) {

    Toast.makeText(this, "You must be older than 4 and younger than 80", Toast.LENGTH_SHORT).show();
    return;
}


text:
Q: querySelector is unreachable inside object So I'm building out an object based approach to my modal and I'm trying to convert all of the existing jQuery into pure JavaScript calls and I'm having some issues.
So here is a basic foundation that I have:
// Initialize modal
let modal = {

// Define an element for namespacing / This will be class based.
    el: null,

    settings: {

        // Define the title
        title: null,

        // If it has a cogwheel or not
        cogwheel: false,

        // Cogwheel trigger
        cogwheel_trigger: '',

    },

    /**************************************************************************/

    header_el: function() {
        // Break down into title/cogwheel?
        // The close button was removed in top right corner
    },

    body_el: function() {
        // Will it be a container?
        // Will there be levels/columns?
    },

    footer_el: function() {
        // What buttons will be included?
        // Do we data target the Save/Close separately?
        // What buttons should we provide?
    },

    /**************************************************************************/

    // Find the modal parent/child.
    findAncestor: function() {
        // Empty
    },

    // Show the modal
    show_modal: function() {
        // Empty
    },

    // Close the modal
    close_modal: function() {
        // Empty
    },

    /**************************************************************************/
    // Controls: Things the user can interact with.

    cogwheel_ctrl: function() {
        // Empty
    },

    add_icon_ctrl: function() {
        // Empty
    },

    remove_icon_ctrl: function() {
        // Empty
    },

    add_button_ctrl: function() {
        return modal
            .body_el()
            document.querySelector('[data-ctrl="add-button"]');
    },

    save_button_ctrl: function() {
        return modal
            .footer_el()
            .find('[data-ctrl="save-button"');
    },

    close_button_ctrl: function() {
        return modal
            .footer_el()
            .find('[data-ctrl="close-button"');
    },
}

For some reason, when using the jQuery .find() call, it all works great, but when calling on a JS alternative using document.querySelector I get a unreachable code error as shown below:

Could someone explain to me the what the major difference is on the .find() call and traditional JS?

A: This is because with JQuery you're chaining the methods (join them), so, you're returning only one thing.
With the Vanilla JavaScript, you are not chaining the methods (and you can't chain JQuery methods with Pure JavaScript methods. So, you are returning the modal.body_el() and after calling the querySelector, but you can't call querySelector because you already returned something.
Solution:
Either use only JQuery methods or only pure JavaScript methods when returning.


text:
Q: LINQ generating SQL with duplicate nested selects I'm very new to the .NET Entity Framework, and  I think it's awesome, but somehow I'm getting this strange issue (sorry for the spanish but my program is in that language, anyway it's not a big deal, just the column or property names): I'm doing a normal LINQ To Entities query to get a list of UltimaConsulta, like this:
var query = from uc in bd.UltimasConsultas
            select uc;

UltimasConsultas is a view, btw. The thing is that LINQ is generating this SQL for the query:
SELECT
[Extent1].[IdPaciente] AS [IdPaciente],
[Extent1].[Nombre] AS [Nombre],
[Extent1].[PrimerApellido] AS [PrimerApellido],
[Extent1].[SegundoApellido] AS [SegundoApellido],
[Extent1].[Fecha] AS [Fecha]
FROM (SELECT
      [UltimasConsultas].[IdPaciente] AS [IdPaciente],
      [UltimasConsultas].[Nombre] AS [Nombre],
      [UltimasConsultas].[PrimerApellido] AS [PrimerApellido],
      [UltimasConsultas].[SegundoApellido] AS [SegundoApellido],
      [UltimasConsultas].[Fecha] AS [Fecha]
      FROM [dbo].[UltimasConsultas] AS [UltimasConsultas]) AS [Extent1]

Why is LINQ generating a nested Select? I thought from videos and examples that it generates normal SQL selects for this kind of queries. Do I have to configure something (the entity model was generating from a wizard, so it's default configuration)? Thanks in advance for your answers.

A: To be clear, LINQ to Entities does not generate the SQL. Instead, it generates an ADO.NET canonical command tree, and the ADO.NET provider for your database, presumably SQL Server in this case, generates the SQL.
So why does it generate this derived table (I think "derived table" is the more correct term for the SQL feature in use here)? Because the code which generates the SQL has to generate SQL for a wide variety of LINQ queries, most of which are not nearly as trivial as the one you show. These queries will often be selecting data for multiple types (many of which might be anonymous, rather than named types), and in order to keep the SQL generation relatively sane, they are grouped into extents for each type.
Another question: Why should you care? It's easy to demonstrate that the use of the derived table in this statement is "free" from a performance point of view.
I selected a table at random from a populated database, and run the following query:
SELECT [AddressId]
      ,[Address1]
      ,[Address2]
      ,[City]
      ,[State]
      ,[ZIP]
      ,[ZIPExtension]
  FROM [VertexRM].[dbo].[Address]

Let's look at the cost:
<StmtSimple StatementCompId="1" StatementEstRows="7900" StatementId="1" StatementOptmLevel="TRIVIAL" StatementSubTreeCost="0.123824" StatementText="/****** Script for SelectTopNRows command from SSMS  ******/
SELECT [AddressId]
      ,[Address1]
      ,[Address2]
      ,[City]
      ,[State]
      ,[ZIP]
      ,[ZIPExtension]
  FROM [VertexRM].[dbo].[Address]" StatementType="SELECT">
  <StatementSetOptions ANSI_NULLS="false" ANSI_PADDING="false" ANSI_WARNINGS="false" ARITHABORT="true" CONCAT_NULL_YIELDS_NULL="false" NUMERIC_ROUNDABORT="false" QUOTED_IDENTIFIER="false" />
  <QueryPlan CachedPlanSize="9" CompileTime="0" CompileCPU="0" CompileMemory="64">
    <RelOp AvgRowSize="246" EstimateCPU="0.008847" EstimateIO="0.114977" EstimateRebinds="0" EstimateRewinds="0" EstimateRows="7900" LogicalOp="Clustered Index Scan" NodeId="0" Parallel="false" PhysicalOp="Clustered Index Scan" EstimatedTotalSubtreeCost="0.123824">

Now let's compare that to the query with the derived table:
SELECT
       [Extent1].[AddressId]
      ,[Extent1].[Address1]
      ,[Extent1].[Address2]
      ,[Extent1].[City]
      ,[Extent1].[State]
      ,[Extent1].[ZIP]
      ,[Extent1].[ZIPExtension]
  FROM (SELECT [AddressId]
          ,[Address1]
          ,[Address2]
          ,[City]
          ,[State]
          ,[ZIP]
          ,[ZIPExtension]
  FROM[VertexRM].[dbo].[Address]) AS [Extent1]

And the cost:
<StmtSimple StatementCompId="1" StatementEstRows="7900" StatementId="1" StatementOptmLevel="TRIVIAL" StatementSubTreeCost="0.123824" StatementText="/****** Script for SelectTopNRows command from SSMS  ******/
SELECT
       [Extent1].[AddressId]
      ,[Extent1].[Address1]
      ,[Extent1].[Address2]
      ,[Extent1].[City]
      ,[Extent1].[State]
      ,[Extent1].[ZIP]
      ,[Extent1].[ZIPExtension]
  FROM (SELECT [AddressId]
          ,[Address1]
          ,[Address2]
          ,[City]
          ,[State]
          ,[ZIP]
          ,[ZIPExtension]
  FROM[VertexRM].[dbo].[Address]) AS [Extent1]" StatementType="SELECT">
  <StatementSetOptions ANSI_NULLS="false" ANSI_PADDING="false" ANSI_WARNINGS="false" ARITHABORT="true" CONCAT_NULL_YIELDS_NULL="false" NUMERIC_ROUNDABORT="false" QUOTED_IDENTIFIER="false" />
  <QueryPlan CachedPlanSize="9" CompileTime="0" CompileCPU="0" CompileMemory="64">
    <RelOp AvgRowSize="246" EstimateCPU="0.008847" EstimateIO="0.114977" EstimateRebinds="0" EstimateRewinds="0" EstimateRows="7900" LogicalOp="Clustered Index Scan" NodeId="0" Parallel="false" PhysicalOp="Clustered Index Scan" EstimatedTotalSubtreeCost="0.123824">

In both cases, SQL Server simply scans the clustered index. Not surprisingly, the cost is almost precisely the same.
Let's take a look at a slightly more complicated query. I fired up LINQPad, and entered the following query against the same table, plus one related table:
from a in Addresses
select new
{
    Id = a.Id,
    Address1 = a.Address1,
    Address2 = a.Address2,
    City = a.City,
    State = a.State,
    ZIP = a.ZIP,
    ZIPExtension = a.ZIPExtension,
    PersonCount = a.EntityAddresses.Count()
}

This generates the following SQL:
SELECT
1 AS [C1],
[Project1].[AddressId] AS [AddressId],
[Project1].[Address1] AS [Address1],
[Project1].[Address2] AS [Address2],
[Project1].[City] AS [City],
[Project1].[State] AS [State],
[Project1].[ZIP] AS [ZIP],
[Project1].[ZIPExtension] AS [ZIPExtension],
[Project1].[C1] AS [C2]
FROM ( SELECT
    [Extent1].[AddressId] AS [AddressId],
    [Extent1].[Address1] AS [Address1],
    [Extent1].[Address2] AS [Address2],
    [Extent1].[City] AS [City],
    [Extent1].[State] AS [State],
    [Extent1].[ZIP] AS [ZIP],
    [Extent1].[ZIPExtension] AS [ZIPExtension],
    (SELECT
        COUNT(cast(1 as bit)) AS [A1]
        FROM [dbo].[EntityAddress] AS [Extent2]
        WHERE [Extent1].[AddressId] = [Extent2].[AddressId]) AS [C1]
    FROM [dbo].[Address] AS [Extent1]
)  AS [Project1]

Analyzing this, we can see that Project1 is the projection onto the anonymous type. Extent1 is the Address table/entity. And Extent2 is the table for the association. Now there is no derived table for Address, but there is one for the projection.
I don't know if you have ever written a SQL generation system, but it isn't easy. I believe that the general problem of proving that a LINQ to Entities query and a SQL query are equivalent is NP-hard, although certain specific cases are obviously much easier. SQL is intentionally Turing-incomplete, because its designers wanted all SQL queries to execute in bounded time. LINQ, not so.
In short, this is a very difficult problem to solve, and the combination of the Entity Framework and its providers do occasionally sacrifice some readability in favor of consistency over a wide range of queries. But it shouldn't be a performance issue.

A: Basically it's defining what Extent1 consists of and what variables will relate to each entry. Then its mapping the actual database table to Extent1 so that it can return all entries for that table.
This is what your query is asking for. Its just that LINQ can't add in a wildcard character as you would if you'd done it by hand.


text:
Q: Stop IE8 from opening or downloading a text/plain MIME type I'm dynamically generating a text file in PHP, so it has a .php extension but a text/plain MIME type. All browsers display the file as nicely preformatted text, except IE8.
Googling tells me that they've added security where if the HTTP header content type doesn't match the expected content type (I think based on the extension and some sniffing) then it forces the file to be downloaded. In my case I have to open it, and also give it permission to open the file I just told it open! That's probably a Win7 annoyance though. Serving a static plain text file works fine, of course.
So can I stop IE8 from downloading the file and get it to view it normally? The code has to run on multiple shared hosting environments, so I think I'm stuck with the .php extension.

A: Add this to your HTTP header:
X-Content-Type-Options: nosniff

It's an IE8 feature to opt-out of its MIME-sniffing.
Source

A: Alternatively, you can "trick" IE8 into thinking that it is indeed serving up a text file. These 2 lines do it for me and don't involve using non-standardized "X-" headers:
Header("Content-Type: text/plain");
Header("Content-Disposition: inline; filename=\"whatever.txt\"");


text:
Q: ModuleNotFoundError: No module named after calling a script from another script Assume I have the following file structure:
  Package/
           __init__.py
           A.py
  B.py

Inside __init__.py I have the following:
__init__.py/
 import numpy as np
 import pandas as pd

Then I issue the following in the A.py script:
A.py/
from Package import *

However, I receive an error message that no module name Package is defined.
ModuleNotFoundError: No module named Package

I thought from Package import * means running everything in the __init__.py.
I can run the A.py content and use the init import from B.py as I expected.(using from Package import *)
I am using VSCode and Anaconda and my OS is Windows 10.
I can append the project folder every time to my PythonPath using the following commands:
sys.path.append("Path to the Package")

But I do not want to run this piece of code every time.
Can anyone explain what is the problem?
Is this a new problem in Python since I do not recall having such issues in the past?

A: Because if you run the B.py, the Parent folder of Package folder will be added into the sys.path, be equal to you add sys.path.append("Path to the Package") in the A.py file.
But when you run the A.py, it will add the Package folder instead of the Parent folder of Package folder to the sys.path.
sys.path:

A list of strings that specifies the search path for modules.
Initialized from the environment variable PYTHONPATH, plus an
installation-dependent default.
As initialized upon program startup, the first item of this list,
path[0], is the directory containing the script that was used to
invoke the Python interpreter.

If you are running the python file in debug mode(F5), and the Package folder was the subfolder of your workspace, you can configure the PYTHONPATH in the launch.json file:
  "env": {
    "PYTHONPATH": "${workspaceFolder}"
  },

A: In your A.py script use just use import file.py and do not use the star. Or, put all your files in a second Package2 directory and use from Package2 import * from your current A.py file.


text:
Q: Unit test using jasmine for durandal router I am using durandal framework for my Single Page Application. Where i need to test a function using jasmine.
The following router.js function code throwing error.
router.navigateTo("#/Home/About");

Error:
TypeError: 'undefined' is not an object (evaluating 'sammy.lookupRoute')

I tried to fix this issue by registering routes in my specs
            router.mapNav("reports/create");
            router.mapNav("reports/display");

Still am getting same error. How to fix this issue? Is there any example for testing router.js modules.


text:
Q: Reusing a footer among multiple HTML pages I am working on a web template which provides 5 HTML pages. I was surprised that inside each page there is the same footer section, as follow:

our Location

9870 St Vincent Place,
Glasgow, DC 45 Fr 45.

Freephone:+1 800 559 6580

Telephone:+1 800 603 6035

FAX:+1 800 889 9898

Overview

what we do

sales for services

Development Process

Clients

our team

Blog

newsletter

                    <form id="form1">

Your subscribe request
 has been sent!

                        <fieldset>

                            <input type="email" value="Enter Your Email">
                            *This is not a valid email address.

Submit

                      </fieldset>
                      </form>

©   Privacy Policy

If I need to modify it, I need to modify each of the 5 HTML pages. I am an ASP.net MVC web developer where i can easily handle this by defining a layout view which each contain all the shared sections.
So my question is how I can manage this inside my web template's HTML pages?

A: The answer is no* (with an asterik).
*There is some support in HTML5 for include-able HTML but it is very limited.
So little support, in fact, that Firefox ..."has no plans to support HTML imports"...
You may have luck using the Web Components Library to enable cross-browser support, but that may be more trouble than it is worth for a 5 page template.


text:
Q: Get VLOOKUP "lookup_value" to refer to a cell reference? I have this table in the top-left of my sheet:

I want to point VLOOKUP to cell A2 above, so that it returns 2. How can I achieve this? This doesn't work:
// this outputs 1, not 2.
=VLOOKUP(A2,A1:B3,2,FALSE)

I want to explicitly work with cell references, somehow, such that each A inside the first column are treated as unique & independent.

A: Because A appears multiple times, VLOOKUP will only return the first occurrence.
You need to add a unique identifier in order for it to work.


text: Q: Does anyone recognize this old novel about grafting minds to make a representative for a species.? It's from the seventies or earlier and may have been in an Ace Double.  Earth has been invited to send an ambassador, or possibly an individual who will be evaluated as proxy for all Homo sapiens, to an interstellar multispecies organization.  Unable to settle on an individual representative they graft multiple complete minds of at least 7 people together in one body.  The aliens are aware of what has been done but just believe it makes failure more likely and allow it.  The grafts do fail but the result is a new, stronger mind rather than a broken one.  The writing style is, in my memory at least, similar to C. Sheffield's, but I don't remember enough detail to be sure of that.


text:
Q: TeamViewer8 infinite loop on startup, never shows up Using latest stuff from the ArchLinux repositories and got the following packages installed:

*

*dotnet2

*ntlm_auth (installed from samba)

*winetricks

*smbclient

This is what it throws on console and then infinite loops:
$ teamviewer

Init...
Checking setup...
Launching TeamViewer...
fixme:service:scmdatabase_autostart_services Auto-start service L"MountMgr" failed to start: 2
fixme:service:scmdatabase_autostart_services Auto-start service L"PlugPlay" failed to start: 2
fixme:actctx:parse_depend_manifests Could not find dependent assembly L"Microsoft.Windows.Common-Controls" (6.0.0.0)
fixme:heap:HeapSetInformation (nil) 1 (nil) 0
fixme:ole:CoInitializeSecurity ((nil),-1,(nil),(nil),0,3,(nil),0,(nil)) - stub!
fixme:heap:HeapSetInformation (nil) 1 (nil) 0
fixme:process:SetProcessShutdownParameters (00000100, 00000000): partial stub.
fixme:resource:GetGuiResources (0xffffffff,0): stub
fixme:win:EnumDisplayDevicesW ((null),0,0x32dc60,0x00000000), stub!
fixme:win:EnumDisplayDevicesW (L"\\\\.\\DISPLAY1",0,0x32d918,0x00000000), stub!
fixme:win:EnumDisplayDevicesW ((null),1,0x32dc60,0x00000000), stub!

A: Solved it by doing the following:
sudo systemctl stop teamviewerd
sudo systemctl disable teamviewerd
sudo systemctl enable teamviewerd
sudo systemctl start teamviewer
sudo teamviewer

Maybe it needed to be run as root.

A: I've had the same issues in the past, you can get around it by downloading it from the official site, http://www.teamviewer.com/en/download/linux.aspx for some reason running it under wine causes wineserver to run out of resources (memory leak perhaps?).
You can run the official Linux version straight from the directory, you don't have to use package manager and it's a lot more stable.


text:
Q: Executing Multiple php scripts in Parallel I have to execute 100+ php scripts to be executed in parallel, each php script insert new data in database and update some previous records.
For example, each script url would be like that:
example.com/update.php?data-from-project-1.com
example.com/update.php?data-from-project-2.com
example.com/update.php?data-from-project-2.com
So on...
And Update page work something like:
Update.php
<?php
//insert some new records from project data
//update some records
?>

I am trying to do:
Cron JOB PAGE:
$urls=array("data-from-project-2.com", "data-from-project-2.com",....)
for ($index = 0; $index < count($urls); $index++) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "update.php?$urls[$index]");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch); }

But i guess this will execute all pages in order and can produce timeout issue as well. Anyway to execute them all in parallel through cron job page. I don't need any output, they just need to update database. Any help would be appreciated. Thanks

A: I'd love to pretend this was my reply but this answer from SO should cover it.
Executing multiple PHP scripts in parallel, and being notified when finished

A: use Php Thread. Simple example:
<?php

class workerThread extends Thread {
public function __construct($i){
  $this->i=$i;
}

public function run(){
  while(true){
   echo $this->i;
   sleep(1);
  }
}
}

for($i=0;$i<50;$i++){
$workers[$i]=new workerThread($i);
$workers[$i]->start();
}

?>

you can write each update in each thread. But i offer you create some batches for each thread. Because each thread also uses some little time for starting.
Or each thread may use some part of global array variable "urls" (start_index, end_index)

A: You can use PHP's curl_multi_init() to handle your tasks asynchronously.
I highly recommend this tutorial


text:
Q: Custom Computed Etag for Express.js I'm working on a simple local image server that provides images to a web application with some JSON. The web application has pagination that will do a get request "/images?page=X&limit&200" to an express.js server that returns the JSON files in a single array. I want to take advantage of the browser's internal caching such that if a user goes to a previous page the express.js returns an ETAG. I was wondering how this could be achieved with express.js? For this application, I really just want the computation of the ETAG to take in three parameters the page, the directory, and the limit (It doesn't need to consider the whole JSON body). Also this application is for local use only, so I want the server to do the heavy lifting since I figured it be faster than the browser. I did see https://www.npmjs.com/package/etag which seems promising, but I'm not sure how to use it with express.js
Here's a boilerplate of the express.js code I have below:

var express = require('express');
var app = express();
var fs = require('fs');

app.get('/', async (req, res) =>{

  let files = [];

  let directory = fs.readdirSync("mypath");

  let page = parseInt(req.query.page);
  let limit = parseInt(req.query.limit);

  for (let i = 0; i < limit; ++i) {
    files.push(new Promise((resolve) => {
      fs.readFile(files[i + page * limit].name, (err, data) => {
        // format the data so easy to use for UI
        resolve(JSON.parse(data));
      });
    });
  }

  let results = await Promise.all(files);
  // compute an etag here and attach it the results.
  res.send(results);
});

app.listen(3000);

A: When your server sends an ETag to the client, it must also be prepared to check the ETag that the client sends back to the server in the If-None-Match header in a subsequent "conditional" request.
If it matches, the server shall respond with status 304; otherwise there is no benefit in using ETags.
var serverEtag = "<compute from page, directory and limit>";
var clientEtag = req.get("If-None-Match");
if (clientEtag === serverEtag) res.status(304).end();
else {
  // Your code from above
  res.set("ETag", serverEtag);
  res.send(results);
}

The computation of the serverEtag could be based on the time of the last modification in the directory, so that it changes whenever any of the images in that directory changes. Importantly, this could be done without carrying out the fs.readFile statements from your code.


text:
Q: Is the word 'Jargon'? The online dictionary Merriam-webster says there is a word 'ungotten'. But Can we use it like we use the words such as unseen, unheard etc.? Is there any other word we can use for 'not obtained'?

A: "Ungotten" is an archaic word that may occasionally still be used in certain literature, but not in everyday speech. "Ill-gotten" (meaning obtained through illegal or questionable means) is similarly archaic but is used slightly more often as part of the idiom "ill-gotten gains".
"Unobtained" is a valid word, although it isn't often used. "Unobtainable" is certainly used often, although this refers to something which cannot be obtained rather than something which has not. I'm a native British English speaker, and I can't think of a single word that is widely used for this purpose. If someone tried to get something but didn't, we would probably just say "I didn't get it".
I'm not completely sure what you mean by asking "is this jargon?", but I am aware that the prefix un- is sometimes applied to the names of technical processes to mean a reversal or undoing of that process. I cannot imagine an archaic term like 'ungotten' being used in this way because the word 'gotten' is equally archaic.


text:
Q: How can I simplify the following term? Here is what I'm trying to simplify:
$$\frac{cV_0}{b\left(\sqrt[3]{\frac{c^2V_0}{bd}}\right)^2}$$
So $b$, $c$, $d$ are all constants and $V_0=xyz$
I'm just having a ton of trouble with the algebra here.

A: Hint: expand all the exponents for each term individually, such as $(\sqrt[3]{c^2})^2=c^\frac 43$, then proceed to simplify based on the result.

A: $$\frac{cV_0}{b\left(\sqrt[3]{\frac{c^2V_0}{bd}}\right)^2}= \frac{cV_0}{b\left(\frac{c^2V_0}{bd}\right)^{2/3}}  = \frac{cV_0}{b} \left(\frac{bd}{c^2V_0}\right)^{2/3} = \frac{cV_0b^{2/3}d^{2/3}}{c^{4/3}V_0^{2/3}b} = \frac{V_0^{1/3}d^{2/3}}{c^{1/3}b^{1/3}}= \left(\frac{V_0d^2}{cb}\right)^{1/3}$$

A: Here is what you should do
$$\eqalign{
  & A = {{c{V_0}} \over {b{{\left( {\root 3 \of {{{{c^2}{V_0}} \over {bd}}} } \right)}^2}}} = c{V_0}{b^{ - 1}}{\left( {{{\left( {{c^2}{V_0}{b^{ - 1}}{d^{ - 1}}} \right)}^{{1 \over 3}}}} \right)^{ - 2}} = c{V_0}{b^{ - 1}}{\left( {{c^2}{V_0}{b^{ - 1}}{d^{ - 1}}} \right)^{ - {2 \over 3}}}  \cr
  & \,\,\, = \left( {c{c^{ - {4 \over 3}}}} \right)\left( {{V_0}V_0^{ - {2 \over 3}}} \right)\left( {{b^{ - 1}}{b^{{2 \over 3}}}} \right){d^{{2 \over 3}}} = {c^{ - {1 \over 3}}}V_0^{{1 \over 3}}{b^{ - {1 \over 3}}}{d^{{2 \over 3}}} = {\left( {{c^{ - 1}}{V_0}{b^{ - 1}}{d^2}} \right)^{{1 \over 3}}} = {\left( {{{{V_0}{d^2}} \over {cb}}} \right)^{{1 \over 3}}}  \cr
  & \,\,\, = \root 3 \of {{{{V_0}{d^2}} \over {cb}}}  \cr} $$


text:
Q: How to Call the /oauth2/token endpoint with our app's client_secret to exchange the code for an access token for DropBox in Swift? I am using SwiftyDropbox to integrate Dropbox with my iOS App. I have completed all the configurations and implemented the code as in the documentation. User need to access the files in their dropbox account through my app. When I tried with 'generated access token' (got from dropbox console), I was able to access the files in my own account only. I understood that we will need to use the standard OAuth flow to obtain access tokens for other users.

Followed the steps as explained in https://developers.dropbox.com/oauth-guide

*

*Constructed a Dropbox authorization URL, with my application's client_id and redirect_uri.

*Next step is to Call the /oauth2/token endpoint with my app's client_secret to exchange the code for an access token. I am not sure how to implement this. If any of you have solved this before, please advise. Some portions of my code is given below.
override func viewDidLoad() {
super.viewDidLoad()
     self.actionDropboxLogin()
 }

 func actionDropboxLogin() {
     if (DropboxClientsManager.authorizedClient != nil) {

         //User is already authorized
         //Fetch images from user's DropBox folder
         self.getImageFromDropbox(path: "", isBack: false)
     } else {

         //User not authorized
         //So we go for authorizing user first.

         guard let rwURL = URL(string: "https://www.dropbox.com/oauth2/authorize?client_id=myclientid&redirect_uri=https://myapp/callback&response_type=code") else { return }

         let scopeRequest = ScopeRequest(scopeType: .user, scopes: ["account_info.read files.content.read files.content.write files.metadata.read file_requests.read"], includeGrantedScopes: false)
           DropboxClientsManager.authorizeFromControllerV2(
               UIApplication.shared,
               controller: self,
               loadingStatusDelegate: nil,
               openURL: { (url: URL) -> Void in UIApplication.shared.openURL(rwURL) },
               scopeRequest: scopeRequest
           )
         self.getImageFromDropbox(path: "", isBack: false)

     }
 }`

 func getImageFromDropbox(path:String, isBack:Bool) {
     let client = DropboxClientsManager.authorizedClient
     if client != nil {
    //code for getting list of folder, images or videos here.

}
self.tableView.reloadData()
}
When I print the value of client in console it is nil. So the condition 'if client != nil' is false and I am not able to get the files. Which means I am not getting an access token.

A: When using the SwiftyDropbox SDK, you don't need to handle any of the /oauth2/authorize or /oauth2/token details directly. The SDK implements the app authorization flow for you. You should only implement the flow as documented here:
https://github.com/dropbox/SwiftyDropbox#configure-your-project


text:
Q: How to find the kth largest eigenvalue of a matrix, taking into account the sign? I have a real symmetric matrix m (i.e. its eigenvalues are all real).  Eigenvalues[m, {k}] will find the kth largest eigenvalue by magnitude.  How can I find the kth largest, taking the sign into account?  How can I find the corresponding eigenvectors?

A: In general, eigenvalues are not real.  When asking for the kth largest eigenvalue, by default Mathematica sorts eigenvalues based on magnitude.
When using the Arnoldi method, it is possible to specify how eigenvalues should be sorted: based on magnitude, the real part, or imaginary part.  This is described under the Method option of Eigenvalues in the version 10 documentation.
For example, let's create a real symmetric matrix:
m = RandomReal[1, 15 {1, 1}];
m = m + Transpose[m];

These are all the eigenvalues, sorted decreasingly by magnitude:
Eigenvalues[m]
(* {14.8003, 2.73255, -2.63109, -2.51576, 1.87506, -1.58716, \
1.43875, 1.243, -1.20684, -0.947984, 0.630826, -0.550382, 0.491025, \
0.283469, -0.0578321} *)

We can instead request the 3 largest by real part:
Eigenvalues[m, 3, Method -> {"Arnoldi", "Criteria" -> "RealPart"}]
(* {14.8003, 2.73255, 1.87506} *)

Use Eigensystem the same way to obtain both eigenvalues and eigenvectors.

A: ClearAll[rF];
rF[mat_, n_] := With[{es = Eigensystem[mat]},
  With[{m = Transpose@es, o = Ordering[N@First@es, {n}]}, First@m[[o]]]]

mat = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
{vals, vecs} = Eigensystem[mat] // N
(* {{16.1168,-1.11684,0.},{{0.283349,0.641675,1.},{-1.28335,-0.141675, 1.},{1.,-2.,1.}}} *)

rF[mat,1]

$$ \left\{-\frac{3}{2} \left(\sqrt{33}-5\right),\left\{\frac{1}{22} \left(-11-3 \sqrt{33}\right),\frac{1}{44} \left(11-3
   \sqrt{33}\right),1\right\}\right\}$$
rF[mat, 1] // N
(* {-1.11684,{-1.28335,-0.141675,1.}} *)

rF[mat, 2] // N
(* {0.,{1.,-2.,1.}} *)
rF[mat, 3] // N
(* {16.1168,{0.283349,0.641675,1.}} *)

A: You can get just the nth largest Eigenvalue using the syntax
m = RandomReal[{-1, 1}, {5, 5}]
Eigenvalues[m, {3}]

Observe that this returns the third largest eigenvalue (i..e, the one with the third largest Abs[]).
Eigenvectors[m, {3}]

gives the corresponding eigenvector. Accordingly, you can get the smallest eigenvalues/vectors with
Eigenvalues[m, {Length[m]}]


text:
Q: Insert functions-defined constant into get_tags code I'm using the below code from WordPress' get_tags Function Reference page
    $tags = get_tags();
    $html = '
';
    foreach ($tags as $tag){
          $tag_link = get_tag_link($tag->term_id);
          $html .= "name} Tag' class='{$tag->slug}'>";
          $html .= "{$tag->name}";}
    $html .= '
';
    echo $html;

In my functions.php file I have a number of defined constants.
 define('xyz_city','New York');

I need to insert a constant into the tag link title (line 5 of above code). So instead of .....
    title='{$tag->name} Tag'

it needs to be .....
    title='{$tag->name} [insert xyz_city]'

But it's proving beyond my ability. Normally I echo the constants in like this
    <?php echo xyz_city ;?>

A: I think this is what you are going for:
$html .= "name} {$xyz_city}' class='{$tag->slug}'>";

The {$tag->name} part is a way to insert a function or variable into a "double quoted" string definition. In the case of {$tag->name} it needs the {curly braces} to get the whole object->method thing to work. You can usually leave the curly braces out when you have a double quoted string and want to insert a variable like $xyx_city, but its good practice to put them in there anyway just in case the underscore or something else in the name messes up the string parsing.


text:
Q: String comparision with equals and compareTo - which is faster? I need to compare 2 Strings. I have following methods I could think of:

*

*equalsIgnoreCase - Heard that this is the fastest, but i can't use it as my String is case sensitive

*matches - Probably the slowest one

*equals

*compareTo
So in the above option, I am left with equals and compareTo. Which one is faster among these?
Note: Input number of Strings are huge in number [around 5000 per sec].

A:
I am left with equals and compareTo.

Both serves in different purposes.
CompareTo

the value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument.

Where as
equals

true if the given object represents a String equivalent to this string, false otherwise

Hence compareTo() need more calculations that equals()
You can see the proof of that in source code of both.
compareTo()
equals()   ----- prefer to use this.

A:
equalsIgnoreCase

You generally use this one for string comparison.

matches

Slow because it is RegEx-based.

equals

I don't think this is slower than equalsIgnoreCase

compareTo

This returns an integer, or 0. This is used in sorting, for example. Don't use it for equality.

A: Note a very important difference between compareTo and equals:
"myString".compareTo(null);  //Throws java.lang.NullPointerException
"myString".equals(null);     //Returns false

Now I advise you to review the source code of both methods to conclude that equals is preferable over compareTo that involves some Math calculations.
Also note that equals makes a == first! This might be a big advantage when the objects are identical. Specially when you mentioned that you have a huge amount of Strings, because Java interns Strings, this might happen more than you thought.

Although you asked about Strings, but I want to add this note:
These methods can be very different when BigDecimal is involved. For example, see the docs:

equals compares this BigDecimal with the specified Object for equality.
  Unlike compareTo, this method considers two BigDecimal objects equal
  only if they are equal in value and scale (thus 2.0 is not equal to
  2.00 when compared by this method).

A: The 2 main differences are that:
equals will take any Object as a parameter, but compareTo will only take Strings.
equals only tells you whether they're equal or not, but compareTo gives information on how the Strings compare lexicographically.

ANd this is the class code url http://www.docjar.com/html/api/java/lang/String.java.html.
U can also look at this post if u want
Java Strings: compareTo() vs. equals()

A: Equals -
1- Override the GetHashCode method to allow a type to work correctly in a hash table.
2- Do not throw an exception in the implementation of an Equals method. Instead, return false for a null argument.
3-
 x.Equals(x) returns true.

 x.Equals(y) returns the same value as y.Equals(x).

 (x.Equals(y) && y.Equals(z)) returns true if and only if x.Equals(z) returns true.

Successive invocations of x.Equals(y) return the same value as long as the object referenced by x and y are not modified.
 x.Equals(null) returns false.

4- For some kinds of objects, it is desirable to have Equals test for value equality     instead of referential equality. Such implementations of Equals return true if the two    objects have the same value, even if they are not the same instance.
For Example -
  Object obj1 = new Object();
  Object obj2 = new Object();
  Console.WriteLine(obj1.Equals(obj2));
  obj1 = obj2;
  Console.WriteLine(obj1.Equals(obj2));

Output :-
  False
  True

while compareTo -
Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object.
It returns -
Less than zero    - This instance precedes obj in the sort order.
Zero              - This instance occurs in the same position in the sort order as obj.
Greater than zero - This instance follows obj in the sort order.
It can throw ArgumentException if object is not the same type as instance.
For example you can visit here.
So I suggest better to use Equals in place of compareTo.

A: You can time the code yourself and see which is faster:
final long start = System.currentTimeMillis();
for (int i = 0; i < input.length; i++) {
  // Do comparison here
}
final long end = System.currentTimeMillis();

System.out.println("Time to execute: " + (end - start));

A:
s1.CompareTo(s2)

0 - both equal
+ve - than s2 is lexicographically lower than the s1
-ve - than s2 is lexicographically higher than the s1

s1.equals(Object o1)

true- if s1 and o1 equals
false- if s1 and o1 not equal

compareTo can throw ClassCastException but equals if s1 and o1 are different class than should return false.

TreeMap depends on  compareTo() while HashMap depends on  equals(). So if you equals and compareTo are not consistent than TreeMap and HashMap can behave differently.  Hence it is good to have equals() and compareTo() consistent to each other but it's not mandatory.

I think the best or efficient way to compare string is to reference compare (but you should have used literals in your whole code). Because string inherently immutable and String class implements FlyWeight pattern inside by intern() method or by compiler. So it is good to compare reference.
if you are not confident about literals in code than you can do an optimization:
s1.hashCode() == s2.hashCode() && s1.equals(s2)

This is because String in immutable.

A:
equalsIgnoreCase - Heard that this is the fastest

Definitely not. It has to do things to promote lowercase to uppercase or vice versa. You can't have 'heard' that anywhere reputable.

matches - Probably the slowest one

Agreed.

equals
  compareTo

There is no reason to expect a difference between these.


text:
Q: How to receive files programmatically using bluetooth I am trying to receive data (strings) from a Bluetooth enabled device whose MAC_ID is known.
I have searched many examples ,but each article is pointing to Bluetooth Chat example, I think in Bluetooth Chat example, application need to be installed on both the devices for them to be connected and exchange strings.Correct me if I am wrong.
    But I need to install application only on Receiver device.I have tried installing the application only on one device and tried connecting to the sender device, without success.

A: Bluetooth is a peer to peer protocol where you need to have application running on both sides. Hence if you want to exchange data very good example would be Bluetooth chat. If you want to download or transfer a file you should either implement obex or FTP profile based applications.

A: Yes you need to deploy an application on both sides. If you are really restricted in a way that you only can deploy on one side, you have to figure out which standard protocols/bluetooth profiles the other side is capable of. You can figure that out by doing a SDP lookup. For a device, you will then get a list of UUIDs identifying these services. See the bluetooth spec for well known UUIDs. As @7383 pointed out, your are most probably looking for OBEX or FTP.
If you can deploy on both sides, you can write your own app using Blaubot (disclaimer: I wrote it). A simple Blaubot program would do this:
UUID MY_UUID = UUID.fromString("33bb1246-1472-11e5-b60b-1697f925ec7b");

// onCreate() or in a service, we create a blaubot instance
// using Bluetooth to form a network and Bluetooth + NFC to find devices
IBlaubotDevice ownDevice = new BlaubotDevice();
BlaubotUUIDSet uuidSet = new BlaubotUUIDSet(MY_UUID);

BlaubotBluetoothAdapter bluetoothAdapter = new BlaubotBluetoothAdapter(uuidSet, ownDevice);
BlaubotNFCBeacon nfcBeacon = new BlaubotNFCBeacon();
BlaubotBluetoothBeacon bluetoothBeacon = new BlaubotBluetoothBeacon();
this.mBlaubot = BlaubotAndroidFactory.createBlaubot(MY_UUID, ownDevice, adapter, nfcBeacon, bluetoothBeacon);

// start and wait until connected
this.mBlaubot.startBlaubot();

// create a channel and send your file
IBlaubotChannel fileChannel = this.mBlaubot.createChannel(1);

// convert your file to its bytes
File yourFile = // ... however you get it
byte[] fileBytes = ...// ... see http://stackoverflow.com/questions/858980/file-to-byte-in-java

// send it to all connected devices
fileChannel.publish(fileBytes, true);

// to receive it on the other device, do this:
// subscribe to the channel
fileChannel.subscribe(new IBlaubotMessageListener() {
    @Override
    public void onMessage(BlaubotMessage message) {
        // extract your bytes from the message
        byte[] fileBytes = message.getPayload();
        // .. do something useful or write it to a file again
        // to write it to a file
        File file = new File(yourFilePath);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
        bos.write(fileBytes);
        bos.flush();
        bos.close();
    }
});

This should be all you need. To allow the devices to connect, you have to pair them before or use NFC (just hold them together, when Blaubot is started). If you go with Blaubot let me know if you have problems that can't be solved with the documentation or the android quickstart guide.
I can only guess what your actual scenario looks like. If you have two android phones, this should work. If that is not the case, you should add more informations about the involved devices. Are we really talking about (classic) Bluetooth connections or are you trying to get data from a Bluetooth Low Energy device?
In this case the famous chat example will not help you either.


text:
Q: Group by multiple columns and then collect the list - Hive I have two tables namely posts and tags.
posts:
account_id post_id
1 1
1 2
2 2
2 3
2 5
3 4

tags:
account_id post_id tag_id
1 1 21
1 2 22
1 2 26
2 2 28
2 3 23
2 3 24
2 3 25
2 5 27

Now to get the all the tags assosiated with posts at an account level i have performed the following join.
CREATE TABLE posts_tags1
AS
SELECT a.account_id, a.post_id, b.tag_id FROM posts a LEFT OUTER JOIN tags b ON a.account_id = b.account_id AND a.post_id = b.post_id;

And the result that i have got is:
posts_tags1:
account_id post_id tag_id
1 1 21
1 2 22
1 2 26
2 2 28
2 3 23
2 3 24
2 3 25
2 5 27
3 4 NULL

Now i would like to convert the above result into
post_tags:
account_id post_id tag_ids
1 1 [21]
1 2 [22,26]
2 2 [28]
2 3 [23,24,25]
2 5 [27]
3 4 []

Can any one help me to achieve this ?

A: How about
CREATE TABLE post_tags
AS
SELECT account_id, post_id, collect_list(tag_id) FROM posts_tags GROUP BY account_id, post_id;


text:
Q: In Haskell, how can I get a substring of a Text between two indices? I'm trying to fint the Haskell equivalent of the Python:
>>>"This is a test"[5:9]
'is a'

I'm using the Data.Text module, if that makes any difference.

A: Usually one uses drop :: Int -> Text -> Text and take :: Int -> Text -> Text to obtain a slice of the subtext. We can combine the two to make some sort of substring:
import Data.Text as Tx(Text, drop, take)

substring :: Int -> Int -> Tx.Text -> Tx.Text
substring start length = Tx.take length . Tx.drop start

or if we want to use the end index (exclusive), we can create a slice function:
import Data.Text as Tx(drop, take)

slice :: Int -> Int -> Tx.Text -> Tx.Text
slice start end = Tx.take (end-start) . Tx.drop start

We then can use it like:
Prelude Tx> slice 5 9 "This is a test"
"is a"

This is not fully equivalent to Python's slice notation, since for instance Python uses negative indices as a way to count from the last element (i.e. -1 is the last element), and we can use 'foobar'[-5:-2] to obtain a slice that where the indices mean "taking a slice from the last but four to the last but one element".

A: Also, you can define the function in terms of Data.Text.take and drop, both functions from Data.Text library:
slice :: Int -> Int -> Text -> Text
slice a b = (Data.Text.take (b - a)) . (Data.Text.drop a)

A: Simple using the take function:
substring :: Int -> Int -> Text -> Text
substring start end text = take (end - start) (drop start text)

A: import Data.List

substring :: Int -> Int -> String -> String

substring i j s = take (j-i) ( drop i s )

A: Using the dot operator and sections gives a nice definition with take and drop:
slice off n = (take n).(drop off)

You can then just use slice 2 3 "hello!" to get "llo"