问:
Send email with attachment from internal storage
I create file on the internal storage as suggested by android docs. To be accurate the file is created under a specific directory in the internal storage. I do this using the mode world_readable mode. Then later on i try to attach the file using email program. I was able to get the file attached, however sending the email failed (does not seem to be to load the file) i am sure it is internal storage/permission thingy.

Anyone knows how to fix it or a working example? It will suck to have convert everything on external storage.

Thank you

Ps:I checked other threads and they don't seem to have solutions (old threads)

答:
It is possible to share a file from your apps local storage to another application (such as email attachment) by granting temporary permissions to read that file as part of the share intent.

Step 1: Add a file provider to your AndroidManifest.xml:

```<code><applicaton>
     ....
    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.your.package.name.fileprovider"
        android:grantUriPermissions="true"
        android:exported="false">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/filepaths" />
    </provider>
</application>
</code>```

Step 2: Add a file res/xml/filepaths.xml with the path to the file in local app storage that you want to share:

```<code><paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="myFolder" path="Folder/"/>
</paths>
</code>```

Step 3: In your java code create the file sharing intent:

```<code>    Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
    shareIntent.setType("text/plain");
    shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Your subject");
    shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Your message");

    ArrayList<Uri> uris = new ArrayList<Uri>();
    String shareName = new String(pathToFile + filename);
    File shareFile = new File(shareName);
    Uri contentUri = FileProvider.getUriForFile(context, "com.your.package.name.fileprovider", shareFile);
    uris.add(contentUri);
    shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);

    // Grant temporary read permission to the content URI
    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    String msgStr = "Share...";
    startActivity(Intent.createChooser(shareIntent, msgStr));
</code>```

If you have any problems with it see the docs here
https://developer.android.com/training/secure-file-sharing/share-file.html for further details.

Body:
It is possible to share a file from your apps local storage to another application (such as email attachment) by granting temporary permissions to read that file as part of the share intent.

Step 1: Add a file provider to your AndroidManifest.xml:

<applicaton>
     ....
    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.your.package.name.fileprovider"
        android:grantUriPermissions="true"
        android:exported="false">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/filepaths" />
    </provider>
</application>

Step 2: Add a file res/xml/filepaths.xml with the path to the file in local app storage that you want to share:

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="myFolder" path="Folder/"/>
</paths>

Step 3: In your java code create the file sharing intent:

    Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
    shareIntent.setType("text/plain");
    shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Your subject");
    shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Your message");

    ArrayList<Uri> uris = new ArrayList<Uri>();
    String shareName = new String(pathToFile + filename);
    File shareFile = new File(shareName);
    Uri contentUri = FileProvider.getUriForFile(context, "com.your.package.name.fileprovider", shareFile);
    uris.add(contentUri);
    shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);

    // Grant temporary read permission to the content URI
    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    String msgStr = "Share...";
    startActivity(Intent.createChooser(shareIntent, msgStr));

If you have any problems with it see the docs here
https://developer.android.com/training/secure-file-sharing/share-file.html for further details.


来源: stackexchange

问:
Python- Card Selection
I'm new to python and I'm trying to figure out how to ask the user for input and then use that input to select a specific card from a deck of cards. This is what I have so far   </p>

```<code>cardfaces = []
suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
royals = ["J", "Q", "K", "A"]
deck = []

for i in range(2,11):
    cardfaces.append(str(i))

for j in range(4):
    cardfaces.append(royals[j])

for k in range(4):
    for l in range(13):
        card = (cardfaces[l] + " of " + suits[k])
        deck.append(card)

for m in range(52):
    print(deck[m])
pick=input('Pick a card 1-52 :')
</code>```

答:
It looks to me as if all you need to do is access the chosen card.

```<code>chosen_card = deck[int(pick)-1]
</code>```

Do you need to do more with this?  I would normally think that you'd want the deck to be a list of (suit, rank) pairs, rather than string descriptions.  You can select a card description with your current code, but deck doesn't have an easy way to turn those descriptions back into characteristics you can manipulate.

ContentLicense: CC BY-SA 3.0

Title: Python- Card Selection

Body:
I'm new to python and I'm trying to figure out how to ask the user for input and then use that input to select a specific card from a deck of cards. This is what I have so far

cardfaces = []
suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
royals = ["J", "Q", "K", "A"]
deck = []

for i in range(2,11):
    cardfaces.append(str(i))

for j in range(4):
    cardfaces.append(royals[j])

for k in range(4):
    for l in range(13):
        card = (cardfaces[l] + " of " + suits[k])
        deck.append(card)

for m in range(52):
    print(deck[m])
pick=input('Pick a card 1-52 :')

Body:
It looks to me as if all you need to do is access the chosen card.

chosen_card = deck[int(pick)-1]

Do you need to do more with this?  I would normally think that you'd want the deck to be a list of (suit, rank) pairs, rather than string descriptions.  You can select a card description with your current code, but deck doesn't have an easy way to turn those descriptions back into characteristics you can manipulate.


问:
Finding out whether a TCP server has sent a data

I have a TCP server which writes data back to the client only for certain messages which the clients sends to the server.

It is basically is a command based server for which the server responds with a string only for certain commands otherwise nothing is sent back to the client.

The code given below is an approach which assumes that if any data is sent by the server it shows it as "MESSAGE FROM SERVER" appended with the data which was sent.

```<code>    class TcpEchoClient
    {
    static void Main(string[] args)
    {
    Console.WriteLine("Starting echo client...");

            string ipaddress = "127.0.0.1";
            TcpClient client = null;
            NetworkStream netstream = null;

            try
            {

                client = new TcpClient(ipaddress,1000);
                netstream = client.GetStream();

            }
            catch
            {
                Console.ReadKey();
                Environment.Exit(0);
            }

            while(true)
            {
                Console.WriteLine("Message :  ");
                string t = Console.ReadLine();
                string readdata = null;
                Console.WriteLine("\n");

                if (write(t,netstream))
                {
                    Console.WriteLine("Message sent.");

                    if (client.Available!=0)
                    {
                        readdata = read(netstream);
                        Console.WriteLine("MESSAGE FROM SERVER : "+readdata);
                    }

                }
                else
                {
                    Console.WriteLine("Unable to send message.");
                }
            }

        }

        static bool write(string dat, NetworkStream stream)
        {

            try
            {

                StreamWriter writer = new StreamWriter(stream) { AutoFlush = true };

                try{writer.WriteLine(dat);}
                catch (IOException){return false;}

                if (SHAHash(dat, "DATA") != SHAHash(read(stream), "DATA"))
                    return false;
            }catch (InvalidOperationException){return false;}

            return true;
        }

        static string read(NetworkStream stream)
        {

            StreamReader reader = new StreamReader(stream);

            string readdata = null;

            try
            {
                readdata = reader.ReadLine();
                reader.BaseStream.Flush();
            }
            catch(IOException)
            {
                return null;
            }

            return readdata;
        }
}
</code>```

The function SHAHash is not shown in this post. Its format is SHAHash(message,salt).

The problem faced is that messages sent by the server is not always read by the client. Sometimes the data sent by the server shows up a the client console, and sometimes it does not.

What correction should I make to the above code so that I can read data from the server only when it sends it. That is I require the following code to be executed only when the server sends some data to the client otherwise it should not be executed.

```<code>readdata = read(netstream);
Console.WriteLine("MESSAGE FROM SERVER : "+readdata);
</code>```

答:
TCP isnt synchronous so you can't write data and expect the response to be available immediately. When you do the following check

```<code>if (client.Available!=0)
</code>```

there is no guarantee that the server has sent any response yet. You need to keep checking until there is data available or read the data asynchronously

I would use NetworkStream.BeginRead and callbacks to get the server response

```<code>class StreamData
{

    public NetworkStream netstream;

    public byte[] myReadBuffer;
}

class TcpEchoClient
{

    static void Main(string[] args)
    {
        Console.WriteLine("Starting echo client...");

        string ipaddress = "127.0.0.1";
        TcpClient client = null;
        NetworkStream netstream = null;

        try
        {
            client = new TcpClient(ipaddress, 13000);
            netstream = client.GetStream();
        }
        catch
        {
            Console.ReadKey();
            Environment.Exit(0);
        }
        var streamData = new StreamData
        {
            netstream = netstream,
            myReadBuffer = new byte[1024],
        };

        netstream.BeginRead(streamData.myReadBuffer, 0, streamData.myReadBuffer.Length,
                                                   new AsyncCallback(myReadCallBack),
                                                   streamData);

        while (true)
        {
            Console.WriteLine("Message :  ");
            string t = Console.ReadLine();
            Console.WriteLine("\n");

            if (write(t, netstream))
            {
                Console.WriteLine("Message sent.");
            }
            else
            {
                Console.WriteLine("Unable to send message.");
            }
        }
    }

    static void myReadCallBack(IAsyncResult ar)
    {
        var streamData = (StreamData)ar.AsyncState;
        int bytesRead = streamData.netstream.EndRead(ar);
        var readdata = Encoding.ASCII.GetString(streamData.myReadBuffer, 0, bytesRead);
        //Be aware that this might not be the complete message depending on the size of the message and the buffer size
        Console.WriteLine("You received the following message : " + readdata);

        //Start waiting for more data
        streamData.netstream.BeginRead(streamData.myReadBuffer, 0, streamData.myReadBuffer.Length,
                                                   new AsyncCallback(myReadCallBack),
                                                   streamData);
    }

    static bool write(string dat, NetworkStream stream)
    {
        try
        {
            StreamWriter writer = new StreamWriter(stream) { AutoFlush = true };

            try { writer.WriteLine(dat); }
            catch (IOException) { return false; }

            //if (SHAHash(dat, "DATA") != SHAHash(read(stream), "DATA"))
            //    return false;
        }
        catch (InvalidOperationException) { return false; }

        return true;
    }

}
</code>```

Body:
I have a TCP server which writes data back to the client only for certain messages which the clients sends to the server.

It is basically is a command based server for which the server responds with a string only for certain commands otherwise nothing is sent back to the client.

The code given below is an approach which assumes that if any data is sent by the server it shows it as "MESSAGE FROM SERVER" appended with the data which was sent.

    class TcpEchoClient
    {
    static void Main(string[] args)
    {
    Console.WriteLine("Starting echo client...");

            string ipaddress = "127.0.0.1";
            TcpClient client = null;
            NetworkStream netstream = null;

            try
            {

                client = new TcpClient(ipaddress,1000);
                netstream = client.GetStream();

            }
            catch
            {
                Console.ReadKey();
                Environment.Exit(0);
            }

            while(true)
            {
                Console.WriteLine("Message :  ");
                string t = Console.ReadLine();
                string readdata = null;
                Console.WriteLine("\n");

                if (write(t,netstream))
                {
                    Console.WriteLine("Message sent.");

                    if (client.Available!=0)
                    {
                        readdata = read(netstream);
                        Console.WriteLine("MESSAGE FROM SERVER : "+readdata);
                    }

                }
                else
                {
                    Console.WriteLine("Unable to send message.");
                }
            }

        }

        static bool write(string dat, NetworkStream stream)
        {

            try
            {

                StreamWriter writer = new StreamWriter(stream) { AutoFlush = true };

                try{writer.WriteLine(dat);}
                catch (IOException){return false;}

                if (SHAHash(dat, "DATA") != SHAHash(read(stream), "DATA"))
                    return false;
            }catch (InvalidOperationException){return false;}

            return true;
        }

        static string read(NetworkStream stream)
        {

            StreamReader reader = new StreamReader(stream);

            string readdata = null;

            try
            {
                readdata = reader.ReadLine();
                reader.BaseStream.Flush();
            }
            catch(IOException)
            {
                return null;
            }

            return readdata;
        }
}

The function SHAHash is not shown in this post. Its format is SHAHash(message,salt).

The problem faced is that messages sent by the server is not always read by the client. Sometimes the data sent by the server shows up a the client console, and sometimes it does not.

What correction should I make to the above code so that I can read data from the server only when it sends it. That is I require the following code to be executed only when the server sends some data to the client otherwise it should not be executed.

readdata = read(netstream);
Console.WriteLine("MESSAGE FROM SERVER : "+readdata);

Body:
TCP isnt synchronous so you can't write data and expect the response to be available immediately. When you do the following check

if (client.Available!=0)

there is no guarantee that the server has sent any response yet. You need to keep checking until there is data available or read the data asynchronously

I would use NetworkStream.BeginRead and callbacks to get the server response

class StreamData
{

    public NetworkStream netstream;

    public byte[] myReadBuffer;
}

class TcpEchoClient
{

    static void Main(string[] args)
    {
        Console.WriteLine("Starting echo client...");

        string ipaddress = "127.0.0.1";
        TcpClient client = null;
        NetworkStream netstream = null;

        try
        {
            client = new TcpClient(ipaddress, 13000);
            netstream = client.GetStream();
        }
        catch
        {
            Console.ReadKey();
            Environment.Exit(0);
        }
        var streamData = new StreamData
        {
            netstream = netstream,
            myReadBuffer = new byte[1024],
        };

        netstream.BeginRead(streamData.myReadBuffer, 0, streamData.myReadBuffer.Length,
                                                   new AsyncCallback(myReadCallBack),
                                                   streamData);

        while (true)
        {
            Console.WriteLine("Message :  ");
            string t = Console.ReadLine();
            Console.WriteLine("\n");

            if (write(t, netstream))
            {
                Console.WriteLine("Message sent.");
            }
            else
            {
                Console.WriteLine("Unable to send message.");
            }
        }
    }

    static void myReadCallBack(IAsyncResult ar)
    {
        var streamData = (StreamData)ar.AsyncState;
        int bytesRead = streamData.netstream.EndRead(ar);
        var readdata = Encoding.ASCII.GetString(streamData.myReadBuffer, 0, bytesRead);
        //Be aware that this might not be the complete message depending on the size of the message and the buffer size
        Console.WriteLine("You received the following message : " + readdata);

        //Start waiting for more data
        streamData.netstream.BeginRead(streamData.myReadBuffer, 0, streamData.myReadBuffer.Length,
                                                   new AsyncCallback(myReadCallBack),
                                                   streamData);
    }

    static bool write(string dat, NetworkStream stream)
    {
        try
        {
            StreamWriter writer = new StreamWriter(stream) { AutoFlush = true };

            try { writer.WriteLine(dat); }
            catch (IOException) { return false; }

            //if (SHAHash(dat, "DATA") != SHAHash(read(stream), "DATA"))
            //    return false;
        }
        catch (InvalidOperationException) { return false; }

        return true;
    }

}


问:
Angular 2 routerlink with multiple routes?
I want to remove a class only one ONE route, (Or add a class on all BUT one route.)  How is that possible?  I have tried [routerLink] with multiple parameters to no avail:

```<code> <div class='body-content' [routerLink]="['/fetch-data', '/counter']" [routerLinkActive]="['col-sm-9']"  >
        <router-outlet></router-outlet>
    </div>
</code>```

Or, is there such a thing as     [routerLinkNOTActive] or something similar like so:

```<code><div class='body-content' [routerLink]="['/home']" [routerLinkNotActive]="['col-sm-9']">
</code>```

so, then it would add the 'col-sm-9' class on all routes that are not '/home'.  Seems very simple, but can't find anything to do it.

答:
Here's  my final solution which just used the [class] attribute. BTW, What happened to the [ng-class] attribute in Angular2?:

HTML:

```<code><div class='body-content' [class]="bodyContentClass()" >
    <router-outlet></router-outlet>
</div>
</code>```

TypeScript:

```<code>import {Location} from '@angular/common';
...
constructor(private authService: AuthService,private location: Location) { }
...
bodyContentClass()
{
    // router  is an instance of Router, injected in the constructor
   var viewLocation = location.pathname;
   return viewLocation == '/counter' || viewLocation == '/fetch-data' ? 'col-sm-9' : '';
}
</code>```

Body:
I want to remove a class only one ONE route, (Or add a class on all BUT one route.)  How is that possible?  I have tried [routerLink] with multiple parameters to no avail:

        <router-outlet></router-outlet>

Or, is there such a thing as     [routerLinkNOTActive] or something similar like so:

so, then it would add the 'col-sm-9' class on all routes that are not '/home'.  Seems very simple, but can't find anything to do it.

Body:
Here's  my final solution which just used the [class] attribute. BTW, What happened to the [ng-class] attribute in Angular2?:

HTML:

<div class='body-content' [class]="bodyContentClass()" >
    <router-outlet></router-outlet>
</div>

TypeScript:

import {Location} from '@angular/common';
...
constructor(private authService: AuthService,private location: Location) { }
...
bodyContentClass()
{
    // router  is an instance of Router, injected in the constructor
   var viewLocation = location.pathname;
   return viewLocation == '/counter' || viewLocation == '/fetch-data' ? 'col-sm-9' : '';
}


问:
Concatenation of multiple HEX values in C
I have an array in memory that holds certain hex values that describe assembly instructions. For example:

```<code>708877665544332211 = jump 0x1122334455667788
</code>```

70 indicates a jump in assembly and the following hex numbers are what I need to concatenate. I've already tried doing,

```<code>address |= memory[1];
address |= memory[2]<<8;
address |= memory[3]<<16;
address |= memory[4]<<24;
address |= memory[5]<<32;
address |= memory[6]<<40;
address |= memory[7]<<48;
address |= memory[8]<<56;
</code>```

The string that was outputted was:

0x100: 708877665544332211   |   jump 1432778700

Where am I going wrong in the concatenation?

EDIT: Following Benjamin's suggestion, I changed it to:

With print statement printf("APPEND: %016llx", address) to debug, I found that the uint64_t was being changed as:

```<code>APPEND: 0000000000002211
APPEND: 0000000000332211
APPEND: 0000000044332211
APPEND: 0000000044332255
APPEND: 0000000044336655
APPEND: 0000000044776655
</code>```

If the address is a 64bit integer, why does it appear to be behaving as a 32bit integer?

答:
I figured out what I was doing wrong. I should have just been appending the bits and then shifting them down 8 every time.</p>

```<code>for(int i = 8; i < 0; i--){
  address<<=8;
  address |= memory[i];
}
</code>```

Body:
I have an array in memory that holds certain hex values that describe assembly instructions. For example:

708877665544332211 = jump 0x1122334455667788

70 indicates a jump in assembly and the following hex numbers are what I need to concatenate. I've already tried doing,

address |= memory[1];
address |= memory[2]<<8;
address |= memory[3]<<16;
address |= memory[4]<<24;
address |= memory[5]<<32;
address |= memory[6]<<40;
address |= memory[7]<<48;
address |= memory[8]<<56;

The string that was outputted was:

0x100: 708877665544332211   |   jump 1432778700

Where am I going wrong in the concatenation?

EDIT: Following Benjamin's suggestion, I changed it to:

With print statement printf("APPEND: %016llx", address) to debug, I found that the uint64_t was being changed as:

APPEND: 0000000000002211
APPEND: 0000000000332211
APPEND: 0000000044332211
APPEND: 0000000044332255
APPEND: 0000000044336655
APPEND: 0000000044776655

If the address is a 64bit integer, why does it appear to be behaving as a 32bit integer?

Body:
I figured out what I was doing wrong. I should have just been appending the bits and then shifting them down 8 every time.

for(int i = 8; i < 0; i--){
  address<<=8;
  address |= memory[i];
}


问:
one git bare repository used for many clone
Is it possible to use the same git bare repository to hold data for different repositories? In other words, can I:

create a git bare repository (called BARE REPO)

clone it with master branch data from REMOTE REPO A

git clone -b consolidate --single-branch git@444.444.44.44:ConsolidateService.git

exec git add .

touch README.md

exec git commit -m "add README"

exec git remote add consolidate
ssh://root@333.333.33.33/var/repos/app.makeatoy.git

exec git push consolidate master

erase the contents of BARE REPO

re-clone it with master branch data from REMOTE REPO B

git clone -b test --single-branch git@444.444.44.44:TestService.git

exec git add .

touch README.md

exec git commit -m "add README"

exec git remote add testing
ssh://root@333.333.33.33/var/repos/app.makeatoy.git

exec git push testing master

erase the contents of BARE REPO

re-clone it with master branch data from REMOTE REPO C

git clone -b prod --single-branch git@444.444.44.44:ProdService.git

exec git add .

touch README.md

exec git commit -m "add README"

exec git remote add production
ssh://root@333.333.33.33/var/repos/app.makeatoy.git

exec git push production master

If it is possible, how would one erase the contents of a bare repository?

TIA

答: create a bare repo and just add the remotes from different projects. To git, it's just unrelated branches. No need to delete anything after you fetch from each one (there's no working tree on a bare repo so nothing to delete.).</p>


问:
Why do Guava classes provide so many factory methods instead of just one that takes varargs?

Possible Duplicate:

  Why does Guava's ImmutableList have so many overloaded of() methods?

Looking at Guava's ImmutableList (and some other classes), you'll find plenty of overloaded of convenience methods ("Returns an immutable list containing the given elements, in order.") that take a different number of parameters:

```<code>...
public static <E> ImmutableList<E> of(E e1, E e2, E e3)
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4)
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5)
...
</code>```

All the way to this one:

```<code>public static <E> ImmutableList<E> of(E e1,
                                      E e2,
                                      E e3,
                                      E e4,
                                      E e5,
                                      E e6,
                                      E e7,
                                      E e8,
                                      E e9,
                                      E e10,
                                      E e11,
                                      E e12,
                                      E... others)
</code>```

Some colleagues of mine consider this silly, wondering why there's isn't just one method: of(E... elements).  They suspect it's an ill-guided performance "optimisation" that falls into the category "do you think you're smarter than compiler", or something like that.

My hunch is that Kevin Bourrillion et al. put these methods in there for a real reason. Can anyone explain (or speculate) what that reason might be?

答:
Actaully the compiler is really dumb, the JVM has most of the smarts, but its still not smart enough to eliminate the need to create an array for a vararg.

Whether saving the array is really worth it, is perhaps something the author didn't want users to worry about. i.e. he might know it doesn't make much difference, but not all users might realise its not worth worrying about it 99% of the time.

When it was google-collections this was part of the description "High-performance immutable implementations of the standard collection types, for example ImmutableSet"

ContentLicense: CC BY-SA 2.5

Body:
Possible Duplicate:

  Why does Guava's ImmutableList have so many overloaded of() methods?

Looking at Guava's ImmutableList (and some other classes), you'll find plenty of overloaded of convenience methods ("Returns an immutable list containing the given elements, in order.") that take a different number of parameters:

...
public static <E> ImmutableList<E> of(E e1, E e2, E e3)
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4)
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5)
...

All the way to this one:

public static <E> ImmutableList<E> of(E e1,
                                      E e2,
                                      E e3,
                                      E e4,
                                      E e5,
                                      E e6,
                                      E e7,
                                      E e8,
                                      E e9,
                                      E e10,
                                      E e11,
                                      E e12,
                                      E... others)

Some colleagues of mine consider this silly, wondering why there's isn't just one method: of(E... elements).  They suspect it's an ill-guided performance "optimisation" that falls into the category "do you think you're smarter than compiler", or something like that.

My hunch is that Kevin Bourrillion et al. put these methods in there for a real reason. Can anyone explain (or speculate) what that reason might be?


问:
Rails - Why am I getting 'You are being redirected' in integration test?
When writing integration tests for a Rails 5 application I encountered the infamous 'You are being redirected' page for no apparent to me reasons. There are two highly similar tests:

```<code>test "GETtting correct activation link on an already activated user gives error message and redirects to root url" do
    # GIVEN a non-yet-registered email address
    email_address = "tester@testing.net"
    # GIVEN the sign-up page has been displayd
    get signup_path
    # GIVEN new user is created
    post signup_path, params: { user: { email: email_address, email_confirmation: email_address, password: "testpassword", password_confirmation: "testpassword" } }
    # GIVEN the URI from activation email
    activation_uri = URI.extract(ActionMailer::Base.deliveries.last.text_part.body.encoded)[0]
    # GIVEN the URI's been used and the user is already activated
    get activation_uri
    # WHEN reading back the newly activated user
    activated_user = User.find_by_email(email_address)
    # EXPECT the user to be activated
    assert activated_user.activated?
    # WHEN using the activation link on an already activated user
    get activation_uri
    # EXPECT redirection to root path
    assert_redirected_to root_url
    follow_redirect!
    # EXPECT flash message
    assert_not flash.empty?
    # EXPECT rendered page to contain activation error information
    assert_select 'div#flash div h5', text: I18n.translate('users.activate.error')
end
</code>```

which finishes correctly, and the next one:

```<code>test "GETtting incorrect activation hash on a non-activated user gives error message and redirects to root url" do
    # GIVEN a non-yet-registered email address
    email_address = "tester@testing.net"
    # GIVEN the sign-up page has been displayd
    get signup_path
    # GIVEN new user is created
    post signup_path, params: { user: { email: email_address, email_confirmation: email_address, password: "testpassword", password_confirmation: "testpassword" } }
    # WEHN GETting the activation URI with invalid activation hash
    activation_uri = "http://localhost:3000/account_activations/waTbfcCoZoPTBEIcewsl8Q/edit?email=#{ERB::Util.url_encode(email_address)}"
    get activation_uri
    # EXPECT redirection to root path
    assert_redirected_to root_url
    follow_redirect!
    # EXPECT flash message
    assert_not flash.empty?
    # EXPECT rendered page to contain activation error information ('You are being redirected' rendered here)
    assert_select 'div#flash div h5', text: I18n.translate('users.activate.error')
end
</code>```

which fails miserably on the last assert because 'You are being redirected' is being rendered instead of the page I am expecting to be rendered. In both cases I use follow_redirect! and the first one works, while the second one doesn't. The static URL in the second test is correct. It only uses a valid but non-associated hash instead of the expected one. In the controller there is simple

```<code>flash[:error] = "#{t'users.activate.error'}"
redirect_to root_url
</code>```

in both cases (the same method). I receive proper 302 response code and proper redirection URL. When doing the same tests manually in the browser, correct page is rendered. When running the tests I get 'You are being…' in the second test.

Any clues?

答:
Did you try, puts response.body in there to see whats going on?

There's a blurp in hartl's rails tutorial that helped me during a similar situation ... I applied his trick in a similar devise situation, honestly I'm not completely sure without poking around your code that the redirect is from a bad URI or not - but thought I'd leave this here for anyone else with issues.  I stumbled your post when looking for some answers to devise redirects myself (though mine are probably related to ID not found issues).

```<code>When I originally wrote this chapter, I couldn’t recall offhand how to escape URLs in Rails, and figuring it out was pure technical sophistication (Box 1.1). What I did was Google “ruby rails escape url”, which led me to find two main possibilities, URI.encode(str) and CGI.escape(str). Trying them both revealed that the latter works. (It turns out there’s a third possibility: the ERB::Util library supplies a url_encode method that has the same effect.)
</code>```

Body:
When writing integration tests for a Rails 5 application I encountered the infamous 'You are being redirected' page for no apparent to me reasons. There are two highly similar tests:

test "GETtting correct activation link on an already activated user gives error message and redirects to root url" do
    # GIVEN a non-yet-registered email address
    email_address = "tester@testing.net"
    # GIVEN the sign-up page has been displayd
    get signup_path
    # GIVEN new user is created
    post signup_path, params: { user: { email: email_address, email_confirmation: email_address, password: "testpassword", password_confirmation: "testpassword" } }
    # GIVEN the URI from activation email
    activation_uri = URI.extract(ActionMailer::Base.deliveries.last.text_part.body.encoded)[0]
    # GIVEN the URI's been used and the user is already activated
    get activation_uri
    # WHEN reading back the newly activated user
    activated_user = User.find_by_email(email_address)
    # EXPECT the user to be activated
    assert activated_user.activated?
    # WHEN using the activation link on an already activated user
    get activation_uri
    # EXPECT redirection to root path
    assert_redirected_to root_url
    follow_redirect!
    # EXPECT flash message
    assert_not flash.empty?
    # EXPECT rendered page to contain activation error information
    assert_select 'div#flash div h5', text: I18n.translate('users.activate.error')
end

which finishes correctly, and the next one:

test "GETtting incorrect activation hash on a non-activated user gives error message and redirects to root url" do
    # GIVEN a non-yet-registered email address
    email_address = "tester@testing.net"
    # GIVEN the sign-up page has been displayd
    get signup_path
    # GIVEN new user is created
    post signup_path, params: { user: { email: email_address, email_confirmation: email_address, password: "testpassword", password_confirmation: "testpassword" } }
    # WEHN GETting the activation URI with invalid activation hash
    activation_uri = "http://localhost:3000/account_activations/waTbfcCoZoPTBEIcewsl8Q/edit?email=#{ERB::Util.url_encode(email_address)}"
    get activation_uri
    # EXPECT redirection to root path
    assert_redirected_to root_url
    follow_redirect!
    # EXPECT flash message
    assert_not flash.empty?
    # EXPECT rendered page to contain activation error information ('You are being redirected' rendered here)
    assert_select 'div#flash div h5', text: I18n.translate('users.activate.error')
end

which fails miserably on the last assert because 'You are being redirected' is being rendered instead of the page I am expecting to be rendered. In both cases I use follow_redirect! and the first one works, while the second one doesn't. The static URL in the second test is correct. It only uses a valid but non-associated hash instead of the expected one. In the controller there is simple

flash[:error] = "#{t'users.activate.error'}"
redirect_to root_url

in both cases (the same method). I receive proper 302 response code and proper redirection URL. When doing the same tests manually in the browser, correct page is rendered. When running the tests I get 'You are being…' in the second test.

Any clues?

Body:
Did you try, puts response.body in there to see whats going on?

There's a blurp in hartl's rails tutorial that helped me during a similar situation ... I applied his trick in a similar devise situation, honestly I'm not completely sure without poking around your code that the redirect is from a bad URI or not - but thought I'd leave this here for anyone else with issues.  I stumbled your post when looking for some answers to devise redirects myself (though mine are probably related to ID not found issues).

When I originally wrote this chapter, I couldn’t recall offhand how to escape URLs in Rails, and figuring it out was pure technical sophistication (Box 1.1). What I did was Google “ruby rails escape url”, which led me to find two main possibilities, URI.encode(str) and CGI.escape(str). Trying them both revealed that the latter works. (It turns out there’s a third possibility: the ERB::Util library supplies a url_encode method that has the same effect.)


问:
Cannot load script for execution
I am getting an error message in VS studios when I try to execute a script task using C# code.  The code opens in the editor and will build and rebuild successfully but when I run the package I get

"Cannot load script for execution".

Screenshots

答:
I figured this out. When you create a new Script task in SSIS there is auto generated code in it that is critical for executing the task. If you take a fully working C# script from a Console application and just ctrl+a, ctrl+v over the entire contents of the SSIS Script task you lose critical parts of the script task code. When this happens, you are left with a script task that will open in the script editor and compile without generating any errors but it will not execute in SSIS.

Specifically was missing this:

```<code>{ [Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain :
Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase {
</code>```

Title: Cannot load script for execution

Body:
I figured this out. When you create a new Script task in SSIS there is auto generated code in it that is critical for executing the task. If you take a fully working C# script from a Console application and just ctrl+a, ctrl+v over the entire contents of the SSIS Script task you lose critical parts of the script task code. When this happens, you are left with a script task that will open in the script editor and compile without generating any errors but it will not execute in SSIS.

Specifically was missing this:

{ [Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain :
Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase {


问:
Doing Forms With Just Windows SharePoint Services 3.0?
For the most part my organization is happy with WSS 3.0 (no upgrading to MOSS) with one exception, there is really just one form we'd like to put up somehow.  It's  fairly big form (basically change requests for IT services, on paper it's easily 2 full 8.5 by 11 pages).  We thought about Custom ASP.NET coding as a separate stand-alone page or maybe as a web part.  What have other people out there done?  MOSS and Infopath is not really an option as it really is too expensive for us at this time.  Thanks in advance!</p>

答:
The Survey list is a good simple alternative to forms, and can be used without any coding.  Enter the "questions" ie. input fields, then attach a mail alert for inserts.  The drawback is that you have no control over the layout of the form, it is strictly one row per input field.  This makes it perhaps not a good candidate for your large forms.  But it is so easy to use that you should take a look at it anyway.

If you decide to develop yourself, write a web part, and add it to a WSS page.  (Simplest deployment: Inherit from the ASP.Net WebPart class, put in GAC, create a .webpart file in the SharePoint webapp's wpcatalog folder).  Re the person who wrote that the learning curve in SharePoint is too steep, I assume that if you're using WSS for your internal web applications you'll discover more needs for SharePoint customization in the future.  Learning how to do that is a good investment.

OwnerDisplayName: Bjørn Stærk

LastEditorDisplayName: Bjørn Stærk


问:
RxJava How to throw error from Observable.fromCallable(()
If I use:

class 1:

```<code>Observable.fromCallable(() -> awsS3.beginUpload(data.bmpPath));
</code>```

class2:

```<code>public  String beginUpload(String filePath) {
   //what if I want to throw error here?
}
</code>```

how can I throw an Observable error in the beginUpload() method?

答:
fromCallable takes a Callable which has a call() throws Exception method, therefore, you can declare your method as throws X where X is the exception type you need to throw:

```<code>public  String beginUpload(String filePath) throws IOException {
    throw new IOException();
}
</code>```

Body:
If I use:

class 1:

Observable.fromCallable(() -> awsS3.beginUpload(data.bmpPath));

class2:

public  String beginUpload(String filePath) {
   //what if I want to throw error here?
}

how can I throw an Observable error in the beginUpload() method?

Body:
fromCallable takes a Callable which has a call() throws Exception method, therefore, you can declare your method as throws X where X is the exception type you need to throw:

public  String beginUpload(String filePath) throws IOException {
    throw new IOException();
}


问:
How to get the following transfer function in Matlab
I was wondering if there is a Matlab code that can calculate the following TF from the 2 equations below. Thank You

答:
The Symbolic Math Toolbox can be used here:</p>

```<code>syms alpha theta delta s
    % we have to solve the system
sol= solve([(88.5*s+3.13)*alpha+(-88.5*s+2.06)*theta==-4.63*delta,...
    -11.27*alpha+(4.75*s^2+0.321*s)*theta==-34.25*delta] ,[theta delta])
tfuncsym= sol.theta/sol.delta % the transfer function (sym object)
[n,d]= numden(tfuncsym);
    % the transfer function (tf object)
tf_object= tf(fliplr(double(coeffs(n))),fliplr(double(coeffs(d))))
    % the transfer function (zpk object)
    % this is exactly what we need
zpk_object= zpk(tf_object)
</code>```

Body:
The Symbolic Math Toolbox can be used here:

syms alpha theta delta s
    % we have to solve the system
sol= solve([(88.5*s+3.13)*alpha+(-88.5*s+2.06)*theta==-4.63*delta,...
    -11.27*alpha+(4.75*s^2+0.321*s)*theta==-34.25*delta] ,[theta delta])
tfuncsym= sol.theta/sol.delta % the transfer function (sym object)
[n,d]= numden(tfuncsym);
    % the transfer function (tf object)
tf_object= tf(fliplr(double(coeffs(n))),fliplr(double(coeffs(d))))
    % the transfer function (zpk object)
    % this is exactly what we need
zpk_object= zpk(tf_object)


问:
Typescript Support for Visual Studio 2017
I have recently been trying to learn TypeScript, and in some of the videos I have been watching after installing the 'Web Essentials' extension when working with a .ts file visual studio gives you a pre-view panel so you can see the JavaScript as you type.

These videos seem to be using VS 2012.

However installing Web Essentials on VS 2017 doesn't seem to have this option, does anyone know how I can get this to work in VS 2017? Does it have the same support for TypeScript?

答:
I see your question is for VS 2017 and I don't find any documentation on VS 2017 to confirm if it has been added back. However, I did find that this was removed in VS 2015. See this link on Github

The TS preview pane has been removed from Web Essentials 2015 due to continuously running into conflicts with the TS compiler when new versions come out. The TS team are aware of it and I hope they will add the feature into the TS tooling in the future. It is possible that this feature will be included in the brand new Web Compiler extensions (https://visualstudiogallery.msdn.microsoft.com/3b329021-cd7a-4a01-86fc-714c2d05bb6c) when preview panes have been implemented.


问:
$.Ajax POST, accessing return data
I'm currently working on a ASP.NET Webforms site and I've run in to a small problem. Been searching around for 2 hours now and I got a deadline, so hoping someone here can assist.

On my .cs file I have the following Webmethod

```<code>[WebMethod]
   public static string IsJobEditable(int jobid)
   {
       try
       {
           string isEditable = "false";

           JobsBLL jbl = new JobsBLL();

           int jobStatusId = jbl.GetJobStatusId(jobid);

           if(jobStatusId == Convert.ToInt32(ConstantsUtil.JobStatus.Waiting) || jobStatusId == Convert.ToInt32(ConstantsUtil.JobStatus.Edit))
           {
               isEditable = "true";
           }

           return isEditable;

       }
       catch (Exception ex)
       {

           throw ex;
       }
   }
</code>```

This function in this case will ALWAYS return TRUE as a string.

On Aspx page I have the following

```<code>$(function () {

           $.ajax({

               type: "POST",
               url: "Coordination.aspx/IsJobEditable",
               data: "{jobid:" + jobid + "}",
               contentType: "application/json; charset=utf-8",
               dataType: "text",
               success: function (result) {

                   alert(result);

                   // This is written out in the alert {"d":"true"}
                   // I want this in a variable as a string
                   // so I can do a check on it before I do some other actions
                   // The format is not a String so i cannot split on it to
                   // retrieve the "true" part.

               },
               error: function (err, result) { alert(err); }

           });
       });
</code>```

As you can see in the comments the value I get back in the Callback method is in to me a weird format. The type is unknown and I need this value to be able to proceed with my entire method surrounding the small portion of the Javascript.

So can anyone point me into the direction where I can access the result variable / data as a var or anything else that will let me put it into a var (as a string).

答:
Use result.d to get your string.

See this site for an explanation of the .d issue when calling .ajax from ASP.NET:  http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/

Title: $.Ajax POST, accessing return data

Body:
I'm currently working on a ASP.NET Webforms site and I've run in to a small problem. Been searching around for 2 hours now and I got a deadline, so hoping someone here can assist.

On my .cs file I have the following Webmethod

[WebMethod]
   public static string IsJobEditable(int jobid)
   {
       try
       {
           string isEditable = "false";

           JobsBLL jbl = new JobsBLL();

           int jobStatusId = jbl.GetJobStatusId(jobid);

           if(jobStatusId == Convert.ToInt32(ConstantsUtil.JobStatus.Waiting) || jobStatusId == Convert.ToInt32(ConstantsUtil.JobStatus.Edit))
           {
               isEditable = "true";
           }

           return isEditable;

       }
       catch (Exception ex)
       {

           throw ex;
       }
   }

This function in this case will ALWAYS return TRUE as a string.

On Aspx page I have the following

$(function () {

           $.ajax({

               type: "POST",
               url: "Coordination.aspx/IsJobEditable",
               data: "{jobid:" + jobid + "}",
               contentType: "application/json; charset=utf-8",
               dataType: "text",
               success: function (result) {

                   alert(result);

                   // This is written out in the alert {"d":"true"}
                   // I want this in a variable as a string
                   // so I can do a check on it before I do some other actions
                   // The format is not a String so i cannot split on it to
                   // retrieve the "true" part.

               },
               error: function (err, result) { alert(err); }

           });
       });

As you can see in the comments the value I get back in the Callback method is in to me a weird format. The type is unknown and I need this value to be able to proceed with my entire method surrounding the small portion of the Javascript.

So can anyone point me into the direction where I can access the result variable / data as a var or anything else that will let me put it into a var (as a string).


问:
Ionic2 Ion-select without OK and Cancel
I have built an Ionic2 app and I am currently trying to improve the UX. To do that, I received some feedback that made me think of whether there is a way of having a

```<code>    <ion-select>
      <ion-option>
      </ion-option>
    </ion-select>
</code>```

which upon tapped on, would give me the output straight away and not wait for the user to press on the currently appearing 'OK'and 'CANCEL' buttons that the ionic action sheet(http://ionicframework.com/docs/v2/api/components/select/Select/) uses by default.

Any suggestions will be greatly appreciated! :)

EDIT:

As @sebaferrreras has suggested,

If the number of options exceed 6, it will use the alert interface even if action-sheet is passed.

So if you need to use more than 6 options, you are going to have to find a workaround as for the moment, this functionality is NOT listed under the Ionic2 docs.

答:
I know this thread is 7 months old and the OP is probably long past this question but since the feature is yet to be added to ionic framework, I'm adding the workaround I came up with for other people's reference.

CSS PART

Intuitively the first thing you need to do is to add some sass/css to hide the unwanted buttons. I did that by passing a css class "remove-ok" to selectOptions for my ion-select element. (I'm only removing OK button but if someone needs to remove cancel button as well, that's an easy css modification).

In component:

```<code>this.selectOptions = {
      cssClass: 'remove-ok'
    };
</code>```

and in HTML:

```<code><ion-select [selectOptions]="selectOptions">
</code>```

And in app.scss add:

```<code>.remove-ok {
    .alert-button:nth-child(2) {
        display: none;
    }
}
</code>```

SCRIPT PART

Now that the OK button is hidden, you will need to somehow close the alert view.

To invoke click() event on the hidden OK button is straightforward and intuitive but you'll soon find out that although it works perfectly on ionic serve, it won't work on an actual iOS device.

The solution is to find reference to the alert view, pass the checked option to the select handler, and finally dismiss the view.

So in ngOnInit in your component class, you'll need this:

```<code>ngOnInit() {
        let root = this.viewController.instance.navCtrl._app._appRoot;
        document.addEventListener('click', function(event){
        let btn = <HTMLLIElement> document.querySelector('.remove-ok .alert-button-default:nth-child(2)');
        let target = <HTMLElement> event.target;
        if(btn && target.className == 'alert-radio-label')
        {
              let view = root._overlayPortal._views[0];
              let inputs = view.instance.d.inputs;
              for(let input of inputs) {
                if(input.checked) {
                  view.instance.d.buttons[1].handler([input.value]);
                  view.dismiss();
                  break;
                }
              }
            }
        });
    }
</code>```

Again, if you intend to remove the Cancel button as well, mind the css references in this code.

Title: Ionic2 Ion-select without OK and Cancel

Body:
I have built an Ionic2 app and I am currently trying to improve the UX. To do that, I received some feedback that made me think of whether there is a way of having a

    <ion-select>
      <ion-option>
      </ion-option>
    </ion-select>

which upon tapped on, would give me the output straight away and not wait for the user to press on the currently appearing 'OK'and 'CANCEL' buttons that the ionic action sheet(http://ionicframework.com/docs/v2/api/components/select/Select/) uses by default.

Any suggestions will be greatly appreciated! :)

EDIT:

As @sebaferrreras has suggested,

If the number of options exceed 6, it will use the alert interface even if action-sheet is passed.

So if you need to use more than 6 options, you are going to have to find a workaround as for the moment, this functionality is NOT listed under the Ionic2 docs.

Body:
I know this thread is 7 months old and the OP is probably long past this question but since the feature is yet to be added to ionic framework, I'm adding the workaround I came up with for other people's reference.

CSS PART

Intuitively the first thing you need to do is to add some sass/css to hide the unwanted buttons. I did that by passing a css class "remove-ok" to selectOptions for my ion-select element. (I'm only removing OK button but if someone needs to remove cancel button as well, that's an easy css modification).

In component:

this.selectOptions = {
      cssClass: 'remove-ok'
    };

and in HTML:

<ion-select [selectOptions]="selectOptions">

And in app.scss add:

.remove-ok {
    .alert-button:nth-child(2) {
        display: none;
    }
}

SCRIPT PART

Now that the OK button is hidden, you will need to somehow close the alert view.

To invoke click() event on the hidden OK button is straightforward and intuitive but you'll soon find out that although it works perfectly on ionic serve, it won't work on an actual iOS device.

The solution is to find reference to the alert view, pass the checked option to the select handler, and finally dismiss the view.

So in ngOnInit in your component class, you'll need this:

ngOnInit() {
        let root = this.viewController.instance.navCtrl._app._appRoot;
        document.addEventListener('click', function(event){
        let btn = <HTMLLIElement> document.querySelector('.remove-ok .alert-button-default:nth-child(2)');
        let target = <HTMLElement> event.target;
        if(btn && target.className == 'alert-radio-label')
        {
              let view = root._overlayPortal._views[0];
              let inputs = view.instance.d.inputs;
              for(let input of inputs) {
                if(input.checked) {
                  view.instance.d.buttons[1].handler([input.value]);
                  view.dismiss();
                  break;
                }
              }
            }
        });
    }

Again, if you intend to remove the Cancel button as well, mind the css references in this code.


问:
Laravel: Changing elements on textbox edit
First Laravel Project.
I want to make a form where if I write something in a textbock (for example a barcode) the code searches in a database and prints out a value (for example the price)

My code is so far:

The view:

```<code>{{ Form::open(array('url' => '/product/$barcode'))}}
<script>
function showProduct(str) {
    if (str == "") {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("txtHint").innerHTML = this.responseText;
            }
        };
        xmlhttp.open("GET","script/getproduct.php?q="+str,true);
        xmlhttp.send();
    }
}
</script>

//If I don't set the @vars first I get "unknown variable" error
<?php $name=0; $price=0; ?>
<table>
<tr>
<td>{{Form::text('barcode', null, ['onchange'=>'showProduct(this.value)'])}}</td>
<td><div id="txtHint">Name: {{ $name }}</div></td>
<td><div id="txtHint">Price: {{ $price }}</div></td>
</tr>
</table>
{{Form::close()}}
</code>```

The showproduct.php:

```<code><?php
$q = intval($_GET['q']);

$sql = DB::select('select * from inventory where barcode = ? LIMIT 1', [$q]);

$price = $sql[0]->price;
$name = $sql[0]->name;
?>
</code>```

But when I put a barcode to the textfield I still got 0 in the fields. What I did wrong?

答:
first issue , you are using multi ID in your DOM document, which is totally wrong .

```<code><td><div id="txtHint">Name: {{ $name }}</div></td>
<td><div id="txtHint">Price: {{ $price }}</div></td>
</code>```

must be as follows :

```<code><td><div id="nameHint">Name: {{ $name }}</div></td>
<td><div id="priceHint">Price: {{ $price }}</div></td>
</code>```

then, in your php side you will need to echo some data , and to send multiple data the best approach by encode it into json , then decode that json from your client side and parse it into DOM elements using javascript.

so , in your php code , modify it to be as follows :

```<code>$price = $sql[0]->price;
$name = $sql[0]->name;
echo json_encode(array("price" => $price, "name" => $name));
</code>```

then from your client side , decode that json as follows :

```<code>if (this.readyState == 4 && this.status == 200) {
    var jsonObject = JSON.parse(this.responseText);
    document.getElementById("priceHint").innerHTML = jsonObject['price'];
    document.getElementById("nameHint").innerHTML = jsonObject['name'];
}
</code>```

Body:
First Laravel Project.
I want to make a form where if I write something in a textbock (for example a barcode) the code searches in a database and prints out a value (for example the price)

My code is so far:

The view:

{{ Form::open(array('url' => '/product/$barcode'))}}

//If I don't set the @vars first I get "unknown variable" error
<?php $name=0; $price=0; ?>

{{Form::text('barcode', null, ['onchange'=>'showProduct(this.value)'])}}

Name: {{ $name }}

Price: {{ $price }}

{{Form::close()}}

The showproduct.php:

<?php
$q = intval($_GET['q']);

$sql = DB::select('select * from inventory where barcode = ? LIMIT 1', [$q]);

$price = $sql[0]->price;
$name = $sql[0]->name;
?>

But when I put a barcode to the textfield I still got 0 in the fields. What I did wrong?

Body:
first issue , you are using multi ID in your DOM document, which is totally wrong .

<td><div id="txtHint">Name: {{ $name }}</div></td>
<td><div id="txtHint">Price: {{ $price }}</div></td>

must be as follows :

<td><div id="nameHint">Name: {{ $name }}</div></td>
<td><div id="priceHint">Price: {{ $price }}</div></td>

then, in your php side you will need to echo some data , and to send multiple data the best approach by encode it into json , then decode that json from your client side and parse it into DOM elements using javascript.

so , in your php code , modify it to be as follows :

$price = $sql[0]->price;
$name = $sql[0]->name;
echo json_encode(array("price" => $price, "name" => $name));

then from your client side , decode that json as follows :

if (this.readyState == 4 && this.status == 200) {
    var jsonObject = JSON.parse(this.responseText);
    document.getElementById("priceHint").innerHTML = jsonObject['price'];
    document.getElementById("nameHint").innerHTML = jsonObject['name'];
}


问:
Is this a good way to parse a ftp url scheme?
I write a small java tool and a at the beginning I have to parse a url. I would like to know, what you are thinking about my solution and if there is a better way?
Here are some examples:

aaa://username:password@server:port/dir/

aaa://server:port/dir/

aaa://server:port

Every kind of String is possible, if the user is not carefully. So it is possible, that my function get such a string

aaa://username:pass

too. But the string always starts witch aaa://.

Here is my code:

url = url.replaceFirst("aaa://", "");

```<code>String params[] = url.split("@");
if(params[0].compareTo("") != 0) {
    String paramsfst[] = params[0].split(":");
    if(params.length == 1) {
        if(paramsfst.length >= 1) {
            this.server = parsePort(paramsfst[0]);
            if(paramsfst.length == 2) {
                this.port = parsePort(paramsfst[1]);
            }
        }
    } else {
        String paramssec[] = params[1].split(":");
        if(paramssec.length >= 1) {
            this.server = parsePort(paramssec[0]);
            if(paramssec.length == 2) {
                this.port = parsePort(paramssec[1]);
            }
        }
        if(paramsfst.length == 2) {
            this.username = paramsfst[0];
            this.password = paramsfst[1];
        }
    }
    if(url.contains("/")) {
        this.path = url.substring(url.indexOf("/"), url.length() -1);
    }

private String parsePort(String port) {
    int i = port.indexOf("/");
    if(i == -1) {
        return port;
    }
    return port.substring(0, i);
}
</code>```

What do you think?

答:
I think you are looking for java.net.URI:

```<code>final String destination = "ftp://anonymous@localhost:21/inbox?password=secret"

final URI uri = new URI(destination);

String host = uri.getHost(); //localhost
final int port = uri.getPort(); //21
final String directoryPath = uri.getPath();  //inbox
String username = uri.getUserInfo(); //anonymous

//The password can exist as a query parameter or as part of the user info
final List<NameValuePair> queryParams = URLEncodedUtils.parse(uri, "UTF-8");
final Map<String, String> paramsMap = new HashMap();
queryParams.forEach((param) -> { paramsMap.put(param.getName(), param.getValue()); });

String password = null;
if (paramsMap.containsKey("password"))
{
    password = paramsMap.get("password"); //secret
}
else if ((username != null) && username.contains(":"))
{
    password = username.split(":")[1];
    username = username.split(":")[0];
}
</code>```

Body:
I write a small java tool and a at the beginning I have to parse a url. I would like to know, what you are thinking about my solution and if there is a better way?
Here are some examples:

aaa://username:password@server:port/dir/

aaa://server:port/dir/

aaa://server:port

Every kind of String is possible, if the user is not carefully. So it is possible, that my function get such a string

aaa://username:pass

too. But the string always starts witch aaa://.

Here is my code:

url = url.replaceFirst("aaa://", "");

String params[] = url.split("@");
if(params[0].compareTo("") != 0) {
    String paramsfst[] = params[0].split(":");
    if(params.length == 1) {
        if(paramsfst.length >= 1) {
            this.server = parsePort(paramsfst[0]);
            if(paramsfst.length == 2) {
                this.port = parsePort(paramsfst[1]);
            }
        }
    } else {
        String paramssec[] = params[1].split(":");
        if(paramssec.length >= 1) {
            this.server = parsePort(paramssec[0]);
            if(paramssec.length == 2) {
                this.port = parsePort(paramssec[1]);
            }
        }
        if(paramsfst.length == 2) {
            this.username = paramsfst[0];
            this.password = paramsfst[1];
        }
    }
    if(url.contains("/")) {
        this.path = url.substring(url.indexOf("/"), url.length() -1);
    }

private String parsePort(String port) {
    int i = port.indexOf("/");
    if(i == -1) {
        return port;
    }
    return port.substring(0, i);
}

What do you think?

Body:
I think you are looking for java.net.URI:

final String destination = "ftp://anonymous@localhost:21/inbox?password=secret"

final URI uri = new URI(destination);

String host = uri.getHost(); //localhost
final int port = uri.getPort(); //21
final String directoryPath = uri.getPath();  //inbox
String username = uri.getUserInfo(); //anonymous

//The password can exist as a query parameter or as part of the user info
final List<NameValuePair> queryParams = URLEncodedUtils.parse(uri, "UTF-8");
final Map<String, String> paramsMap = new HashMap();
queryParams.forEach((param) -> { paramsMap.put(param.getName(), param.getValue()); });

String password = null;
if (paramsMap.containsKey("password"))
{
    password = paramsMap.get("password"); //secret
}
else if ((username != null) && username.contains(":"))
{
    password = username.split(":")[1];
    username = username.split(":")[0];
}


答:
I assume your problem is that you don't know how to access the chosen card, once the player picks a number.

If that's the case, you're already close to the solution!

When the player inputs a number, you've stored it as a string in the pick variable. The next steps are to:

convert that string to an integer, and

find the card at that position in the deck.

Python has a built-in int function, to convert the pick from a string to an integer.

Your deck variable is a list, and to get items out of a list in Python, you can request the item by index. The index is a number representing the position of that item:

```<code>animals = ["cat", "dog", "fish", "pterodactyl]
print(animals[0]) # "cat"
print(animals[1]) # "dog"
print(animals[2]) # "fish"
</code>```

Adding this to your code should do the trick:

```<code>pick = int(pick)
card = deck[pick]
print("Your card is", card)
</code>```

Title: Python- Card Selection

Body:
I'm new to python and I'm trying to figure out how to ask the user for input and then use that input to select a specific card from a deck of cards. This is what I have so far

cardfaces = []
suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
royals = ["J", "Q", "K", "A"]
deck = []

for i in range(2,11):
    cardfaces.append(str(i))

for j in range(4):
    cardfaces.append(royals[j])

for k in range(4):
    for l in range(13):
        card = (cardfaces[l] + " of " + suits[k])
        deck.append(card)

for m in range(52):
    print(deck[m])
pick=input('Pick a card 1-52 :')

Body:
I assume your problem is that you don't know how to access the chosen card, once the player picks a number.

If that's the case, you're already close to the solution!

When the player inputs a number, you've stored it as a string in the pick variable. The next steps are to:

convert that string to an integer, and

find the card at that position in the deck.

Python has a built-in int function, to convert the pick from a string to an integer.

Your deck variable is a list, and to get items out of a list in Python, you can request the item by index. The index is a number representing the position of that item:

animals = ["cat", "dog", "fish", "pterodactyl]
print(animals[0]) # "cat"
print(animals[1]) # "dog"
print(animals[2]) # "fish"

Adding this to your code should do the trick:

pick = int(pick)
card = deck[pick]
print("Your card is", card)


问:
How to find the workflow running instances by JAVA in AEM
How to find the available workflow instances that are running in an AEM instance Programmatically.</p>

答:
You can find the all workflows in your workflow session from the Interface com.adobe.granite.workflow.WorkflowSession by using Workflow[] workflows = wfSession.getAllWorkflows()

and you can get the workflow state by using Interface com.adobe.granite.workflow.exec.Workflow getState() method. For more information you can look for the workflow api document.

WorkflowSession API CQ 5.6

WorkflowSession API AEM 6.1

WorkflowSession API AEM 6.2


问:
Create group ID for runs of non-zero values
I would like to find contiguous runs of non-zero elements in a vector (separated by at least one zero), and to assign an ID to each group (subsequent integer).

Toy vector:

value <- c(1, 1, 2, 3, 4, 3,   0, 0, 0,   1, 2, 3, 9, 8,   0, 0,   3, 2)

In this example, there are three runs of non-zero values: [1,1,2,3,4,3], [1,2,3,9,8], [3,2], separated by chunks of one or more zeros.

Each non-zero run should have a unique ID: 1, 2, 3... Runs of zero should have NA as ID:

```<code>   value id
1      1  1
2      1  1
3      2  1
4      3  1
5      4  1
6      3  1
7      0 NA
8      0 NA
9      0 NA
10     1  2
11     2  2
12     3  2
13     9  2
14     8  2
15     0 NA
16     0 NA
17     3  3
18     2  3
</code>```

答:
You need to define a vector of vectors so in v[0] you will find all values of the first group, and in v[1] you will find all values of the second group and so on,

You need to loop on all values when you find a zero value. Continue until you find anon zero. Increment the vector with one and add the value and so on,

I wish this answer be helpful.

ContentLicense: CC BY-SA 4.0

Body:
I would like to find contiguous runs of non-zero elements in a vector (separated by at least one zero), and to assign an ID to each group (subsequent integer).

Toy vector:

value <- c(1, 1, 2, 3, 4, 3,   0, 0, 0,   1, 2, 3, 9, 8,   0, 0,   3, 2)

In this example, there are three runs of non-zero values: [1,1,2,3,4,3], [1,2,3,9,8], [3,2], separated by chunks of one or more zeros.

Each non-zero run should have a unique ID: 1, 2, 3... Runs of zero should have NA as ID:

   value id
1      1  1
2      1  1
3      2  1
4      3  1
5      4  1
6      3  1
7      0 NA
8      0 NA
9      0 NA
10     1  2
11     2  2
12     3  2
13     9  2
14     8  2
15     0 NA
16     0 NA
17     3  3
18     2  3


问:
Zoomed/stretched images with IE11 but not with Chrome/Firefox
Swiper (?) doesn't behave perfectly when displaying images under IE11. The images are rendered perfectly on Chrome and Firefox.

And you can see this live here

Here's the code (for what it's worth, it's laravel that generates it)

```<code><div class="row">
    <div class="col-xs-12">
        <div class="panel panel-default">
            <div class="panel-heading">
                <i class="fa fa-car"></i> {{ trans('navs.general.pictures') }}
            </div>

            <div class="panel-body">
                    <div class="swiper-container">
                        <div class="swiper-pagination"></div>
                        <div class="swiper-button-next"></div>
                        <div class="swiper-button-prev"></div>
                        <div class="swiper-wrapper">
                            @foreach($car->getMedia('vehicules') as $i)
                             <div class="swiper-slide" style="background-image:url({{ $i->getUrl() }})">
                             <img data-src="{{ $i->getUrl() }}" src="{{ $i->getUrl() }}" alt="Photo">
                            </div>
                            @endforeach
                        </div>
                    </div>
            </div>
        </div><!-- panel -->
    </div><!-- col-md-10 -->

</div><!--row-->
@section('after-scripts')
<script src='/js/swiper/swiper.jquery.js'></script>
<script>
  $(document).ready(function () {
    //initialize swiper when document ready
    var mySwiper = new Swiper ('.swiper-container', {
      // Optional parameters
      pagination: '.swiper-pagination',
      paginationClickable: true,
        nextButton: '.swiper-button-next',
        prevButton: '.swiper-button-prev',
    })
  });
</script>
@stop
@section('before-styles')
<link rel="stylesheet" href="/css/swiper/swiper.css">
<style>
    html, body {
        position: relative;
        height: 100%;
    }
    .swiper-container {
        width: 100%;
        height: 100%;
    }
    .swiper-slide {
        text-align: center;
        font-size: 18px;
        background: #fff;
        width: auto;
        /* Center slide text vertically */
        display: -webkit-box;
        display: -ms-flexbox;
        display: -webkit-flex;
        display: flex;
        -webkit-box-pack: center;
        -ms-flex-pack: center;
        -webkit-justify-content: center;
        justify-content: center;
        -webkit-box-align: center;
        -ms-flex-align: center;
        -webkit-align-items: center;
        align-items: center;
    }
    </style>
@stop
</code>```

EDIT:
This fixed it:

```<code>.swiper-container img {
    width: 100%;
 }
</code>```

答:
The image itself has max-width: 100%;. The actual width is being defined by .swiper-container .swiper-container-horizontal but there's a few layers of divs with width: 100% between that.

This issue is probably easier to fix than it is to understand. I'm on Linux, but I'll give some guesses.

It may be that because the image doesn't have width, IE uses the max-width.

Try defining the width on the image.

Try removing the max-width, and/or applying it to a parent.

Body:
Swiper (?) doesn't behave perfectly when displaying images under IE11. The images are rendered perfectly on Chrome and Firefox.

And you can see this live here

Here's the code (for what it's worth, it's laravel that generates it)

                 {{ trans('navs.general.pictures') }}

                            @foreach($car->getMedia('vehicules') as $i)

getUrl() }})">
                             getUrl() }}" src="{{ $i->getUrl() }}" alt="Photo">

                            @endforeach

@section('after-scripts')

@stop
@section('before-styles')
<link rel="stylesheet" href="/css/swiper/swiper.css">

@stop

EDIT:
This fixed it:

.swiper-container img {
    width: 100%;
 }


问:
Apache Directory Studio java was started but returned exit code=13
I have to install Apache Directory Studio.

For this I perform the below Steps

Download ApacheDirectoryStudio-win32-x86-2.0.0.v20130628.exe

Double click on ApacheDirectoryStudio-win32-x86-2.0.0.v20130628.exe and perform Next than it ask for Java Home Directory

I browse and give the path C:\Program Files\Java\jdk1.8.0_60\ on Java Home Directory and perform Next Steps as Default Configuration

After complete installation of Apache Directory Studio when I try to Open Apache Directory Studio it gives the following Error

I am using Java 1.8 and Windows 10.

答:
If you look at the second line in the error dialog screenshot, it shows the path that it is looking for the javaw.exe file. It is C:\ProgramData\Oracle\Java\javapath.

If you browse to this directory you'll se that it contains three shortcuts to java.exe, javaw.exe and javas.exe. Make sure that these shortcuts are pointing to valid exe files. If not delete these shortcuts and create new ones.


问:
How to know when application is exit in .Net Compact framework?
I have a .Net Compact Framework WinForm application , I want to catch Application OnExit event but there is no such event available.

Does anyone know any work around to achieve the same ?

答: If your app is architected "normally" that is the Form being passed to Application.Run is closed, then whatever code is after the call to Run in Main is going to execute.  You could raise your own event there, or do whatever handling you need at that point.


问:
What is the best practice to manage sessions with Ionic 2
i have an app on ionic 2 and i dont know how to manage the user session, i wanna that the user inserts his credentials every time that launch the app</p>

答:
You should use Ionic Auth - https://ionic.io/docs/auth-connect

This page is pretty clear in explaining what you need to do. There are also several methods of authentication. You can use Ionic's backend services to handle this for you. Alternatively you can handle the authentication at your end and return a JWT. There are also many social logins available.

On your specific point about wanting users to log in each time they open the app. I'll draw your attention to the final section of the URL.

How can I require users to login every time the app is opened?

By default, we keep users logged in. If you only want them to be logged in for the duration of the app being opened, you need to set remember: false in your login options.

```<code>this.auth.login('basic', details, {'remember': false});
</code>```

Body:
You should use Ionic Auth - https://ionic.io/docs/auth-connect

This page is pretty clear in explaining what you need to do. There are also several methods of authentication. You can use Ionic's backend services to handle this for you. Alternatively you can handle the authentication at your end and return a JWT. There are also many social logins available.

On your specific point about wanting users to log in each time they open the app. I'll draw your attention to the final section of the URL.

How can I require users to login every time the app is opened?

By default, we keep users logged in. If you only want them to be logged in for the duration of the app being opened, you need to set remember: false in your login options.

this.auth.login('basic', details, {'remember': false});


问:
Android paste large text file into edittext
I have an app and I need users to be able to paste any amount of text into an edittext box. I would like users to be able to paste up to at least 100,000 words if possible. How can I accomplish this with android? Attaching a file isn't possible.

Here is the xml for my edittext if that helps.

```<code>    <EditText
    android:id="@+id/editText"
    android:ems="10"
    android:inputType="textMultiLine"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    android:text=""
    android:minLines="2"
    android:textIsSelectable="true"
    android:isScrollContainer="true"
    android:focusable="true"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textView2"

    />
</code>```

And if it helps this is all I am doing with the edit text

```<code>final EditText input = (EditText) findViewById(R.id.editText);
    button2.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            document = input.getText().toString();
</code>```

答: Turns out the device I was using for testing couldn't handle the input. </p>

Body:
I have an app and I need users to be able to paste any amount of text into an edittext box. I would like users to be able to paste up to at least 100,000 words if possible. How can I accomplish this with android? Attaching a file isn't possible.

Here is the xml for my edittext if that helps.

    <EditText
    android:id="@+id/editText"
    android:ems="10"
    android:inputType="textMultiLine"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    android:text=""
    android:minLines="2"
    android:textIsSelectable="true"
    android:isScrollContainer="true"
    android:focusable="true"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textView2"

    />

And if it helps this is all I am doing with the edit text

final EditText input = (EditText) findViewById(R.id.editText);
    button2.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            document = input.getText().toString();


问:
Java MySQL Connection with SSL Authority Certificate
I am trying to connect using Java Rest WebService to a JDBC.

First I connected successfully using MySQL Workbench with username and password and one extra detail, I needed to add a "Path to Certificate Authority file for SSL" and worked, I was able to connect and use.I have the certificate to use the database remote.

Now I am trying to connect using Java and that is the way I am trying:

```<code>import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConexaoBD {
    // Define o Metodo de Conexao quando a classe � chamada
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public Connection obtemConexao() throws SQLException {
        System.getProperties().setProperty("javax.net.ssl.trustStore","/mysqlcertificate.pem");
        return DriverManager.getConnection("jdbc:mysql://myHost", "myUsername", "myPassword");
    }
}
</code>```

I research about put useSSL=true in the URL but didn't work or this system.getproperties, I also p the .pem file in the project package and inside my class package (because I don't know what is the place I need to put the file).

What should I do to connect? Without this SSL, the database refuse my connection, and I am trying to connect in another class this way:

```<code>Connection conn = null;
Statement stm = null;
try {
    ConexaoBD bd = new ConexaoBD();
    conn = bd.obtemConexao();
</code>```

Can anyone help me?

答:
My case was similar, but not same. I could connect to MySQL from workbench but not from my code. The only option selected in workbench was useSSL if Available.
The code below worked for me in that case. </p>

```<code>private String db_server = BaseMethods.getSystemData("db_server");
private String db_user = BaseMethods.getSystemData("db_user");
private String db_password = BaseMethods.getSystemData("db_password");

private void connectToDb() throws Exception {
    String jdbcDriver = "com.mysql.jdbc.Driver";
    String dbUrl = "jdbc:mysql://" + db_server +
        "?verifyServerCertificate=false" +
        "&useSSL=true" +
        "&requireSSL=true";
    System.setProperty(jdbcDriver, "");
    Class.forName(jdbcDriver).newInstance();

    Connection conn = DriverManager.getConnection(dbUrl, db_user, db_password);
    Statement statement = conn.createStatement();
}
</code>```

Body:
I am trying to connect using Java Rest WebService to a JDBC.

First I connected successfully using MySQL Workbench with username and password and one extra detail, I needed to add a "Path to Certificate Authority file for SSL" and worked, I was able to connect and use.I have the certificate to use the database remote.

Now I am trying to connect using Java and that is the way I am trying:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConexaoBD {
    // Define o Metodo de Conexao quando a classe � chamada
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public Connection obtemConexao() throws SQLException {
        System.getProperties().setProperty("javax.net.ssl.trustStore","/mysqlcertificate.pem");
        return DriverManager.getConnection("jdbc:mysql://myHost", "myUsername", "myPassword");
    }
}

I research about put useSSL=true in the URL but didn't work or this system.getproperties, I also p the .pem file in the project package and inside my class package (because I don't know what is the place I need to put the file).

What should I do to connect? Without this SSL, the database refuse my connection, and I am trying to connect in another class this way:

Connection conn = null;
Statement stm = null;
try {
    ConexaoBD bd = new ConexaoBD();
    conn = bd.obtemConexao();

Can anyone help me?

Body:
My case was similar, but not same. I could connect to MySQL from workbench but not from my code. The only option selected in workbench was useSSL if Available.
The code below worked for me in that case.

private String db_server = BaseMethods.getSystemData("db_server");
private String db_user = BaseMethods.getSystemData("db_user");
private String db_password = BaseMethods.getSystemData("db_password");

private void connectToDb() throws Exception {
    String jdbcDriver = "com.mysql.jdbc.Driver";
    String dbUrl = "jdbc:mysql://" + db_server +
        "?verifyServerCertificate=false" +
        "&useSSL=true" +
        "&requireSSL=true";
    System.setProperty(jdbcDriver, "");
    Class.forName(jdbcDriver).newInstance();

    Connection conn = DriverManager.getConnection(dbUrl, db_user, db_password);
    Statement statement = conn.createStatement();
}


问:
Why this code getting me error message?astropy: attribute error cannot import fitting
i want to use astropy for fitting spectra my code is:

```<code>from astropy.io import fits
from astropy.modeling import models, fitting
import math
import numpy as np
import pylab as plb
import matplotlib.pyplot as plt
#after opening  the fits file and reading its data pixel by pixel
# fitting for the spectra at a pixel
x = velocity
y = ant_tem
g_init = models.Gaussian1D(amplitude=1., mean=0, stddev=1.)
f1 = fitting.NonLinearLSQFitter()
g = f1(g_init, x,y)
# Plot the data with the best-fit model
plt.figure(figsize=(8,5))
plt.plot(x, y, 'ko')
plt.plot(x, g(x), 'r-', lw=2, label='Gaussian')
plt.xlabel('Velocity')
plt.ylabel('Antenne Temperature')
plt.legend(loc=2)
</code>```

`
But my code is giving me the following error:

```<code>in <module>
    f1 = fitting.NonLinearLSQFitter().
AttributeError: 'module' object has no attribute 'NonLinearLSQFitter'
Please suggest what should i do?
</code>```

答:
You're using astropy 0.3 or earlier documentation.

NonLinearLSQFitter has been renamed LevMarLSQFitter in astropy 0.4 and later. Use that instead.

Body:
i want to use astropy for fitting spectra my code is:

from astropy.io import fits
from astropy.modeling import models, fitting
import math
import numpy as np
import pylab as plb
import matplotlib.pyplot as plt
#after opening  the fits file and reading its data pixel by pixel
# fitting for the spectra at a pixel
x = velocity
y = ant_tem
g_init = models.Gaussian1D(amplitude=1., mean=0, stddev=1.)
f1 = fitting.NonLinearLSQFitter()
g = f1(g_init, x,y)
# Plot the data with the best-fit model
plt.figure(figsize=(8,5))
plt.plot(x, y, 'ko')
plt.plot(x, g(x), 'r-', lw=2, label='Gaussian')
plt.xlabel('Velocity')
plt.ylabel('Antenne Temperature')
plt.legend(loc=2)

`
But my code is giving me the following error:

in <module>
    f1 = fitting.NonLinearLSQFitter().
AttributeError: 'module' object has no attribute 'NonLinearLSQFitter'
Please suggest what should i do?


问:
Stack overflow in recursive method
I'm writing a program that allows a user to input a set of integers into an array and characteristics of those numbers will be displayed once a zero is entered. I am having an issue with one method:findMaxOfLessThanFirst. Which, of course, finds the maximum number in the array that is also less than the first number entered. Here is the full code:

```<code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Assignment9 {
    public static void main(String[] args) throws IOException {
        int index = 0;
        int[] numbers;
        numbers = new int[100];

        InputStreamReader inRead = new InputStreamReader(System.in);
        BufferedReader buffRead = new BufferedReader(inRead);
        String line = buffRead.readLine();

        try {
            while (!line.equals("0") && index < 100) {
                numbers[index] = Integer.parseInt(line);
                index++;
                line = buffRead.readLine();
            }
        } catch (IOException exception) {
            System.out.println("Array index out of bound");
        }
        int min = findMin(numbers, 0);
        int sumAtEven = computeSumAtEvenIndexes(numbers, 0, numbers.length - 1);
        int divByThree = countDivisibleBy3(numbers, 0, numbers.length - 1);
        int maxLessThanFirst = findMaxOfLessThanFirst(numbers, 1, numbers.length - 1, numbers[0]);
        System.out.println("The minimum number is " + min);
        System.out.println("The sum of numbers at even indexes is " + sumAtEven);
        System.out.println("The count of numbers that are divisible by 3 is " + divByThree);
        System.out.println(
                "The maximum number among numbers that are less than the first number is " + maxLessThanFirst);
    }

    public static int findMin(int[] numbers, int index) {
        if (index == numbers.length - 1) {
            return numbers[index];
        } else {
            return Math.min(numbers[index], findMin(numbers, index + 1));
        }
    }

    public static int computeSumAtEvenIndexes(int[] numbers, int startIndex, int endIndex) {
        if (startIndex == endIndex) {
            if (startIndex % 2 == 0) {
                return numbers[startIndex];
            } else
                return 0;
        } else {
            if (endIndex % 2 == 0) {
                return computeSumAtEvenIndexes(numbers, startIndex, endIndex - 1) + numbers[endIndex];
            } else {
                return computeSumAtEvenIndexes(numbers, startIndex, endIndex - 1);
            }
        }
    }

    public static int countDivisibleBy3(int[] numbers, int startIndex, int endIndex) {
        if (startIndex == endIndex) {
            if (numbers[startIndex] % 3 == 0) {
                return +2;
            } else {
                return 1;
            }
        } else {
            if (numbers[endIndex] == 0) {
                return countDivisibleBy3(numbers, startIndex, endIndex - 1);
            }
            if (numbers[endIndex] % 3 == 0) {
                return countDivisibleBy3(numbers, startIndex, endIndex - 1) + 1;
            } else {
                return countDivisibleBy3(numbers, startIndex, endIndex - 1);
            }
        }
    }

    private static int findMaxOfLessThanFirst(int[] numbers, int startIndex, int endIndex, int firstNumber) {
        if (startIndex == endIndex) {
            if (numbers[endIndex] <= firstNumber)
                return numbers[startIndex];
        }
        int max = findMaxOfLessThanFirst(numbers, startIndex, endIndex - 1, firstNumber);
        if (max >= numbers[endIndex] && max <= firstNumber) {
            return max;
        }
        return numbers[endIndex];
    }
}
</code>```

I am sure I'm missing something really elementary here. I just started learning the concept of recursion. So, please be gentle.

答:
All you need to do is to remove the nested if condition inside the first if. That is redundant as both startIndex and endIndex are same. Below should work:

```<code>private static int findMaxOfLessThanFirst(int[] numbers, int startIndex, int endIndex, int firstNumber) {
    if (startIndex == endIndex) {
        return numbers[startIndex];
    }
    int max = findMaxOfLessThanFirst(numbers, startIndex, endIndex - 1, firstNumber);
    if (max >= numbers[endIndex] && max <= firstNumber) {
        return max;
    }
    return numbers[endIndex];
}
</code>```

Title: Stack overflow in recursive method

Body:
I'm writing a program that allows a user to input a set of integers into an array and characteristics of those numbers will be displayed once a zero is entered. I am having an issue with one method:findMaxOfLessThanFirst. Which, of course, finds the maximum number in the array that is also less than the first number entered. Here is the full code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Assignment9 {
    public static void main(String[] args) throws IOException {
        int index = 0;
        int[] numbers;
        numbers = new int[100];

        InputStreamReader inRead = new InputStreamReader(System.in);
        BufferedReader buffRead = new BufferedReader(inRead);
        String line = buffRead.readLine();

        try {
            while (!line.equals("0") && index < 100) {
                numbers[index] = Integer.parseInt(line);
                index++;
                line = buffRead.readLine();
            }
        } catch (IOException exception) {
            System.out.println("Array index out of bound");
        }
        int min = findMin(numbers, 0);
        int sumAtEven = computeSumAtEvenIndexes(numbers, 0, numbers.length - 1);
        int divByThree = countDivisibleBy3(numbers, 0, numbers.length - 1);
        int maxLessThanFirst = findMaxOfLessThanFirst(numbers, 1, numbers.length - 1, numbers[0]);
        System.out.println("The minimum number is " + min);
        System.out.println("The sum of numbers at even indexes is " + sumAtEven);
        System.out.println("The count of numbers that are divisible by 3 is " + divByThree);
        System.out.println(
                "The maximum number among numbers that are less than the first number is " + maxLessThanFirst);
    }

    public static int findMin(int[] numbers, int index) {
        if (index == numbers.length - 1) {
            return numbers[index];
        } else {
            return Math.min(numbers[index], findMin(numbers, index + 1));
        }
    }

    public static int computeSumAtEvenIndexes(int[] numbers, int startIndex, int endIndex) {
        if (startIndex == endIndex) {
            if (startIndex % 2 == 0) {
                return numbers[startIndex];
            } else
                return 0;
        } else {
            if (endIndex % 2 == 0) {
                return computeSumAtEvenIndexes(numbers, startIndex, endIndex - 1) + numbers[endIndex];
            } else {
                return computeSumAtEvenIndexes(numbers, startIndex, endIndex - 1);
            }
        }
    }

    public static int countDivisibleBy3(int[] numbers, int startIndex, int endIndex) {
        if (startIndex == endIndex) {
            if (numbers[startIndex] % 3 == 0) {
                return +2;
            } else {
                return 1;
            }
        } else {
            if (numbers[endIndex] == 0) {
                return countDivisibleBy3(numbers, startIndex, endIndex - 1);
            }
            if (numbers[endIndex] % 3 == 0) {
                return countDivisibleBy3(numbers, startIndex, endIndex - 1) + 1;
            } else {
                return countDivisibleBy3(numbers, startIndex, endIndex - 1);
            }
        }
    }

    private static int findMaxOfLessThanFirst(int[] numbers, int startIndex, int endIndex, int firstNumber) {
        if (startIndex == endIndex) {
            if (numbers[endIndex] <= firstNumber)
                return numbers[startIndex];
        }
        int max = findMaxOfLessThanFirst(numbers, startIndex, endIndex - 1, firstNumber);
        if (max >= numbers[endIndex] && max <= firstNumber) {
            return max;
        }
        return numbers[endIndex];
    }
}

I am sure I'm missing something really elementary here. I just started learning the concept of recursion. So, please be gentle.

Body:
All you need to do is to remove the nested if condition inside the first if. That is redundant as both startIndex and endIndex are same. Below should work:

private static int findMaxOfLessThanFirst(int[] numbers, int startIndex, int endIndex, int firstNumber) {
    if (startIndex == endIndex) {
        return numbers[startIndex];
    }
    int max = findMaxOfLessThanFirst(numbers, startIndex, endIndex - 1, firstNumber);
    if (max >= numbers[endIndex] && max <= firstNumber) {
        return max;
    }
    return numbers[endIndex];
}