问:
Objective C Socket Server does not receive Java Socket Client Messages
I created server in Objective C, using CocoaAsyncTask, it works fine if I connect from telnet both localhost and on same network.

Now I have a client in Java, that works fine with another Java server and I cannot get to communicate; no messages are received on sever side.

For reference, here is the Java Client code:

```<code>    public class Client {
   public static void main(String[] args) {
       try {
           Socket socket = new Socket("192.168.0.106",4353);
           PrintWriter printWriter = new PrintWriter(socket.getOutputStream(),true);
           BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

           while (true) {
               System.out.println("Enter message: ");
               String msg = br.readLine();

               if (msg != null && !msg.equals("bye"))
               {
                   printWriter.println(msg);
               }
               else
               {
                   break;
               } } } catch (IOException e) {e.printStackTrace();} } }
</code>```

And the server Objective C code:

```<code>    ...
    [newSocket readDataToData:[GCDAsyncSocket CRLFData] withTimeout:15.0 tag:0];
    ...

    (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
        dispatch_async(dispatch_get_main_queue(), ^{
            @autoreleasepool {
                DDLogInfo(@"data: %@", data);
                NSData *strData = [data subdataWithRange:NSMakeRange(0, [data length] - 2)];
                DDLogInfo(@"Info: %@", strData);
                NSString *msg = [[NSString alloc] initWithData:strData encoding:NSUTF8StringEncoding];
                DDLogInfo(@"Info: %@", msg);
</code>```

We've tried appending \n and \r at the end, but no success.

What could cause this miss-communication?

答:
The problem was on the server side, by receiving the data from socket using readDataToData, instead of readDataWithTimeout.

Most probable, the problem is in line ending, so the library does not process it as a line, thus not calling the method for the next data.

Body:
I created server in Objective C, using CocoaAsyncTask, it works fine if I connect from telnet both localhost and on same network.

Now I have a client in Java, that works fine with another Java server and I cannot get to communicate; no messages are received on sever side.

For reference, here is the Java Client code:

    public class Client {
   public static void main(String[] args) {
       try {
           Socket socket = new Socket("192.168.0.106",4353);
           PrintWriter printWriter = new PrintWriter(socket.getOutputStream(),true);
           BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

           while (true) {
               System.out.println("Enter message: ");
               String msg = br.readLine();

               if (msg != null && !msg.equals("bye"))
               {
                   printWriter.println(msg);
               }
               else
               {
                   break;
               } } } catch (IOException e) {e.printStackTrace();} } }

And the server Objective C code:

    ...
    [newSocket readDataToData:[GCDAsyncSocket CRLFData] withTimeout:15.0 tag:0];
    ...

    (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
        dispatch_async(dispatch_get_main_queue(), ^{
            @autoreleasepool {
                DDLogInfo(@"data: %@", data);
                NSData *strData = [data subdataWithRange:NSMakeRange(0, [data length] - 2)];
                DDLogInfo(@"Info: %@", strData);
                NSString *msg = [[NSString alloc] initWithData:strData encoding:NSUTF8StringEncoding];
                DDLogInfo(@"Info: %@", msg);

We've tried appending \n and \r at the end, but no success.

What could cause this miss-communication?


来源: stackexchange

问:
issue to remove NavigationView menu item selected color?
Hi all i am facing one strange issue. I added Navigation View in my Activity and by default every time when i start the App the first navigation item selected with some background color.

I want to remove this feature.

My gradle:

```<code>dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:22.2.1'
compile 'com.android.support:design:22.2.1'
}
</code>```

Code:

```<code>public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
  }
}
</code>```

Menu XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

<group android:checkableBehavior="single">
    <item
        android:id="@+id/nav_camera"
        android:icon="@drawable/ic_menu_camera"
        android:title="Import" />
    <item
        android:id="@+id/nav_gallery"
        android:icon="@drawable/ic_menu_gallery"
        android:title="Gallery" />
    <item
        android:id="@+id/nav_slideshow"
        android:icon="@drawable/ic_menu_slideshow"
        android:title="Slideshow" />
    <item
        android:id="@+id/nav_manage"
        android:icon="@drawable/ic_menu_manage"
        android:title="Tools" />
</group>
</code>```

Layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">

<include
    layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main"
    app:menu="@menu/activity_main_drawer" />

   </android.support.v4.widget.DrawerLayout>
</code>```

SnapShot::

Any hint how to remove this type of features?

答:
```<code>return false;
</code>```

In the end of public boolean onNavigationItemSelected(MenuItem item)

does the job

ContentLicense: CC BY-SA 3.0

Body:
Hi all i am facing one strange issue. I added Navigation View in my Activity and by default every time when i start the App the first navigation item selected with some background color.

I want to remove this feature.

My gradle:

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:22.2.1'
compile 'com.android.support:design:22.2.1'
}

Code:

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
  }
}

Menu XML:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

<group android:checkableBehavior="single">
    <item
        android:id="@+id/nav_camera"
        android:icon="@drawable/ic_menu_camera"
        android:title="Import" />
    <item
        android:id="@+id/nav_gallery"
        android:icon="@drawable/ic_menu_gallery"
        android:title="Gallery" />
    <item
        android:id="@+id/nav_slideshow"
        android:icon="@drawable/ic_menu_slideshow"
        android:title="Slideshow" />
    <item
        android:id="@+id/nav_manage"
        android:icon="@drawable/ic_menu_manage"
        android:title="Tools" />
</group>

Layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">

<include
    layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main"
    app:menu="@menu/activity_main_drawer" />

   </android.support.v4.widget.DrawerLayout>

SnapShot::

Any hint how to remove this type of features?

Body:
return false;

In the end of public boolean onNavigationItemSelected(MenuItem item)

does the job


问:
Transmission torrent client sequential download
I'm using TransmissionBT torrent client (http://www.transmissionbt.com/).

Is it possible to make simple modification in code to be able to download files in sequential mode (from beginning of the file). Then it will be possible to play video file without waiting to finish downloading whole file.
I found solution for it - https://trac.transmissionbt.com/wiki/Can%20I%20sequence%20the%20files%20I%20download but it's from 7 years ago and in current version there is no function mentioned in link.

答: The qBittorrent has such a built-in function, from the context menu of the torrent


问:
calculate sum or product based on input
I am asking user to enter 2 numbers and s for sum, or "p" for product.
when I run the script I don't see any results
here is my script</p>

```<code>#!/bin/bash

read -p "please enter two integers, s or p to calculate sum or  product of this numbers: "  num1 num2 result
if [ result == "s" ]
then
echo "num1+num2" | bc

elif [ result == "p" ]
then
echo $((num1*num2))

fi
</code>```

答:
You are comparing the string result, not the value of the variable result.

```<code>if [ "$result" = s ]; then
    echo "$(($num1 + $num2))"
elif [ "$result" = p ]; then
    echo "$(($num1 * $num2))"
fi
</code>```

Inside $((...)), you can omit the leading $ because a string is assumed to be a variable name to be dereferenced.

There's no reason to use bc if you intend to restrict the inputs to integers.

Title: calculate sum or product based on input

Body:
I am asking user to enter 2 numbers and s for sum, or "p" for product.
when I run the script I don't see any results
here is my script

#!/bin/bash

read -p "please enter two integers, s or p to calculate sum or  product of this numbers: "  num1 num2 result
if [ result == "s" ]
then
echo "num1+num2" | bc

elif [ result == "p" ]
then
echo $((num1*num2))

fi

Body:
You are comparing the string result, not the value of the variable result.

if [ "$result" = s ]; then
    echo "$(($num1 + $num2))"
elif [ "$result" = p ]; then
    echo "$(($num1 * $num2))"
fi

Inside $((...)), you can omit the leading $ because a string is assumed to be a variable name to be dereferenced.

There's no reason to use bc if you intend to restrict the inputs to integers.


问:
Pandas: Error while searching asterisk in dataframe. Eg: busiest_hosts['host'].str.contains('***.botol.dk')
Below is what my dataframe looks like, as you would see one of my dataframe column is URL and other is timestamp count. When I am running this code: busiest_hosts[busiest_hosts['host'].str.contains('***.novo.dk')==True] I get an error: error: nothing to repeat at position 0. Which I think is because the first element of my URL is *. It seems like a python bug (my python version is 3.x). I would really appreciate if anyone could help me in resolving this.

答:
contains assumes the string is a regex expression and interprets the * as a command to repeat the prior character or expression.  You want to escape the *.  And while you're at it, escape the . as well.

```<code>busiest_hosts[busiest_hosts['host'].str.contains('\*{3}\.novo\.dk')==True]
</code>```

demo

```<code>busiest_hosts = pd.DataFrame(dict(host=['***.novo.dk', '007.thegap.com'], timestamp=[16, 45]))

print(busiest_hosts)

             host  timestamp
0     ***.novo.dk         16
1  007.thegap.com         45
</code>```

```<code>busiest_hosts[busiest_hosts['host'].str.contains('\*{3}\.novo\.dk')==True]

          host  timestamp
0  ***.novo.dk         16
</code>```

Or as OP pointed out to me ;-), just turn regex off regex=False

```<code>busiest_hosts[busiest_hosts['host'].str.contains('***.novo.dk', regex=False)==True]
</code>```

Body:
contains assumes the string is a regex expression and interprets the * as a command to repeat the prior character or expression.  You want to escape the *.  And while you're at it, escape the . as well.

busiest_hosts[busiest_hosts['host'].str.contains('\*{3}\.novo\.dk')==True]

demo

busiest_hosts = pd.DataFrame(dict(host=['***.novo.dk', '007.thegap.com'], timestamp=[16, 45]))

print(busiest_hosts)

             host  timestamp
0     ***.novo.dk         16
1  007.thegap.com         45

busiest_hosts[busiest_hosts['host'].str.contains('\*{3}\.novo\.dk')==True]

          host  timestamp
0  ***.novo.dk         16

Or as OP pointed out to me ;-), just turn regex off regex=False

busiest_hosts[busiest_hosts['host'].str.contains('***.novo.dk', regex=False)==True]


问:
Stripping single quotes from user input in seach bar
I have a simple PHP/MySQL psychiatric drug database website. Everything is working well, until the user puts a single quote anywhere into the search string. I get this error:

Fatal error: Uncaught Error: Call to a member function fetch() on boolean in /home/psychoph/public_html/connection.php:76 Stack trace: #0 /home/psychoph/public_html/index.php(70): include() #1 {main} thrown in /home/psychoph/public_html/connection.php on line 76

I tried this: $generic = $dbc->real_escape_string($generic); to no avail ($generic is the variable assigned to the user input)...I get this error:

Fatal error: Uncaught Error: Call to undefined method PDO::real_escape_string() in /home/psychoph/public_html/connection.php:12 Stack trace: #0 /home/psychoph/public_html/index.php(70): include() #1 {main} thrown in /home/psychoph/public_html/connection.php on line 12

Any guidance would be appreciated. I really just need to strip single quotes from the user input, but don't know how.

Here's the code for connection.php:

```<code><?php
$dbc = new PDO(
"mysql:host=173.236.101.74;dbname=psychoph_psychopharm",
'psychoph_knasky',
'#######');

try {
$results = $dbc->query("
    SELECT *
    FROM drugs
    WHERE generic = '$generic'
    OR brand = '$generic'
    "); // this method call returns the query results and places it into $results
} catch (Exception $e) {
echo "Unable to retrieve results";
    exit;
}

try {
$side_effects = $dbc->query("
    SELECT se.side_effect
    FROM side_effects AS se
    JOIN jnct_drug_side_effects AS jse ON se.id = jse.side_effect
    JOIN drugs AS d ON jse.drug = d.id
    WHERE generic = '$generic'
    OR brand = '$generic'
    ");
} catch (Exception $e) {
echo "Unable to retrieve results";
    exit;
}

try {
$indications = $dbc->query("
    SELECT i.indication
    FROM indications AS i
    JOIN jnct_drug_indications AS ji ON i.id = ji.indication
    JOIN drugs AS d ON ji.drug = d.id
    WHERE generic = '$generic'
    OR brand = '$generic'
    ");
} catch (Exception $e) {
echo "Unable to retrieve results";
    exit;
}

try {
$oi_indications = $dbc->query("
    SELECT oi.indication
    FROM ol_indications AS oi
    JOIN jnct_ol_drug_indications AS joi ON oi.id = joi.indication
    JOIN drugs AS d ON joi.drug = d.id
    WHERE generic = '$generic'
    OR brand = '$generic'
    ");
} catch (Exception $e) {
echo "Unable to retrieve results";
    exit;
}

$row = $results->fetch(PDO::FETCH_ASSOC);

$se_row = $side_effects->fetchAll(PDO::FETCH_COLUMN, 0);
$print_se = implode(", ", $se_row);

$ind_row = $indications->fetchAll(PDO::FETCH_COLUMN, 0);
$print_ind = implode(", ", $ind_row);

$oi_ind_row = $oi_indications->fetchAll(PDO::FETCH_COLUMN, 0);
$print_ol_ind = implode(", ", $oi_ind_row);
?>
</code>```

To clarify my question, I don't have any SQL injection concerns. This isn't a site that contains any data that needs protection (unless someone really wants to change the half-life of Zoloft on some random website for psychiatrists). I'm just trying to get this to work. I'm a physician trying to build a useful web tool, and don't like that a single quotation mark in my query returns an error message to the user. Is there a simple fix to this? I'm not a programmer - I'm trying to learn just enough to make this site work. Thanks, all!

答:
You could replace it?

http://php.net/manual/en/function.str-replace.php

You could replace with ''.  <~~  essentially a blank string variable

This link should help.

Regular Expression Sanitize (PHP)

Body:
I have a simple PHP/MySQL psychiatric drug database website. Everything is working well, until the user puts a single quote anywhere into the search string. I get this error:

Fatal error: Uncaught Error: Call to a member function fetch() on boolean in /home/psychoph/public_html/connection.php:76 Stack trace: #0 /home/psychoph/public_html/index.php(70): include() #1 {main} thrown in /home/psychoph/public_html/connection.php on line 76

I tried this: $generic = $dbc->real_escape_string($generic); to no avail ($generic is the variable assigned to the user input)...I get this error:

Fatal error: Uncaught Error: Call to undefined method PDO::real_escape_string() in /home/psychoph/public_html/connection.php:12 Stack trace: #0 /home/psychoph/public_html/index.php(70): include() #1 {main} thrown in /home/psychoph/public_html/connection.php on line 12

Any guidance would be appreciated. I really just need to strip single quotes from the user input, but don't know how.

Here's the code for connection.php:

<?php
$dbc = new PDO(
"mysql:host=173.236.101.74;dbname=psychoph_psychopharm",
'psychoph_knasky',
'#######');

try {
$results = $dbc->query("
    SELECT *
    FROM drugs
    WHERE generic = '$generic'
    OR brand = '$generic'
    "); // this method call returns the query results and places it into $results
} catch (Exception $e) {
echo "Unable to retrieve results";
    exit;
}

try {
$side_effects = $dbc->query("
    SELECT se.side_effect
    FROM side_effects AS se
    JOIN jnct_drug_side_effects AS jse ON se.id = jse.side_effect
    JOIN drugs AS d ON jse.drug = d.id
    WHERE generic = '$generic'
    OR brand = '$generic'
    ");
} catch (Exception $e) {
echo "Unable to retrieve results";
    exit;
}

try {
$indications = $dbc->query("
    SELECT i.indication
    FROM indications AS i
    JOIN jnct_drug_indications AS ji ON i.id = ji.indication
    JOIN drugs AS d ON ji.drug = d.id
    WHERE generic = '$generic'
    OR brand = '$generic'
    ");
} catch (Exception $e) {
echo "Unable to retrieve results";
    exit;
}

try {
$oi_indications = $dbc->query("
    SELECT oi.indication
    FROM ol_indications AS oi
    JOIN jnct_ol_drug_indications AS joi ON oi.id = joi.indication
    JOIN drugs AS d ON joi.drug = d.id
    WHERE generic = '$generic'
    OR brand = '$generic'
    ");
} catch (Exception $e) {
echo "Unable to retrieve results";
    exit;
}

$row = $results->fetch(PDO::FETCH_ASSOC);

$se_row = $side_effects->fetchAll(PDO::FETCH_COLUMN, 0);
$print_se = implode(", ", $se_row);

$ind_row = $indications->fetchAll(PDO::FETCH_COLUMN, 0);
$print_ind = implode(", ", $ind_row);

$oi_ind_row = $oi_indications->fetchAll(PDO::FETCH_COLUMN, 0);
$print_ol_ind = implode(", ", $oi_ind_row);
?>

To clarify my question, I don't have any SQL injection concerns. This isn't a site that contains any data that needs protection (unless someone really wants to change the half-life of Zoloft on some random website for psychiatrists). I'm just trying to get this to work. I'm a physician trying to build a useful web tool, and don't like that a single quotation mark in my query returns an error message to the user. Is there a simple fix to this? I'm not a programmer - I'm trying to learn just enough to make this site work. Thanks, all!


问:
zip command not working
I am trying to zip a file using shell script command. I am using following command:

```<code>  zip ./test/step1.zip $FILES
</code>```

where $FILES contain all the input files. But I am getting a warning as follows

```<code>    zip warning: name not matched: myfile.dat
</code>```

and one more thing I observed that the file which is at last in the list of files in a folder has the above warning and that file is not getting zipped.

Can anyone explain me why this is happening? I am new to shell script world.

答:
Another possible cause that can generate a zip warning: name not matched: error is having any of zip's environment variables set incorrectly.

From the man page:

```<code>ENVIRONMENT
    The following environment variables are read and used by zip as described.

ZIPOPT
    contains default options that will be used when running zip.  The contents of this environment variable will get added to the command line just after the zip command.

ZIP
    [Not on RISC OS and VMS] see ZIPOPT

Zip$Options
    [RISC OS] see ZIPOPT

Zip$Exts
    [RISC OS] contains extensions separated by a : that will cause native filenames with one of the specified extensions to be added to the zip file with basename and extension swapped.

ZIP_OPTS
    [VMS] see ZIPOPT
</code>```

In my case, I was using zip in a script and had the binary location in an environment variable ZIP so that we could change to a different zip binary easily without making tonnes of changes in the script.

Example:

```<code>ZIP=/usr/bin/zip
...
${ZIP} -r folder.zip folder
</code>```

This is then processed as:

```<code>/usr/bin/zip /usr/bin/zip -r folder.zip folder
</code>```

And generates the errors:

```<code>zip warning: name not matched: folder.zip
zip I/O error: Operation not permitted
zip error: Could not create output file (/usr/bin/zip.zip)
</code>```

The first because it's now trying to add folder.zip to the archive instead of using it as the archive. The second and third because it's trying to use the file /usr/bin/zip.zip as the archive which is (fortunately) not writable by a normal user.

Note: This is a really old question, but I didn't find this answer anywhere, so I'm posting it to help future searchers (my future self included).

Title: zip command not working

Body:
I am trying to zip a file using shell script command. I am using following command:

  zip ./test/step1.zip $FILES

where $FILES contain all the input files. But I am getting a warning as follows

    zip warning: name not matched: myfile.dat

and one more thing I observed that the file which is at last in the list of files in a folder has the above warning and that file is not getting zipped.

Can anyone explain me why this is happening? I am new to shell script world.

Body:
Another possible cause that can generate a zip warning: name not matched: error is having any of zip's environment variables set incorrectly.

From the man page:

ENVIRONMENT
    The following environment variables are read and used by zip as described.

ZIPOPT
    contains default options that will be used when running zip.  The contents of this environment variable will get added to the command line just after the zip command.

ZIP
    [Not on RISC OS and VMS] see ZIPOPT

Zip$Options
    [RISC OS] see ZIPOPT

Zip$Exts
    [RISC OS] contains extensions separated by a : that will cause native filenames with one of the specified extensions to be added to the zip file with basename and extension swapped.

ZIP_OPTS
    [VMS] see ZIPOPT

In my case, I was using zip in a script and had the binary location in an environment variable ZIP so that we could change to a different zip binary easily without making tonnes of changes in the script.

Example:

ZIP=/usr/bin/zip
...
${ZIP} -r folder.zip folder

This is then processed as:

/usr/bin/zip /usr/bin/zip -r folder.zip folder

And generates the errors:

zip warning: name not matched: folder.zip
zip I/O error: Operation not permitted
zip error: Could not create output file (/usr/bin/zip.zip)

The first because it's now trying to add folder.zip to the archive instead of using it as the archive. The second and third because it's trying to use the file /usr/bin/zip.zip as the archive which is (fortunately) not writable by a normal user.

Note: This is a really old question, but I didn't find this answer anywhere, so I'm posting it to help future searchers (my future self included).


问:
Where to create ExecutorServices and when to close them
I'm creating a REST service using Spring with Jersey and I have a use case where for every request I get, I need to make several calls (N) to an upstream API.

I get one request, it has n items, for each item, I create a thread to call my dependency (REST) and process the response. At the end I collect all the responses together, maintaining the order, and return them as a single response to the client.

I am using Java 8's CompletableFuture and wanted to know if I was using the ExecutorService framework correctly.

```<code>@Component // automatic singleton by Spring
class A {
    private ExecutorService executorService = Executors.newCachedThreadPool();

    private RawResponse getRawResponse(Item item) {
        // make REST call
    }

    private Response processResponse(RawResponse rawResponse) {
        // process response
    }

    public List<Response> handleRequest(Request request) {
        List<CompletableFuture> futureResponses = new ArrayList<>();

        for(Item item : request.getItems()) {
            CompletableFuture<Response> futureResponse = CompletableFuture.supplyAsync(() -> getRawResponse(item), executorService)
            .thenApply(rawResponse -> processResponse(rawResponse))
            .handle((response, throwable) {
            if(throwable != null) { // log and return default response
            } else { return response;}});

            futureResponses.add(futureResponse);
        }

        List<Response> result = new ArrayList<>();

        for (CompletableFuture<Resource> futureResponse : futureResponses) {
                    try {
                        result.add(futureResponse.get());
                    } catch (Exception e) {

                        // log error
                    }
        }
        return result;
    }
}
</code>```

The question I have now is, should I move the creation of the executorService right above:

```<code>List<CompletableFuture> futureResponses = new ArrayList<>();
</code>```

and call shutdown on it right above:

```<code>return result;
</code>```

because at this time, I am not really calling shutdown anywhere since the app will always run in it's docker container.

Is it costly to keep creating and discarding the pool, or is the current way going to leak memory? And I think calling the pool static as a private field var is redundant since the class is a spring bean anyways (singleton).

Any advice will be appreciated, also should I be using a cachedThreadPool? I am not sure how to approximate the number of threads I need.

答:
should I move the creation of the executorService right above?

No you don't, you have your ExecutorService the right place in your example code. Think it as a thread pool, you will not want to init a new thread pool and close it for each method call of handleRequest. Of course ExecutorService does more job than a thread pool, actually it'll manage a thread pool underneath, and provides life-circle management for async tasks.

I am not really calling shutdown anywhere since the app will always run in it's docker container.

In most of cases you init your ExecutorService when applications starts and shut it down when applications shuts down. So you can just leave it there, because it'll be closed when application exits, or you can add some kind of shutdown hooks if you need to do graceful shutdown.

Is it costly to keep creating and discarding the pool.

Kind of, we don't want to create and discard Thread very often, so we have thread pool, if you create/discard pool for each method call, what's the point to have a thread pool.

or is the current way going to leak memory?

No, as long as the task you submitted does not leak memory. The implementation of ExecutorService itself is good to use.

And I think calling the pool static as a private field var is redundant since the class is a spring bean anyways (singleton)

Yes, you're correct. You can also define ExecutorService as Spring Bean and inject it to service bean, if you want to do some customized init process.

should I be using a cachedThreadPool, I am not sure how to approximate the number of threads I need.

That's hard to say, you need to do some test to get the right number of threads for your application. But most of NIO or EventDriven framework has the twice number of available cores to be the number of threads by default.

Body:
I'm creating a REST service using Spring with Jersey and I have a use case where for every request I get, I need to make several calls (N) to an upstream API.

I get one request, it has n items, for each item, I create a thread to call my dependency (REST) and process the response. At the end I collect all the responses together, maintaining the order, and return them as a single response to the client.

I am using Java 8's CompletableFuture and wanted to know if I was using the ExecutorService framework correctly.

@Component // automatic singleton by Spring
class A {
    private ExecutorService executorService = Executors.newCachedThreadPool();

    private RawResponse getRawResponse(Item item) {
        // make REST call
    }

    private Response processResponse(RawResponse rawResponse) {
        // process response
    }

    public List<Response> handleRequest(Request request) {
        List<CompletableFuture> futureResponses = new ArrayList<>();

        for(Item item : request.getItems()) {
            CompletableFuture<Response> futureResponse = CompletableFuture.supplyAsync(() -> getRawResponse(item), executorService)
            .thenApply(rawResponse -> processResponse(rawResponse))
            .handle((response, throwable) {
            if(throwable != null) { // log and return default response
            } else { return response;}});

            futureResponses.add(futureResponse);
        }

        List<Response> result = new ArrayList<>();

        for (CompletableFuture<Resource> futureResponse : futureResponses) {
                    try {
                        result.add(futureResponse.get());
                    } catch (Exception e) {

                        // log error
                    }
        }
        return result;
    }
}

The question I have now is, should I move the creation of the executorService right above:

List<CompletableFuture> futureResponses = new ArrayList<>();

and call shutdown on it right above:

return result;

because at this time, I am not really calling shutdown anywhere since the app will always run in it's docker container.

Is it costly to keep creating and discarding the pool, or is the current way going to leak memory? And I think calling the pool static as a private field var is redundant since the class is a spring bean anyways (singleton).

Any advice will be appreciated, also should I be using a cachedThreadPool? I am not sure how to approximate the number of threads I need.


问:
Why is array co-variance considered so horrible?
In .NET reference type arrays are co-variant. This is considered a mistake. However, I don't see why this is so bad consider the following code:

```<code>string[] strings = new []{"Hey there"};
object[] objects = strings;
objects[0] = new object();
</code>```

Oh ho, this compiles and will fail at runtime. As we tried to stick an object into a string[]. Okay, I agree that stinks, but a T[] extends Array and also implements IList (and IList<T>, I wonder if it implements IList<BaseType>...>. Both Array and IList allow us to make the same horrid mistake.

```<code>string[] strings = new []{"Hey there"};
Array objects = strings;
objects.SetValue(new object(),new[]{0});
</code>```

IList version

```<code>string[] strings = new []{"Hey there"};
IList objects = strings;
objects[0] = new object();
</code>```

The T[] classes are generated by the CLR, and have to include a type check on the equivalent of the set_Item method (arrays don't actually have one).

Is the concern that setting to a T[] has to do the type check at runtime (which violates the type-safety you expect at compile time)? Why is it considered harmful for arrays to exhibit this property when there are equivalent means to shoot yourself in the foot through the provided means above?

答: One cost of array-variance is that assignments to an array of a non sealed reference type are a bit more expensive. But considering that assignments to reference types already do quite a bit related to the GC I guess that cost isn't significant.</p>

ContentLicense: CC BY-SA 2.5

Body:
In .NET reference type arrays are co-variant. This is considered a mistake. However, I don't see why this is so bad consider the following code:

string[] strings = new []{"Hey there"};
object[] objects = strings;
objects[0] = new object();

Oh ho, this compiles and will fail at runtime. As we tried to stick an object into a string[]. Okay, I agree that stinks, but a T[] extends Array and also implements IList (and IList<T>, I wonder if it implements IList<BaseType>...>. Both Array and IList allow us to make the same horrid mistake.

string[] strings = new []{"Hey there"};
Array objects = strings;
objects.SetValue(new object(),new[]{0});

IList version

string[] strings = new []{"Hey there"};
IList objects = strings;
objects[0] = new object();

The T[] classes are generated by the CLR, and have to include a type check on the equivalent of the set_Item method (arrays don't actually have one).

Is the concern that setting to a T[] has to do the type check at runtime (which violates the type-safety you expect at compile time)? Why is it considered harmful for arrays to exhibit this property when there are equivalent means to shoot yourself in the foot through the provided means above?


问:
Pass an array of strings into a function without having to specify N (compile time constant)
The following code runs:

```<code>fn last_el(arr: [&str; 2]) -> usize {
    arr.len() - 1
}

fn main() {
    let names = ["this", "that"];
    println!("{}", names[last_el(names)]);
}
</code>```

However it only does so with [&str; 2] and 2 has to match the number of elements in names. For example, the following code fails to compile:

```<code>fn last_el(arr: [&str]) -> usize {
    arr.len() - 1
}

fn main(){
    let names = ["this","that"];
    println!("{}", names[last_el(names)]);
}
</code>```

How would I write this so that I don't have to specify N?

I understand that arr.len() - 1 is probably less of a headache than trying to write a function that does the same thing, but as far as understanding how functions accept arrays with strings in them, why does the second example fail to compile?

答:
And to answer the question you asked:

Pass an array of strings into a function without having to specify N

You cannot:

How to define a function with a generic fixed-length array?

Is it possible to control the size of an array using the type parameter of a generic?

Body:
The following code runs:

fn last_el(arr: [&str; 2]) -> usize {
    arr.len() - 1
}

fn main() {
    let names = ["this", "that"];
    println!("{}", names[last_el(names)]);
}

However it only does so with [&str; 2] and 2 has to match the number of elements in names. For example, the following code fails to compile:

fn last_el(arr: [&str]) -> usize {
    arr.len() - 1
}

fn main(){
    let names = ["this","that"];
    println!("{}", names[last_el(names)]);
}

How would I write this so that I don't have to specify N?

I understand that arr.len() - 1 is probably less of a headache than trying to write a function that does the same thing, but as far as understanding how functions accept arrays with strings in them, why does the second example fail to compile?


问:
Eclipse file input through CLI for Algorithms 4th edition problems
I'm trying to execute the practice problems in Algorithms 4h edition.
I imported the algs4.jar libraries and added to my Build path. While exercising the practice problems, I'm trying to give the input file as a CLI through the "Run Configurations". I'm not able to read input through this approach. What am I missing here.

答:
You will need to put the "algs4-data" folder in your project root folder. In case you have your own input files, you may want to add them too, to your project root, unless you want give the full path in the arguments.

Here is what worked for me.


问:
Get fish shell to work with gcloud command line tools?
Has anyone had any luck getting fish shell to work with google's gcloud command line tools? I'm not an expert in Fish script but these are the two files gcloud needs to run (which work fine use Fish's bash mode). Fish doesn't allow you to source bash files from what I understand so these would need to be converted to Fish script?

path.bash

```<code>script_link="$( readlink "$BASH_SOURCE" )" || script_link="$BASH_SOURCE"
apparent_sdk_dir="${script_link%/*}"
if [ "$apparent_sdk_dir" == "$script_link" ]; then
  apparent_sdk_dir=.
fi
sdk_dir="$( command cd -P "$apparent_sdk_dir" && pwd -P )"
bin_path="$sdk_dir/bin"
export PATH=$bin_path:$PATH
</code>```

path.completion

```<code>_python_argcomplete() {
    local IFS=''
    COMPREPLY=( $(IFS="$IFS"                   COMP_LINE="$COMP_LINE"                   COMP_POINT="$COMP_POINT"                   _ARGCOMPLETE_COMP_WORDBREAKS="$COMP_WORDBREAKS"                   _ARGCOMPLETE=1                   "$1" 8>&1 9>&2 1>/dev/null 2>/dev/null) )
    if [[ $? != 0 ]]; then
        unset COMPREPLY
    fi
}
complete -o default -F _python_argcomplete "gcloud"

_completer() {
    command=$1
    name=$2
    eval '[[ "$'"${name}"'_COMMANDS" ]] || '"${name}"'_COMMANDS="$('"${command}"')"'
    set -- $COMP_LINE
    shift
    while [[ $1 == -* ]]; do
          shift
    done
    [[ $2 ]] && return
    grep -q "${name}\s*$" <<< $COMP_LINE &&
        eval 'COMPREPLY=($'"${name}"'_COMMANDS)' &&
        return
    [[ "$COMP_LINE" == *" " ]] && return
    [[ $1 ]] &&
        eval 'COMPREPLY=($(echo "$'"${name}"'_COMMANDS" | grep ^'"$1"'))'
}

unset bq_COMMANDS
_bq_completer() {
    _completer "CLOUDSDK_COMPONENT_MANAGER_DISABLE_UPDATE_CHECK=1 bq help | grep '^[^ ][^ ]*  ' | sed 's/ .*//'" bq
}

unset gsutil_COMMANDS
_gsutil_completer() {
    _completer "CLOUDSDK_COMPONENT_MANAGER_DISABLE_UPDATE_CHECK=1 gsutil help | sed /Additional/q | grep '^  ' | sed -e 's/^  //' -e 's/ .*//'" gsutil
}

unset gcutil_COMMANDS
_gcutil_completer() {
    _completer "CLOUDSDK_COMPONENT_MANAGER_DISABLE_UPDATE_CHECK=1 gcutil help | grep -v '^information' | grep '^[a-z]' | sed -e 's/ .*//' -e '/^$/d'" gcutil
}

complete -o default -F _bq_completer bq
complete -o default -F _gsutil_completer gsutil
complete -o default -F _gcutil_completer gcutil
</code>```

答:
Fish support is now included out of the box with gcloud, however I ran into a pretty annoying issue. The code included in google-cloud-sdk/path.fish.inc (and @nafg's answer) leaves the directory changed, resulting in each new shell session starting in the google-cloud-sdk directory.

The modification I made was fairly simple, adding two extra lines to get the current working directory and restore it afterwards. This seems to have resolved the issue for me, so hopefully will help anyone else googling for "fish gcloud" problems.

```<code>set restore_dir (pwd -P)
set sdk_dir (builtin cd "$apparent_sdk_dir" > /dev/null; and pwd -P)
set bin_path "$sdk_dir/bin"
cd "$restore_dir"
</code>```

Body:
Has anyone had any luck getting fish shell to work with google's gcloud command line tools? I'm not an expert in Fish script but these are the two files gcloud needs to run (which work fine use Fish's bash mode). Fish doesn't allow you to source bash files from what I understand so these would need to be converted to Fish script?

path.bash

script_link="$( readlink "$BASH_SOURCE" )" || script_link="$BASH_SOURCE"
apparent_sdk_dir="${script_link%/*}"
if [ "$apparent_sdk_dir" == "$script_link" ]; then
  apparent_sdk_dir=.
fi
sdk_dir="$( command cd -P "$apparent_sdk_dir" && pwd -P )"
bin_path="$sdk_dir/bin"
export PATH=$bin_path:$PATH

path.completion

_python_argcomplete() {
    local IFS=''
    COMPREPLY=( $(IFS="$IFS"                   COMP_LINE="$COMP_LINE"                   COMP_POINT="$COMP_POINT"                   _ARGCOMPLETE_COMP_WORDBREAKS="$COMP_WORDBREAKS"                   _ARGCOMPLETE=1                   "$1" 8>&1 9>&2 1>/dev/null 2>/dev/null) )
    if [[ $? != 0 ]]; then
        unset COMPREPLY
    fi
}
complete -o default -F _python_argcomplete "gcloud"

_completer() {
    command=$1
    name=$2
    eval '[[ "$'"${name}"'_COMMANDS" ]] || '"${name}"'_COMMANDS="$('"${command}"')"'
    set -- $COMP_LINE
    shift
    while [[ $1 == -* ]]; do
          shift
    done
    [[ $2 ]] && return
    grep -q "${name}\s*$" <<< $COMP_LINE &&
        eval 'COMPREPLY=($'"${name}"'_COMMANDS)' &&
        return
    [[ "$COMP_LINE" == *" " ]] && return
    [[ $1 ]] &&
        eval 'COMPREPLY=($(echo "$'"${name}"'_COMMANDS" | grep ^'"$1"'))'
}

unset bq_COMMANDS
_bq_completer() {
    _completer "CLOUDSDK_COMPONENT_MANAGER_DISABLE_UPDATE_CHECK=1 bq help | grep '^[^ ][^ ]*  ' | sed 's/ .*//'" bq
}

unset gsutil_COMMANDS
_gsutil_completer() {
    _completer "CLOUDSDK_COMPONENT_MANAGER_DISABLE_UPDATE_CHECK=1 gsutil help | sed /Additional/q | grep '^  ' | sed -e 's/^  //' -e 's/ .*//'" gsutil
}

unset gcutil_COMMANDS
_gcutil_completer() {
    _completer "CLOUDSDK_COMPONENT_MANAGER_DISABLE_UPDATE_CHECK=1 gcutil help | grep -v '^information' | grep '^[a-z]' | sed -e 's/ .*//' -e '/^$/d'" gcutil
}

complete -o default -F _bq_completer bq
complete -o default -F _gsutil_completer gsutil
complete -o default -F _gcutil_completer gcutil

Body:
Fish support is now included out of the box with gcloud, however I ran into a pretty annoying issue. The code included in google-cloud-sdk/path.fish.inc (and @nafg's answer) leaves the directory changed, resulting in each new shell session starting in the google-cloud-sdk directory.

The modification I made was fairly simple, adding two extra lines to get the current working directory and restore it afterwards. This seems to have resolved the issue for me, so hopefully will help anyone else googling for "fish gcloud" problems.

set restore_dir (pwd -P)
set sdk_dir (builtin cd "$apparent_sdk_dir" > /dev/null; and pwd -P)
set bin_path "$sdk_dir/bin"
cd "$restore_dir"


问:
Javascript click event triggers twice
In the following snippet, why does divClicked() trigger twice when the  is clicked, but only once when <input> is clicked?

function divClicked(_index) {
  console.log("div click event");
}

function inputClicked(_index) {
  console.log("input click event");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="option" onclick="divClicked(1)">
  <input id="1_1" name="group_1" type="radio" value="1" onclick="inputClicked(1)" />
  <label for="1_1">label</label>
</div></code>```

Note: I want to know why this happens, not a "quick fix" like: put onclick() on label.

答:
This is usually be cause of the bubbling principle of click event:

When an event happens on an element, it runs on it, its associated elements,its parent and other ancestors.

Now, The relation is when you click on label there a are two events which bubbles up here:

1) Click on div (which you expect)

2) Click on input (which is also expected)

2.1) When click on input is triggered then a click on div is also triggered again here

You can confirm this behavior by using event.bubbles prop.

EDIT:

The reason for the connection between label and input: (I know this is absolutely not required, as it's present all over the place yet)

A  can be associated with a control either by placing the control element inside the  element, or by using the for attribute. Such a control is called the labeled control of the label element. One input can be associated with multiple labels.

Taken from: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label

Which means placing for on label referencing id of an input element will stimulate the behavior as if the element is inside the label. This would bubble a event on input onto label like any event on child to parent

Title: Javascript click event triggers twice

Body:
In the following snippet, why does divClicked() trigger twice when the  is clicked, but only once when <input> is clicked?

function divClicked(_index) {
  console.log("div click event");
}

function inputClicked(_index) {
  console.log("input click event");
}

  <input id="1_1" name="group_1" type="radio" value="1" onclick="inputClicked(1)" />
  label

Note: I want to know why this happens, not a "quick fix" like: put onclick() on label.

Body:
This is usually be cause of the bubbling principle of click event:

When an event happens on an element, it runs on it, its associated elements,its parent and other ancestors.

Now, The relation is when you click on label there a are two events which bubbles up here:

1) Click on div (which you expect)

2) Click on input (which is also expected)

2.1) When click on input is triggered then a click on div is also triggered again here

You can confirm this behavior by using event.bubbles prop.

EDIT:

The reason for the connection between label and input: (I know this is absolutely not required, as it's present all over the place yet)

A <label> can be associated with a control either by placing the control element inside the <label> element, or by using the for attribute. Such a control is called the labeled control of the label element. One input can be associated with multiple labels.

Taken from: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label

Which means placing for on label referencing id of an input element will stimulate the behavior as if the element is inside the label. This would bubble a event on input onto label like any event on child to parent


问:
Alexa skill not sending the correct intent
I have the following settings for an Alexa skill that I'm writing:

Intent Schema

```<code>{
  "intents": [
    {
      "intent": "AddToGroceriesIntent",
      "slots": [
        {
          "name": "GroceriesItems",
          "type": "GROCERIES_ITEMS"
        }
      ]
    },
    {
      "intent": "GetGroceriesIntent"
    },
    {
      "intent": "ClearGroceriesIntent"
    },
    {
      "intent": "AMAZON.HelpIntent"
    },
    {
      "intent": "AMAZON.StopIntent"
    },
    {
      "intent": "AMAZON.CancelIntent"
    }
  ]
}
</code>```

Sample Utterances

```<code>AddToGroceriesIntent to add {GroceriesItems}
AddToGroceriesIntent to add {GroceriesItems} to shopping list
AddToGroceriesIntent to add {GroceriesItems} to the shopping list
AddToGroceriesIntent to add {GroceriesItems} to the list
GetGroceriesIntent list
GetGroceriesIntent shopping list
GetGroceriesIntent for the shopping list
GetGroceriesIntent for the list
GetGroceriesIntent what's on my shopping list
GetGroceriesIntent what's on the shopping list
GetGroceriesIntent what's on the list
GetGroceriesIntent what's on my list
GetGroceriesIntent what is on my shopping list
GetGroceriesIntent what is on the shopping list
GetGroceriesIntent what is on the list
GetGroceriesIntent what is on my list
ClearGroceriesIntent to clear my shopping list
ClearGroceriesIntent to clear my list
ClearGroceriesIntent to clear the shopping list
ClearGroceriesIntent to clear the list
ClearGroceriesIntent to empty my shopping list
ClearGroceriesIntent to empty my list
ClearGroceriesIntent to empty the shopping list
ClearGroceriesIntent to empty the list
ClearGroceriesIntent to delete my shopping list
ClearGroceriesIntent to delete my list
ClearGroceriesIntent to delete the shopping list
ClearGroceriesIntent to delete the list
</code>```

When Alexa hears:

alexa ask my app to clear my shopping list

As expected, the correct ClearGroceriesIntent is sent. However, when Alexa hears:

alexa ask my app to clear the shopping list

The GetGroceriesIntent is sent instead.

This issue can't be replicated by the Service Simulator - it works fine then. It's only during speech that it gets muddled up, even though (according to the history) Alexa heard the exact same thing as what I type into the test form.

(All of the AddToGroceriesIntent and GetGroceriesIntent utterances work as expected)

答: One suggestion that might help is to change your sample utterances to remove the connecting words - in your case 'to' and 'for' shouldn't be in the sample utterances, reference these docs under 'Invoking a Skill with a Specific Request (Intent)'. I'm not sure if that will fix the problem but good to do anyway. If the problem persists, you may have a situation that maps to this discussion about how the NLP always returns one of your intents - even if it doesn't understand, it just picks one. Maybe it is routinely picking GetGroceriesIntent when it doesn't understand. </p>

Body:
I have the following settings for an Alexa skill that I'm writing:

Intent Schema

{
  "intents": [
    {
      "intent": "AddToGroceriesIntent",
      "slots": [
        {
          "name": "GroceriesItems",
          "type": "GROCERIES_ITEMS"
        }
      ]
    },
    {
      "intent": "GetGroceriesIntent"
    },
    {
      "intent": "ClearGroceriesIntent"
    },
    {
      "intent": "AMAZON.HelpIntent"
    },
    {
      "intent": "AMAZON.StopIntent"
    },
    {
      "intent": "AMAZON.CancelIntent"
    }
  ]
}

Sample Utterances

AddToGroceriesIntent to add {GroceriesItems}
AddToGroceriesIntent to add {GroceriesItems} to shopping list
AddToGroceriesIntent to add {GroceriesItems} to the shopping list
AddToGroceriesIntent to add {GroceriesItems} to the list
GetGroceriesIntent list
GetGroceriesIntent shopping list
GetGroceriesIntent for the shopping list
GetGroceriesIntent for the list
GetGroceriesIntent what's on my shopping list
GetGroceriesIntent what's on the shopping list
GetGroceriesIntent what's on the list
GetGroceriesIntent what's on my list
GetGroceriesIntent what is on my shopping list
GetGroceriesIntent what is on the shopping list
GetGroceriesIntent what is on the list
GetGroceriesIntent what is on my list
ClearGroceriesIntent to clear my shopping list
ClearGroceriesIntent to clear my list
ClearGroceriesIntent to clear the shopping list
ClearGroceriesIntent to clear the list
ClearGroceriesIntent to empty my shopping list
ClearGroceriesIntent to empty my list
ClearGroceriesIntent to empty the shopping list
ClearGroceriesIntent to empty the list
ClearGroceriesIntent to delete my shopping list
ClearGroceriesIntent to delete my list
ClearGroceriesIntent to delete the shopping list
ClearGroceriesIntent to delete the list

When Alexa hears:

alexa ask my app to clear my shopping list

As expected, the correct ClearGroceriesIntent is sent. However, when Alexa hears:

alexa ask my app to clear the shopping list

The GetGroceriesIntent is sent instead.

This issue can't be replicated by the Service Simulator - it works fine then. It's only during speech that it gets muddled up, even though (according to the history) Alexa heard the exact same thing as what I type into the test form.

(All of the AddToGroceriesIntent and GetGroceriesIntent utterances work as expected)


问:
Firebase storage with Ionic 2 SocialSharing plugin
My images are stored in firebase storage. I have noticed that if I store the image in a folder, I am no longer able to use it with the SocialSharing plugin from ionic native.

Anyone has found any workaround on this?

```<code>whatsappShare() {

        let image = "https://firebasestorage.googleapis.com/v0/b/instagram-test-fe4a8.appspot.com/o/000.jpg?alt=media&token=64dd92cd-27c2-4c36-9c1d-2ab376ffd16c"  //This is working
        //let image = "https://firebasestorage.googleapis.com/v0/b/instagram-test-fe4a8.appspot.com/o/test%2F000.jpg?alt=media&token=2bc49648-cf1c-41fe-8e1f-071d54f56402"  //This is failing because stored in test/ folder

        //shareViaWhatsApp(message, image, url)
        SocialSharing.shareViaWhatsApp("Checkout this picture!", image, "lycos.com/")
            .then( () => {
                    alert("WhatsApp Success");
                }, () => {
                    alert("WhatsApp failed")
                })
    }
</code>```

I have found this github which seems related
https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin/issues/696

It means the plugin can work in iOS and fail in android?
Any possible solution to this?

答:
Yes. Finally I got a way to share images from Firebase Storage to any service. Just follow these two conditions:

Convert the image from the uri to a base64 string. You can find plenti of examples of that conversion out there.

Send the image data using shareWithOptions(). Other methods seem not to work with image data encoded that way.

I'm interested in any other updates regarding this issue. Hope that helps anyone.

Body:
My images are stored in firebase storage. I have noticed that if I store the image in a folder, I am no longer able to use it with the SocialSharing plugin from ionic native.

Anyone has found any workaround on this?

whatsappShare() {

        let image = "https://firebasestorage.googleapis.com/v0/b/instagram-test-fe4a8.appspot.com/o/000.jpg?alt=media&token=64dd92cd-27c2-4c36-9c1d-2ab376ffd16c"  //This is working
        //let image = "https://firebasestorage.googleapis.com/v0/b/instagram-test-fe4a8.appspot.com/o/test%2F000.jpg?alt=media&token=2bc49648-cf1c-41fe-8e1f-071d54f56402"  //This is failing because stored in test/ folder

        //shareViaWhatsApp(message, image, url)
        SocialSharing.shareViaWhatsApp("Checkout this picture!", image, "lycos.com/")
            .then( () => {
                    alert("WhatsApp Success");
                }, () => {
                    alert("WhatsApp failed")
                })
    }

I have found this github which seems related
https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin/issues/696

It means the plugin can work in iOS and fail in android?
Any possible solution to this?


问:
UIPickerView inside an action sheet is not responsive from bottom half
I created a UIPickerView inside an UIActionSheet, using the following tutorial:
Add UIPickerView & a Button in Action sheet - How?

I've noticed that the UIPickerView does not respond to touches below the bottom half of the UIPicker.  Perhaps just below the selection bar, but not any more below.

Has anyone had any similar experiences and resolved them?

答:
I had a similar problem recently where I was presenting 3 options and a cancel.  The lower 3 buttons seemed about half a button out of alignment.  I had to click inbetween the buttons to get them to operate.  It all depended on where I was presenting the action sheet from.  If you have a TabBarController you should present the action sheet from there:

```<code>[actionSheet showInView:self.parentViewController.tabBarController.view];
</code>```

If you just have the view itself, with perhaps a navbar then presenting it from the view is fine:

```<code>[actionSheet showInView:self.view];
</code>```

In my case I had a tab bar for the iphone and not for the ipad version so I did this:

```<code>if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
    [actionSheet showInView:self.view];
} else {
    [actionSheet showInView:self.parentViewController.tabBarController.view];
}
</code>```

It's not clear from the UIActionSheet reference documentation but it might be wise to present the action sheet from the 'front' most controller that is sensible.  So if there is a toolbar at the bottom present it from that.  These restrictions do not appear to apply to the iPad as action sheets are presented inside popovers.

Hope that helps.

Body:
I had a similar problem recently where I was presenting 3 options and a cancel.  The lower 3 buttons seemed about half a button out of alignment.  I had to click inbetween the buttons to get them to operate.  It all depended on where I was presenting the action sheet from.  If you have a TabBarController you should present the action sheet from there:

[actionSheet showInView:self.parentViewController.tabBarController.view];

If you just have the view itself, with perhaps a navbar then presenting it from the view is fine:

[actionSheet showInView:self.view];

In my case I had a tab bar for the iphone and not for the ipad version so I did this:

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
    [actionSheet showInView:self.view];
} else {
    [actionSheet showInView:self.parentViewController.tabBarController.view];
}

It's not clear from the UIActionSheet reference documentation but it might be wise to present the action sheet from the 'front' most controller that is sensible.  So if there is a toolbar at the bottom present it from that.  These restrictions do not appear to apply to the iPad as action sheets are presented inside popovers.

Hope that helps.


问:
Logging into website programmatically returns HTML of login

I have the following Java program which is supposed to login to my Student website programmatically and return the HTML of the Gradebook. However, when I run it, I am returned with the HTML of the actual login site:

```<code>public class Scraper {

static String formData = "j_username=[username here]&j_password=[password here]";
static String link = "https://parents.mtsd.k12.nj.us/genesis/parents?tab1=studentdata&tab2=gradebook&tab3=weeklysummary&studentid=100916&action=form";

public static void main (String[] args){

   String display = postData(link,formData);
   System.out.print(display);

}

public static String postData (String url, String data){

    URL link = null;
    HttpURLConnection connection = null;
    StringBuffer stringBuffer = new StringBuffer();
    DataOutputStream dataOutputStream = null;
    String document = null;

    try {
        link = new URL(url);
    }catch (Exception e){System.out.print(e);}

    try {
        connection = (HttpURLConnection) link.openConnection();
    }catch (Exception e){System.out.print(e);}

    connection.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
    connection.setRequestProperty("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
    connection.setRequestProperty("Accept-Encoding","gzip, deflate, br");
    connection.setRequestProperty("Accept-Language","en-US,en;q=0.8");
    connection.setRequestProperty("Cookie","");
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setInstanceFollowRedirects(true);

    //setCookie(connection);

    //post data
    String postString = data;
    stringBuffer.append(postString);

    try {
        connection.connect();
    }catch (Exception e){System.out.print(e);}

    try {
        dataOutputStream = new DataOutputStream(connection.getOutputStream());
    }catch (Exception e){System.out.print(e);}

    try {
        IOUtils.write(stringBuffer.toString(),dataOutputStream,"UTF-8");
    }catch (Exception e){System.out.print(e);}

    //handle redirects
    try {
        if(connection.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP || connection.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM || connection.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER){
            String redirectURL = connection.getHeaderField("Location");
            String cookie = connection.getHeaderField("Set-Cookie");

            URL redURL = null;

            try {
                redURL = new URL(redirectURL);
            }catch (Exception e){System.out.print(e);}

            connection = (HttpURLConnection)redURL.openConnection();
            connection.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            connection.setRequestProperty("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
            connection.setRequestProperty("Accept-Encoding","gzip, deflate, br");
            connection.setRequestProperty("Accept-Language","en-US,en;q=0.8");
            connection.setRequestProperty("Cookie",cookie);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setInstanceFollowRedirects(true);

        }
    }catch (Exception e){System.out.print(e);}

    InputStream inputStream = null;

    try {

        inputStream = connection.getInputStream();

        document = IOUtils.toString(inputStream,"UTF-8");

    } catch (Exception e){System.out.print(e);}

    return document;
}

public static void setCookie(HttpURLConnection httpURLConnection){

}

}
</code>```

I originally tried sending the initial POST request to the request URL shown in the network tab of inspect element (https://parents.mtsd.k12.nj.us/genesis/j_security_check), however, this returns an error and no HTML data. Any help is appreciated as I this is the first time I am attempting something of this nature.

Update: After experimenting with the login process, I noticed that the cookie I obtain contains only something along the lines of "lastvisit=95FD925038EF488AA22719B64FB5C4A3" but is missing the "JSESSION_ID". I am unsure as to whether this is causing the problem or not.

Update #2 I edited my code to comply with the suggestions offered, however, I still get the HTML of the login page rather than the grade data page. Also, I add print statements to display the cookie I obtained and I noticed that the "JsessionID" cookie is missing and instead I only get the "lastvisited" cookie.

```<code>public class Scraper {

static String formData = "user&pass";
static String link = "https://parents.mtsd.k12.nj.us/genesis/parents?tab1=studentdata&tab2=gradebook&tab3=weeklysummary&studentid=100916&action=form";

public static void main (String[] args){

   String display = postData(link,formData);
   System.out.print(display);

}

public static String postData (String url, String data){

    URL link = null;
    HttpURLConnection connection = null;
    StringBuffer stringBuffer = new StringBuffer();
    DataOutputStream dataOutputStream = null;
    String document = null;

    try {
        link = new URL(url);
    }catch (Exception e){System.out.print(e);}

    try {
        connection = (HttpURLConnection) link.openConnection();
        connection.setRequestMethod("GET");
    }catch (Exception e){System.out.print(e);}

    connection.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
    connection.setRequestProperty("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
    connection.setRequestProperty("Accept-Encoding","gzip, deflate, br");
    connection.setRequestProperty("Accept-Language","en-US,en;q=0.8");
    connection.setRequestProperty("Cookie","");
    connection.setDoInput(true);
    connection.setDoOutput(true);
    //connection.setInstanceFollowRedirects(true);

    //setCookie(connection);

    String cookie = connection.getHeaderField("Set-Cookie"); //get cookies for session

    //try {
    //    connection.connect();
    //}catch (Exception e){System.out.print(e);}

    //try {
    //    dataOutputStream = new DataOutputStream(connection.getOutputStream());
    //}catch (Exception e){System.out.print(e);}

    //try {
    //    IOUtils.write(stringBuffer.toString(),dataOutputStream,"UTF-8");
    //}catch (Exception e){System.out.print(e);}

    //handle redirects
    try {

            //post data
            String postString = data;
            stringBuffer.append(postString);

            URL redURL = null;

            try {
                redURL = new URL("https://parents.mtsd.k12.nj.us/genesis/j_security_check");
            }catch (Exception e){System.out.print(e);}

            connection = (HttpURLConnection)redURL.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            connection.setRequestProperty("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
            connection.setRequestProperty("Accept-Encoding","gzip, deflate, br");
            connection.setRequestProperty("Accept-Language","en-US,en;q=0.8");
            connection.setRequestProperty("Cookie",cookie);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setInstanceFollowRedirects(true);

            //connection.connect();

    }catch (Exception e){System.out.print(e);}

    InputStream inputStream = null;

    String cookie2 = null;

    try {
            dataOutputStream = new DataOutputStream(connection.getOutputStream());
        }catch (Exception e){System.out.print(e);}

        try {
            IOUtils.write(stringBuffer.toString(),dataOutputStream,"UTF-8");

            System.out.println(stringBuffer.toString());

            cookie2 = connection.getHeaderField("Set-Cookie"); //get cookies for session

        }catch (Exception e){System.out.print(e);}

    URL fLink = null;

    try {
        fLink = new URL("https://parents.mtsd.k12.nj.us/genesis/parents?tab1=studentdata&tab2=gradebook&tab3=weeklysummary&studentid=100916&action=form" + stringBuffer.toString());
    }catch (Exception e){System.out.print(e);}

    HttpURLConnection conn = null;

    try {
         conn = (HttpURLConnection) fLink.openConnection();
        conn.setRequestMethod("GET");
    }catch (Exception e){System.out.print(e);}

    conn.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
    conn.setRequestProperty("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
    conn.setRequestProperty("Accept-Encoding","gzip, deflate, br");
    conn.setRequestProperty("Accept-Language","en-US,en;q=0.8");
    conn.setRequestProperty("Cookie",cookie);
    conn.setDoInput(true);
    conn.setDoOutput(true);

        try {

            conn.connect();
            inputStream = conn.getInputStream();

        document = IOUtils.toString(inputStream,"UTF-8");

    } catch (Exception e){System.out.print(e);}

    System.out.println("cookie -- " + cookie);
    System.out.println("cookie2 -- " + cookie2);

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

The output for my cookie print statements is as follows (for experimental purposes)

```<code>cookie -- lastvisit=A1753DA7F2454A03B58DF8CBD39C22C4; Expires=Tue,   27-Mar-2018 18:27:55 GMT
cookie2 -- null
</code>```

答:
This site is using Java Servlet authentication mechanism. When you try to get any page that is password protected the server internally issues a forward that returns the login page content. After you post a valid username/password it forwards you to the requested URL.

Note that this is not a redirect, it is managed internally by the application server and the client does not see what is going on at the server side.

To get this to work you need to issue a GET to the page you are trying to retrieve. The server responds with the login page content and the session id as a cookie. You have to save the session id and send it when you post to the form action.

Since I don't have valid credentials to test I cannot guarantee that this will work. With invalid credentials, the server will issue a number of redirects which will eventually change the session, probably because it is invalidated and recreated.

Please try this with valid credentials and let me know if it works. If there are redirects on successful login maybe it will be necessary to disable automatic redirects and do them programmatically, checking for session id changes. Depending on the application server, it may change the session id for security purposes.

That said, this MAY work when you post valid credentials.

```<code>import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

public class Scraper {

    private static final String USERNAME = "user@test.com";
    private static final String PASSWORD = "secret";
    private static final String GET_URL  = "https://parents.mtsd.k12.nj.us/genesis/parents?tab1=studentdata&tab2=gradebook&tab3=weeklysummary&studentid=100916&action=form";
    private static final String POST_URL = "https://parents.mtsd.k12.nj.us/genesis/j_security_check";

    public static void main(String[] args) {
        String cookies = doGet(GET_URL);
        doPost(POST_URL, cookies);
    };

    /**
     * Send the initial GET request which will forward to the login page
     * and retrieve cookies sent by the server.
     * Cookies are formatted according to HTTP specification so they can be
     * passed to the next request Cookie header.
     * @param getURL URL to get
     */
    public static String doGet(String getURL) {
        StringBuilder formattedCookies = new StringBuilder();
        try {
            URL url = new URL(getURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            InputStream is = conn.getInputStream();
            Map<String, List<String>> headers = conn.getHeaderFields();
            List<String> cookies = headers.get("Set-Cookie");
            ListIterator<String> it = cookies.listIterator();
            while (it.hasNext()) {
                String[] parts = it.next().split("; ");
                formattedCookies.append(parts[0]);
                if (it.hasNext()) {
                    formattedCookies.append("; ");
                }
            }
            System.out.println("\n\nGET OUTPUT");
            printContent(is);
        } catch (Exception e) {
            System.out.println(e.getLocalizedMessage());
        }
        return formattedCookies.toString();
    }

    /**
     * Post the form parameters and get page content.
     * @param postURL URL to post to
     * @param cookies The cookies to send
     */
    public static void doPost(String postURL, String cookies) {
        try {
            String postData = String.format("j_username=%s&j_password=%s",
                URLEncoder.encode(USERNAME, "UTF-8"), PASSWORD);
            URL url = new URL(postURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setInstanceFollowRedirects(true);
            conn.setRequestProperty("Cookie", cookies);
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
            out.write(postData);
            out.close();
            InputStream is = conn.getInputStream();
            System.out.println("\n\nPOST OUTPUT");
            printContent(is);
        } catch (Exception e) {
            System.out.println(e.getLocalizedMessage());
        }
    }

    public static void printContent(InputStream is) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
    }

}
</code>```

Body:
I have the following Java program which is supposed to login to my Student website programmatically and return the HTML of the Gradebook. However, when I run it, I am returned with the HTML of the actual login site:

public class Scraper {

static String formData = "j_username=[username here]&j_password=[password here]";
static String link = "https://parents.mtsd.k12.nj.us/genesis/parents?tab1=studentdata&tab2=gradebook&tab3=weeklysummary&studentid=100916&action=form";

public static void main (String[] args){

   String display = postData(link,formData);
   System.out.print(display);

}

public static String postData (String url, String data){

    URL link = null;
    HttpURLConnection connection = null;
    StringBuffer stringBuffer = new StringBuffer();
    DataOutputStream dataOutputStream = null;
    String document = null;

    try {
        link = new URL(url);
    }catch (Exception e){System.out.print(e);}

    try {
        connection = (HttpURLConnection) link.openConnection();
    }catch (Exception e){System.out.print(e);}

    connection.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
    connection.setRequestProperty("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
    connection.setRequestProperty("Accept-Encoding","gzip, deflate, br");
    connection.setRequestProperty("Accept-Language","en-US,en;q=0.8");
    connection.setRequestProperty("Cookie","");
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setInstanceFollowRedirects(true);

    //setCookie(connection);

    //post data
    String postString = data;
    stringBuffer.append(postString);

    try {
        connection.connect();
    }catch (Exception e){System.out.print(e);}

    try {
        dataOutputStream = new DataOutputStream(connection.getOutputStream());
    }catch (Exception e){System.out.print(e);}

    try {
        IOUtils.write(stringBuffer.toString(),dataOutputStream,"UTF-8");
    }catch (Exception e){System.out.print(e);}

    //handle redirects
    try {
        if(connection.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP || connection.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM || connection.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER){
            String redirectURL = connection.getHeaderField("Location");
            String cookie = connection.getHeaderField("Set-Cookie");

            URL redURL = null;

            try {
                redURL = new URL(redirectURL);
            }catch (Exception e){System.out.print(e);}

            connection = (HttpURLConnection)redURL.openConnection();
            connection.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            connection.setRequestProperty("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
            connection.setRequestProperty("Accept-Encoding","gzip, deflate, br");
            connection.setRequestProperty("Accept-Language","en-US,en;q=0.8");
            connection.setRequestProperty("Cookie",cookie);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setInstanceFollowRedirects(true);

        }
    }catch (Exception e){System.out.print(e);}

    InputStream inputStream = null;

    try {

        inputStream = connection.getInputStream();

        document = IOUtils.toString(inputStream,"UTF-8");

    } catch (Exception e){System.out.print(e);}

    return document;
}

public static void setCookie(HttpURLConnection httpURLConnection){

}

}

I originally tried sending the initial POST request to the request URL shown in the network tab of inspect element (https://parents.mtsd.k12.nj.us/genesis/j_security_check), however, this returns an error and no HTML data. Any help is appreciated as I this is the first time I am attempting something of this nature.

Update: After experimenting with the login process, I noticed that the cookie I obtain contains only something along the lines of "lastvisit=95FD925038EF488AA22719B64FB5C4A3" but is missing the "JSESSION_ID". I am unsure as to whether this is causing the problem or not.

Update #2 I edited my code to comply with the suggestions offered, however, I still get the HTML of the login page rather than the grade data page. Also, I add print statements to display the cookie I obtained and I noticed that the "JsessionID" cookie is missing and instead I only get the "lastvisited" cookie.

public class Scraper {

static String formData = "user&pass";
static String link = "https://parents.mtsd.k12.nj.us/genesis/parents?tab1=studentdata&tab2=gradebook&tab3=weeklysummary&studentid=100916&action=form";

public static void main (String[] args){

   String display = postData(link,formData);
   System.out.print(display);

}

public static String postData (String url, String data){

    URL link = null;
    HttpURLConnection connection = null;
    StringBuffer stringBuffer = new StringBuffer();
    DataOutputStream dataOutputStream = null;
    String document = null;

    try {
        link = new URL(url);
    }catch (Exception e){System.out.print(e);}

    try {
        connection = (HttpURLConnection) link.openConnection();
        connection.setRequestMethod("GET");
    }catch (Exception e){System.out.print(e);}

    connection.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
    connection.setRequestProperty("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
    connection.setRequestProperty("Accept-Encoding","gzip, deflate, br");
    connection.setRequestProperty("Accept-Language","en-US,en;q=0.8");
    connection.setRequestProperty("Cookie","");
    connection.setDoInput(true);
    connection.setDoOutput(true);
    //connection.setInstanceFollowRedirects(true);

    //setCookie(connection);

    String cookie = connection.getHeaderField("Set-Cookie"); //get cookies for session

    //try {
    //    connection.connect();
    //}catch (Exception e){System.out.print(e);}

    //try {
    //    dataOutputStream = new DataOutputStream(connection.getOutputStream());
    //}catch (Exception e){System.out.print(e);}

    //try {
    //    IOUtils.write(stringBuffer.toString(),dataOutputStream,"UTF-8");
    //}catch (Exception e){System.out.print(e);}

    //handle redirects
    try {

            //post data
            String postString = data;
            stringBuffer.append(postString);

            URL redURL = null;

            try {
                redURL = new URL("https://parents.mtsd.k12.nj.us/genesis/j_security_check");
            }catch (Exception e){System.out.print(e);}

            connection = (HttpURLConnection)redURL.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            connection.setRequestProperty("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
            connection.setRequestProperty("Accept-Encoding","gzip, deflate, br");
            connection.setRequestProperty("Accept-Language","en-US,en;q=0.8");
            connection.setRequestProperty("Cookie",cookie);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setInstanceFollowRedirects(true);

            //connection.connect();

    }catch (Exception e){System.out.print(e);}

    InputStream inputStream = null;

    String cookie2 = null;

    try {
            dataOutputStream = new DataOutputStream(connection.getOutputStream());
        }catch (Exception e){System.out.print(e);}

        try {
            IOUtils.write(stringBuffer.toString(),dataOutputStream,"UTF-8");

            System.out.println(stringBuffer.toString());

            cookie2 = connection.getHeaderField("Set-Cookie"); //get cookies for session

        }catch (Exception e){System.out.print(e);}

    URL fLink = null;

    try {
        fLink = new URL("https://parents.mtsd.k12.nj.us/genesis/parents?tab1=studentdata&tab2=gradebook&tab3=weeklysummary&studentid=100916&action=form" + stringBuffer.toString());
    }catch (Exception e){System.out.print(e);}

    HttpURLConnection conn = null;

    try {
         conn = (HttpURLConnection) fLink.openConnection();
        conn.setRequestMethod("GET");
    }catch (Exception e){System.out.print(e);}

    conn.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
    conn.setRequestProperty("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
    conn.setRequestProperty("Accept-Encoding","gzip, deflate, br");
    conn.setRequestProperty("Accept-Language","en-US,en;q=0.8");
    conn.setRequestProperty("Cookie",cookie);
    conn.setDoInput(true);
    conn.setDoOutput(true);

        try {

            conn.connect();
            inputStream = conn.getInputStream();

        document = IOUtils.toString(inputStream,"UTF-8");

    } catch (Exception e){System.out.print(e);}

    System.out.println("cookie -- " + cookie);
    System.out.println("cookie2 -- " + cookie2);

    return document;
}
}

The output for my cookie print statements is as follows (for experimental purposes)

cookie -- lastvisit=A1753DA7F2454A03B58DF8CBD39C22C4; Expires=Tue,   27-Mar-2018 18:27:55 GMT
cookie2 -- null

Body:
This site is using Java Servlet authentication mechanism. When you try to get any page that is password protected the server internally issues a forward that returns the login page content. After you post a valid username/password it forwards you to the requested URL.

Note that this is not a redirect, it is managed internally by the application server and the client does not see what is going on at the server side.

To get this to work you need to issue a GET to the page you are trying to retrieve. The server responds with the login page content and the session id as a cookie. You have to save the session id and send it when you post to the form action.

Since I don't have valid credentials to test I cannot guarantee that this will work. With invalid credentials, the server will issue a number of redirects which will eventually change the session, probably because it is invalidated and recreated.

Please try this with valid credentials and let me know if it works. If there are redirects on successful login maybe it will be necessary to disable automatic redirects and do them programmatically, checking for session id changes. Depending on the application server, it may change the session id for security purposes.

That said, this MAY work when you post valid credentials.

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

public class Scraper {

    private static final String USERNAME = "user@test.com";
    private static final String PASSWORD = "secret";
    private static final String GET_URL  = "https://parents.mtsd.k12.nj.us/genesis/parents?tab1=studentdata&tab2=gradebook&tab3=weeklysummary&studentid=100916&action=form";
    private static final String POST_URL = "https://parents.mtsd.k12.nj.us/genesis/j_security_check";

    public static void main(String[] args) {
        String cookies = doGet(GET_URL);
        doPost(POST_URL, cookies);
    };

    /**
     * Send the initial GET request which will forward to the login page
     * and retrieve cookies sent by the server.
     * Cookies are formatted according to HTTP specification so they can be
     * passed to the next request Cookie header.
     * @param getURL URL to get
     */
    public static String doGet(String getURL) {
        StringBuilder formattedCookies = new StringBuilder();
        try {
            URL url = new URL(getURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            InputStream is = conn.getInputStream();
            Map<String, List<String>> headers = conn.getHeaderFields();
            List<String> cookies = headers.get("Set-Cookie");
            ListIterator<String> it = cookies.listIterator();
            while (it.hasNext()) {
                String[] parts = it.next().split("; ");
                formattedCookies.append(parts[0]);
                if (it.hasNext()) {
                    formattedCookies.append("; ");
                }
            }
            System.out.println("\n\nGET OUTPUT");
            printContent(is);
        } catch (Exception e) {
            System.out.println(e.getLocalizedMessage());
        }
        return formattedCookies.toString();
    }

    /**
     * Post the form parameters and get page content.
     * @param postURL URL to post to
     * @param cookies The cookies to send
     */
    public static void doPost(String postURL, String cookies) {
        try {
            String postData = String.format("j_username=%s&j_password=%s",
                URLEncoder.encode(USERNAME, "UTF-8"), PASSWORD);
            URL url = new URL(postURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setInstanceFollowRedirects(true);
            conn.setRequestProperty("Cookie", cookies);
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
            out.write(postData);
            out.close();
            InputStream is = conn.getInputStream();
            System.out.println("\n\nPOST OUTPUT");
            printContent(is);
        } catch (Exception e) {
            System.out.println(e.getLocalizedMessage());
        }
    }

    public static void printContent(InputStream is) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
    }

}


问:
Unable to Set Initializer for Custom UICollectionView Cell Class
I am trying to set an initializer for a custom UICollectionViewCell class and I am receiving an error. I am new to Swift and understand that a model class must have a relevant initializer in order to use items from the class. Here is my code and the error I am receiving:

答:
You need to set a default value to your key variable or make it Optional

```<code>var key: String?
</code>```

Body:
You need to set a default value to your key variable or make it Optional

var key: String?


问:
Find 'average' with equal upper and lower distance to values of a given set
I recently encountered the following
problem:

Given a set of points with height yᵢ, find the height of the line for which the average distance to points above equals the average distance to points below the line:

More abstract definition: Given a set of real valued data points Y = {y1, ..., yn}, find ȳ which splits Y into two sets Y⁺ = {y ∊ Y : y > ȳ} and Y⁻ = {y ∊ Y : y < ȳ} so that the average distance between ȳ and elements of Y⁺ equals the average distance between ȳ and elements of Y⁻.

Naive solution: Initialize ȳ with the average of Y, compute average upper and lower distances and iteratively move up or down depending on whether the upper or lower average distance is greater.

Question: This problem is pretty basic, so there is probably a better solution (?) Even a non-iterative algebraic algorithm?

答:
An iterative solution based on maraca's answer:

Initialize ȳ with the mean of the given values.

Split the given values into those above and below ȳ.

Calculate the new optimal ȳ for this split.

Repeat until ȳ converges.

This is slightly faster than the algorithm outlined in the question.

// Find mean with equal average distance to upper and lower values:
function findEqualAverageDistanceMean(values) {
  let mean = values.reduce((a, b) => a + b) / values.length,
      last = NaN;

  // Iteratively equalize average distances:
  while (last != mean) {
    let lower_total = 0,
        lower_n = 0,
        upper_total = 0,
        upper_n = 0;

    for (let value of values) {
      if (value > mean) {
        upper_total += value;
        ++upper_n;
      } else if (value < mean) {
        lower_total += value;
        ++lower_n;
      }
    }
    last = mean;
    mean = (upper_total / upper_n + lower_total / lower_n) / 2;
  }
  return mean;
}

// Example:
let canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d"),
    points = Array.from({length: 100}, () => Math.random() ** 4),
    mean = points.reduce((a, b) => a + b) / points.length,
    equalAverageDistanceMean = findEqualAverageDistanceMean(points);

function draw(points, mean, equalAverageDistanceMean) {
  for (let [i, point] of points.entries()) {
    ctx.fillStyle = (point < equalAverageDistanceMean) ? 'red' : 'green';
    ctx.fillRect(i * canvas.width / points.length, canvas.height * point, 3, 3);
  }
  ctx.fillStyle = 'black';
  ctx.fillRect(0, canvas.height * mean, canvas.width, .5);
  ctx.fillRect(0, canvas.height * equalAverageDistanceMean, canvas.width, 3);
}

draw(points, mean, equalAverageDistanceMean);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="canvas" width="400" height="200"></code>```

Body:
An iterative solution based on maraca's answer:

Initialize ȳ with the mean of the given values.

Split the given values into those above and below ȳ.

Calculate the new optimal ȳ for this split.

Repeat until ȳ converges.

This is slightly faster than the algorithm outlined in the question.

// Find mean with equal average distance to upper and lower values:
function findEqualAverageDistanceMean(values) {
  let mean = values.reduce((a, b) => a + b) / values.length,
      last = NaN;

  // Iteratively equalize average distances:
  while (last != mean) {
    let lower_total = 0,
        lower_n = 0,
        upper_total = 0,
        upper_n = 0;

    for (let value of values) {
      if (value > mean) {
        upper_total += value;
        ++upper_n;
      } else if (value < mean) {
        lower_total += value;
        ++lower_n;
      }
    }
    last = mean;
    mean = (upper_total / upper_n + lower_total / lower_n) / 2;
  }
  return mean;
}

// Example:
let canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d"),
    points = Array.from({length: 100}, () => Math.random() ** 4),
    mean = points.reduce((a, b) => a + b) / points.length,
    equalAverageDistanceMean = findEqualAverageDistanceMean(points);

function draw(points, mean, equalAverageDistanceMean) {
  for (let [i, point] of points.entries()) {
    ctx.fillStyle = (point < equalAverageDistanceMean) ? 'red' : 'green';
    ctx.fillRect(i * canvas.width / points.length, canvas.height * point, 3, 3);
  }
  ctx.fillStyle = 'black';
  ctx.fillRect(0, canvas.height * mean, canvas.width, .5);
  ctx.fillRect(0, canvas.height * equalAverageDistanceMean, canvas.width, 3);
}

draw(points, mean, equalAverageDistanceMean);

<canvas id="canvas" width="400" height="200">