问:
How to change first activity in Android Studio?
I want to change my first activity, first I have activity named MainActivity. And I add new activity named ActivityFirst. Surely I have to change AndroidManifest.xml. Previously I have androidManifest like this:

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

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

And after I add my new activity, also I change my androidManifest file.

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

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".ActivityFirst">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

I'm confused where I put the MainActivity after I add ActivityFirst. This my ActivityFirst.java:

```<code>public class ActivityFirst extends AppCompatActivity {

  private Button mulai;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_first);

    mulai = (Button) findViewById(R.id.mulai);

    mulai.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(ActivityFirst.this, MainActivity.class);
            startActivity(intent);
        }
    });
  }
}
</code>```

答:
In Android, The first Activity to show when a app is launched is tagged LAUNCHER in your manifest file.

All you need do to change the Launcher Activity is to add an intent-filter tag inside the activity tag.

So if your activity tag was self closing, you change it and add intent filter tag inside the tag.

Here is an illustration.

```<code><activity android:name=".MainActivity" />
<activity android:name=".ActivityFirst">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
</code>```

The above code in your Manifest will make ActivityFirst the launcher activity,

while the below code will make MainActivity the launcher activity.

```<code><activity android:name=".ActivityFirst" />
<activity android:name=".MainActivity">
<intent-filter>
    <action android:name="android.intent.action.MAIN" />

    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</code>```

I hope this helps.

Body:
I want to change my first activity, first I have activity named MainActivity. And I add new activity named ActivityFirst. Surely I have to change AndroidManifest.xml. Previously I have androidManifest like this:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="edmt.dev.androidsimsimi">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

And after I add my new activity, also I change my androidManifest file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="edmt.dev.androidsimsimi">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".ActivityFirst">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

I'm confused where I put the MainActivity after I add ActivityFirst. This my ActivityFirst.java:

public class ActivityFirst extends AppCompatActivity {

  private Button mulai;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_first);

    mulai = (Button) findViewById(R.id.mulai);

    mulai.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(ActivityFirst.this, MainActivity.class);
            startActivity(intent);
        }
    });
  }
}

Body:
In Android, The first Activity to show when a app is launched is tagged LAUNCHER in your manifest file.

All you need do to change the Launcher Activity is to add an intent-filter tag inside the activity tag.

So if your activity tag was self closing, you change it and add intent filter tag inside the tag.

Here is an illustration.

<activity android:name=".MainActivity" />
<activity android:name=".ActivityFirst">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

The above code in your Manifest will make ActivityFirst the launcher activity,

while the below code will make MainActivity the launcher activity.

<activity android:name=".ActivityFirst" />
<activity android:name=".MainActivity">
<intent-filter>
    <action android:name="android.intent.action.MAIN" />

    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

I hope this helps.


来源: stackexchange

问:
Can you use a fixed size type and pointers together in the same union?
I'm investigating the possibility of defining a structure for a packet. I would like to set header variables in the packet and then set a pointer to the data part of the packet. My end goal is to be able to send this packet to a low level library that takes only a uint8_t*. I created this quick program to test the feasibility and it does not seem to work.

```<code>#include <iostream>
#include <cstdint>
#include <stdlib.h>

typedef union {
    struct {
        uint8_t header;
        uint8_t* data;
    };
    uint8_t* packet;
} sometype;

int main() {
    sometype s;
    s.header = 3;
    s.data = (uint8_t *) malloc(sizeof(uint8_t) * 2);
    s.data[0] = 1;
    s.data[1] = 2;

    for (unsigned int i = 0; i < 3; i++) {
        std::cout << s.packet[i] << std::endl;
    }

    std::cout << std::endl;

    std::cout << s.header << std::endl;
    std::cout << s.data[0] << std::endl;
    std::cout << s.data[1] << std::endl;
}
</code>```

My output is

```<code>�
�
�

</code>```

Which makes me realize I have some type of error in my code (I've never worked with union before). However, when I debug the program I can see the data in the union. Looking at the packet, I can see that this method does not appear to be working. The data in the packet is not 3, 1, 2. It is 300, 221, 020 instead.

```<code>(gdb) print s
$1 = {{header = 3 '\003', data = 0x613c20 "\001\002"}, packet = 0x400903 <main()+125> "\300\211ƿ`\020`"}
</code>```

Is this method that I am attempting valid? From google searches I saw someone say you can use whatever datatypes you want. Do I have to pack the structure using a pragma to get this to work or is this method not feasible?

答:
The unusual output is because you attempt to use << to print a uint8_t.

Usually (although the C++ standard doesn't specify this), uint8_t triggers the character overload of <<, so you print out the glyph corresponding to that character code, instead of the integer.  To avoid this hiccup you could do std::cout << static_cast<int>(s.header); etc.

Note that in Standard C++ it is not permitted to write one member of a union and then read a different member, i.e. you may only read the same member that was last written.  The technique you are trying to use is called union aliasing and is not allowed in Standard C++, although compilers may seem to support it as an extension.

However, even if you're on a compiler that does offer union aliasing, you still won't be able to do s.packet[i] with your current struct definition. This is because packet overlaps with header and data. The byte value of header should not be a part of the address packet is pointing to, but your code treats it like it is.

I guess you mentally had a model of a single pointer and you can interpret the memory being pointed to by the pointer as either a char array,   or as a char followed by a char array. But your code doesn't reflect that (and in fact you can't do that at all, unless the lengths of the arrays are known at compile-time).

Since header and data[0] are not in contiguous memory, there's no way you are going to be able to have a single pointer that points to some fictitious memory block in which those two bytes are adjacent.  I would recommend giving up on this entire line of enquiry; just have a single memory block, and you can make functions that access particular parts of it.

ContentLicense: CC BY-SA 3.0

Body:
I'm investigating the possibility of defining a structure for a packet. I would like to set header variables in the packet and then set a pointer to the data part of the packet. My end goal is to be able to send this packet to a low level library that takes only a uint8_t*. I created this quick program to test the feasibility and it does not seem to work.

#include <iostream>
#include <cstdint>
#include <stdlib.h>

typedef union {
    struct {
        uint8_t header;
        uint8_t* data;
    };
    uint8_t* packet;
} sometype;

int main() {
    sometype s;
    s.header = 3;
    s.data = (uint8_t *) malloc(sizeof(uint8_t) * 2);
    s.data[0] = 1;
    s.data[1] = 2;

    for (unsigned int i = 0; i < 3; i++) {
        std::cout << s.packet[i] << std::endl;
    }

    std::cout << std::endl;

    std::cout << s.header << std::endl;
    std::cout << s.data[0] << std::endl;
    std::cout << s.data[1] << std::endl;
}

My output is

�
�
�

Which makes me realize I have some type of error in my code (I've never worked with union before). However, when I debug the program I can see the data in the union. Looking at the packet, I can see that this method does not appear to be working. The data in the packet is not 3, 1, 2. It is 300, 221, 020 instead.

(gdb) print s
$1 = {{header = 3 '\003', data = 0x613c20 "\001\002"}, packet = 0x400903  "\300\211ƿ`\020`"}

Is this method that I am attempting valid? From google searches I saw someone say you can use whatever datatypes you want. Do I have to pack the structure using a pragma to get this to work or is this method not feasible?


问:
Sendgrid category analytics with API v3
Is it possible to add a category tag to mail being send via the Sendgrid API?

What I'd like to know is open and click rates for specific types of transactional e-mails. It appears you can add a category using the STMP API but I can't find any documentation on how to do that using API v3 (just a GET endpoint).

Am I even thinking about this right? Is SendGrid the right place to track opens and clicks or should I use the webhooks and track this stuff myself?

答:
It looks like SendGrid accepts categories. Check out their other API documentation page.

There's also a send example of categories in their python client.

Title: Sendgrid category analytics with API v3


问:
UITableView cell selected not loading another View
Hey everbody, im getting a curious problem here. Im trying to make my table push another view, called 'productviewcontroller'.

Im importing both 'productviewcontroller' and  'myappviewcontroller' on header.

```<code>#import "SearchViewController.h"
#import "MyAppViewController.h"
#import "TBXML.h"
#import "ProductViewController.h"
</code>```

And im setting my table to push the another view.

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    ProductViewController *productViewController = [[ProductViewController alloc] initWithNibName:@"ProductViewController" bundle:[NSBundle mainBundle]];

    [self.navigationController pushViewController:productViewController animated:YES];
    [productViewController release];

    NSLog(@"Test.");
}
</code>```

When i selects the cell, it gives me the message 'test'. But dont push the another view.
Im setting the navigationController on app delegate.

What im doing wrong?

Thanks!

答: Use your navigation controller in this view from which you want to push "ProductControllerView" and bind it with IBOutlet and you are able to push the view..</p>

ContentLicense: CC BY-SA 2.5

Body:
Hey everbody, im getting a curious problem here. Im trying to make my table push another view, called 'productviewcontroller'.

Im importing both 'productviewcontroller' and  'myappviewcontroller' on header.

#import "SearchViewController.h"
#import "MyAppViewController.h"
#import "TBXML.h"
#import "ProductViewController.h"

And im setting my table to push the another view.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    ProductViewController *productViewController = [[ProductViewController alloc] initWithNibName:@"ProductViewController" bundle:[NSBundle mainBundle]];

    [self.navigationController pushViewController:productViewController animated:YES];
    [productViewController release];

    NSLog(@"Test.");
}

When i selects the cell, it gives me the message 'test'. But dont push the another view.
Im setting the navigationController on app delegate.

What im doing wrong?

Thanks!


问:
Adding zeros spaces to an array of a picture
I have an image defined as:

```<code>imagen = scipy.misc.imread("C:\\Users\\Reymi\\Downloads\\imagen.png")
</code>```

It has a size of (1929,1280)
I need to add 2 columns and rows with zeros to each side of the array so I can use a kernel without worrying about it going outside of the array.

How? Thank you

答:
Use the pad function:

```<code>im_new = scipy.pad(array=imagen, pad_width=[2, 2], mode='constant', constant_values=0)
</code>```

The above function makes the array bigger by 2 in all directions.  If you wanted to replace the outer two pixels with 0's without making the picture larger I don't think there is a built-in function, but I would do something like:

```<code>pad = 2
im_new = scipy.zeros_like(imagen)
im_new[pad:-pad, pad:-pad] = imagen[pad:-pad, pad:-pad]
</code>```

This creates an image of 0's, then fills in the middle with the middle part of imagen.

Body:
I have an image defined as:

imagen = scipy.misc.imread("C:\\Users\\Reymi\\Downloads\\imagen.png")

It has a size of (1929,1280)
I need to add 2 columns and rows with zeros to each side of the array so I can use a kernel without worrying about it going outside of the array.

How? Thank you

Body:
Use the pad function:

im_new = scipy.pad(array=imagen, pad_width=[2, 2], mode='constant', constant_values=0)

The above function makes the array bigger by 2 in all directions.  If you wanted to replace the outer two pixels with 0's without making the picture larger I don't think there is a built-in function, but I would do something like:

pad = 2
im_new = scipy.zeros_like(imagen)
im_new[pad:-pad, pad:-pad] = imagen[pad:-pad, pad:-pad]

This creates an image of 0's, then fills in the middle with the middle part of imagen.


问:
Matplotlib plot only horizontal lines in step plot
I am using matplotlib to plot some step functions from a dataframe

```<code>df['s1'].plot(c='b', drawstyle="steps-post")
df['s2'].plot(c='b', drawstyle="steps-post")
...
</code>```

The result looks like

I would like to have this only plot the horizontal lines, not the vertical lines connecting the jump points. I could not find a straightforward parameter for plot that would seem to do that. Is there a way to do this?

答:
There is no built-in option to produce a step function without vertical lines as far as I can tell. But you may easily build one yourself. The following uses the fact that np.nan is not plotted and cuts the line. So adding np.nan in between the steps suppresses the vertical line.

```<code>import matplotlib.pyplot as plt
import numpy as np

def mystep(x,y, ax=None, where='post', **kwargs):
    assert where in ['post', 'pre']
    x = np.array(x)
    y = np.array(y)
    if where=='post': y_slice = y[:-1]
    if where=='pre': y_slice = y[1:]
    X = np.c_[x[:-1],x[1:],x[1:]]
    Y = np.c_[y_slice, y_slice, np.zeros_like(x[:-1])*np.nan]
    if not ax: ax=plt.gca()
    return ax.plot(X.flatten(), Y.flatten(), **kwargs)

x = [1,3,4,5,8,10,11]
y = [5,4,2,7,6,4,4]

mystep(x,y, color="crimson")

plt.show()
</code>```

Body:
I am using matplotlib to plot some step functions from a dataframe

df['s1'].plot(c='b', drawstyle="steps-post")
df['s2'].plot(c='b', drawstyle="steps-post")
...

The result looks like

I would like to have this only plot the horizontal lines, not the vertical lines connecting the jump points. I could not find a straightforward parameter for plot that would seem to do that. Is there a way to do this?

Body:
There is no built-in option to produce a step function without vertical lines as far as I can tell. But you may easily build one yourself. The following uses the fact that np.nan is not plotted and cuts the line. So adding np.nan in between the steps suppresses the vertical line.

import matplotlib.pyplot as plt
import numpy as np

def mystep(x,y, ax=None, where='post', **kwargs):
    assert where in ['post', 'pre']
    x = np.array(x)
    y = np.array(y)
    if where=='post': y_slice = y[:-1]
    if where=='pre': y_slice = y[1:]
    X = np.c_[x[:-1],x[1:],x[1:]]
    Y = np.c_[y_slice, y_slice, np.zeros_like(x[:-1])*np.nan]
    if not ax: ax=plt.gca()
    return ax.plot(X.flatten(), Y.flatten(), **kwargs)

x = [1,3,4,5,8,10,11]
y = [5,4,2,7,6,4,4]

mystep(x,y, color="crimson")

plt.show()

ContentLicense: CC BY-SA 4.0


问:
Exceptionless.extras error in VS2015 using vb.net
I have been programming a web forms application using VS2015.
All of a sudden an error form starts popping up for Exceptionless.Extras has encountered a problem and needs to close.
Then asking me to send to submit a report Exceptionless.Extras Error dialog image

To my knowledge I have not added any packages for this control.  Checking Tools and NuGet for Exceptionless shows nothing installed

How do I get rid of this?
Any help would be greatly appreciated

答: I work for CodeSmith Tools on CodeSmith Generator as well as the Exceptionless Project. This could be caused by an unhandled Visual Studio exception that's being picked up by the CodeSmith Generator add-in or a third party add-in which uses Exceptionless. If you have Generator installed. I'd recommend submitting the exception with your email address and contact support and we'll take a look into the exception. Also, we can let you know how to disable this dialog if you have CodeSmith Generator installed.</p>


问:
React Native - Animated Functional Components
I love the React Native animated API but it conflicts heavily with my preferred way of writing components which is completely stateless functional components.

Take this component as an example. How would I make the Image animated without reverting to class syntax and a state variable to drive the Image style?

```<code>const Logo = () => (
  <View style={styles.container}>
    <View style={styles.imageContainer}>
      <Animated.Image
        resizeMode='contain'
        style={styles.image}
        source={require(img/sample.png')}
      />
    </View>
  </View>
)

export default Logo
</code>```

答:
You can use store to keep animated values of course. But IMO it is bad idea.  Just use classes. You should be more flexible ;)

As alternative you can try https://github.com/oblador/react-native-animatable with declarative syntax. I didn't use it before but look like it can help.

UPDATED: With React Native 0.59 and above you can use hooks inside functional components.

Body:
I love the React Native animated API but it conflicts heavily with my preferred way of writing components which is completely stateless functional components.

Take this component as an example. How would I make the Image animated without reverting to class syntax and a state variable to drive the Image style?

const Logo = () => (
  <View style={styles.container}>
    <View style={styles.imageContainer}>
      <Animated.Image
        resizeMode='contain'
        style={styles.image}
        source={require(img/sample.png')}
      />
    </View>
  </View>
)

export default Logo


问:
Can't start Android Studio Layout Inspector: "Unexpected error: empty view hierarchy"
Can't seem to launch Layout Inspector on Android Studio 3.0 (Canary 3)

When connected to my device and app running, choosing Tools > Android > Layout Inspector comes up with the following error dialog:

"Error obtaining view hierarchy: Unexpected error: empty view hierarchy"

Any setup I'm missing? I have Developer Options enabled on the device.

答: I can't launch my hierarchy viewer while playing video. Once I pause the video, it works!</p>


问:
Algorithm - How to delete duplicate elements in a Haskell list
I'm having a problem creating an function similar to the nub function.

I need this func to remove duplicated elements form a list.
An element is duplicated when 2 elements have the same email, and it should keep the newer one (is closer to the end of the list).

```<code>type Regist = [name,email,,...,date]
type ListRe = [Regist]

rmDup ListRe -> ListRe
rmDup [] = []
rmDup [a] = [a]
rmDup (h:t) | isDup h (head t) = rmDup t
            | otherwise = h : rmDup t

isDup :: Regist -> Regist -> Bool
isDup (a:b:c:xs) (d:e:f:ts) = b==e
</code>```

The problem is that the function doesn't delete duplicated elements unless they are together in the list.

答:
Anon is correct: nubBy is the function you are looking for, and can be found in Data.List.

That said, you want a function rem which accepts a list xs and a function f :: a -> a -> Bool (on which elements are compared for removal from xs). Since the definition is recursive, you need a base case and a recursive case.

In the base case xs = [] and rem f xs = [], since the result of removing all duplicate elements from [] is []:

```<code>rem :: Eq a => (a -> a -> Bool) -> [a] -> [a]
rem f [] = []
</code>```

In the recursive case, xs = (a:as). Let as' be the list obtained by removing all elements a' such that f a a' = True from the list as. This is simply the function filter (\a' -> not $ f a a') applied to the list as. Them rem f (a:as) is the result of recursively calling rem f on as', that is, a : rem f as':

```<code>rem f (a:as) = a : rem f $ filter (\a' -> not $ f a a') as
</code>```

Replace f be a function comparing your list elements for the appropriate equality (e-mail addresses).

Body:
I'm having a problem creating an function similar to the nub function.

I need this func to remove duplicated elements form a list.
An element is duplicated when 2 elements have the same email, and it should keep the newer one (is closer to the end of the list).

type Regist = [name,email,,...,date]
type ListRe = [Regist]

rmDup ListRe -> ListRe
rmDup [] = []
rmDup [a] = [a]
rmDup (h:t) | isDup h (head t) = rmDup t
            | otherwise = h : rmDup t

isDup :: Regist -> Regist -> Bool
isDup (a:b:c:xs) (d:e:f:ts) = b==e

The problem is that the function doesn't delete duplicated elements unless they are together in the list.

Body:
Anon is correct: nubBy is the function you are looking for, and can be found in Data.List.

That said, you want a function rem which accepts a list xs and a function f :: a -> a -> Bool (on which elements are compared for removal from xs). Since the definition is recursive, you need a base case and a recursive case.

In the base case xs = [] and rem f xs = [], since the result of removing all duplicate elements from [] is []:

rem :: Eq a => (a -> a -> Bool) -> [a] -> [a]
rem f [] = []

In the recursive case, xs = (a:as). Let as' be the list obtained by removing all elements a' such that f a a' = True from the list as. This is simply the function filter (\a' -> not $ f a a') applied to the list as. Them rem f (a:as) is the result of recursively calling rem f on as', that is, a : rem f as':

rem f (a:as) = a : rem f $ filter (\a' -> not $ f a a') as

Replace f be a function comparing your list elements for the appropriate equality (e-mail addresses).


问:
How to make a uiactionsheet dismiss when you tap outside eg above it?
How do i make a uiactionsheet dismiss when you tap outside eg above it? This is for iPhone. Apparently the ipad does this by default (I may be wrong).</p>

答: Use .cancel UIAlertActionStyle as an option.


问:
parse xml output into drop down selection box
I want to parse the xml recieved from the Kunaki API into a Drop Down Selection Box. I have this code so far but the box keeps remaining empty, so my question is this how do I achieve this? I keep getting an empty drop down selection box everytime.

```<code><?php
$context  = stream_context_create(array('http' => array('header' => 'Accept: application/xml')));
$url = 'http://kunaki.com/HTTPService.ASP?RequestType=ShippingOptions&State_Province=NY&PostalCode=11204&Country=United+States&ProductId=PX0012345&Quantity=1&ProductId=PX04444444&Quantity=1&ResponseType=xml ';

$xml = file_get_contents($url, false, $context);
$xml2 = simplexml_load_string($xml);

?>
<html>
  <head>

  </head>
  <body>

    <select>

    <Option Value=<?php  echo $value = (string)$xml2->Description[0]." Delivery Time ".(string)$xml2pt->DeliveryTime[0].(string)$xml2->Price[0];?></Option>
    </select>
 </body>
</html>
</code>```

答:
After some fiddling, I believe this is what you're after.

```<code><?php

// Setup your context for file_get_contents
$oContext = stream_context_create(array("http" => array("header" => "Accept: application/xml")));
// Put in your URL here to get the XML from
$sURL = "http://kunaki.com/HTTPService.ASP?RequestType=ShippingOptions&State_Province=NY&PostalCode=11204&Country=United+States&ProductId=PX0012345&Quantity=1&ProductId=PX04444444&Quantity=1&ResponseType=xml";
// Parse the XML
$oXML = simplexml_load_string(file_get_contents($sURL, false, $oContext));
// Grab the data that we need from the XML
$pOptions = isset($oXML->Option) && isset($oXML->Option[0]) ? $oXML->Option : array("error" => true);
// Display everything to the page
echo "<html>";
    echo "<head>";
        echo "<title>XML Test</title>";
    echo "</head>";
    echo "<body>";
        // If there was an error, display it to the page
        if(isset($pOptions["error"]))
        {
            echo "<h3>Sorry, wrong data returned.";
            var_dump($pOptions);
        }
        else
        {
            // Loop through the array and display the dropdown
            echo "<select>";
                for($i = 0, $iCount = count($pOptions); $i < $iCount; ++$i)
                {
                    $sString = $pOptions[$i]->Description.", ";
                    $sString .= "Delivery Time: ".$pOptions[$i]->DeliveryTime." ";
                    $sString .= "($".$pOptions[$i]->Price.")";
                    echo "<option>".$sString."</option>";
                }
            echo "</select>";
        }
    echo "</body>";
echo "</html>";

?>
</code>```

I reformatted the display of the dropdown text a little bit so that it was easier to read.
In this example, it makes this dropdown:

<select>
  <option>
    USPS First Class Mail, Delivery Time: 2-5 business days ($0.66)
  </option>
  <option>
    UPS Ground, Delivery Time: 1-5 business days ($17.17)
  </option>
  <option>
    UPS 2nd Day Air, Delivery Time: 2 business days ($30.42)
  </option>
  <option>
    UPS Next Day Air Saver, Delivery Time: 1 business day ($50.17)
  </option>
</select>```
</div>
</div>
</p>

<p>One of your issues was, you were putting the data only into the value attribute of the dropdown items.</p>

<p>Example:</p>

<p><code><option value="test"></option></code></p>

<p>Which would only display:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><select>
  <option value="test"></option>
</select></code>```

So what you were after, was something more like this:

<select>
  <option>Test</option>
</select>```

Other than that, you were only trying to display the first returned option, not all of them.
That's where that for() loop comes into play, it will loop through and display all of the returned shipping options, irregardless of how many there are.

Hope this helps!

Body:
I want to parse the xml recieved from the Kunaki API into a Drop Down Selection Box. I have this code so far but the box keeps remaining empty, so my question is this how do I achieve this? I keep getting an empty drop down selection box everytime.

<?php
$context  = stream_context_create(array('http' => array('header' => 'Accept: application/xml')));
$url = 'http://kunaki.com/HTTPService.ASP?RequestType=ShippingOptions&State_Province=NY&PostalCode=11204&Country=United+States&ProductId=PX0012345&Quantity=1&ProductId=PX04444444&Quantity=1&ResponseType=xml ';

$xml = file_get_contents($url, false, $context);
$xml2 = simplexml_load_string($xml);

?>

    <select>

    <Option Value=<?php  echo $value = (string)$xml2->Description[0]." Delivery Time ".(string)$xml2pt->DeliveryTime[0].(string)$xml2->Price[0];?></Option>
    </select>

Body:
After some fiddling, I believe this is what you're after.

<?php

// Setup your context for file_get_contents
$oContext = stream_context_create(array("http" => array("header" => "Accept: application/xml")));
// Put in your URL here to get the XML from
$sURL = "http://kunaki.com/HTTPService.ASP?RequestType=ShippingOptions&State_Province=NY&PostalCode=11204&Country=United+States&ProductId=PX0012345&Quantity=1&ProductId=PX04444444&Quantity=1&ResponseType=xml";
// Parse the XML
$oXML = simplexml_load_string(file_get_contents($sURL, false, $oContext));
// Grab the data that we need from the XML
$pOptions = isset($oXML->Option) && isset($oXML->Option[0]) ? $oXML->Option : array("error" => true);
// Display everything to the page
echo "<html>";
    echo "<head>";
        echo "<title>XML Test</title>";
    echo "</head>";
    echo "<body>";
        // If there was an error, display it to the page
        if(isset($pOptions["error"]))
        {
            echo "<h3>Sorry, wrong data returned.";
            var_dump($pOptions);
        }
        else
        {
            // Loop through the array and display the dropdown
            echo "<select>";
                for($i = 0, $iCount = count($pOptions); $i < $iCount; ++$i)
                {
                    $sString = $pOptions[$i]->Description.", ";
                    $sString .= "Delivery Time: ".$pOptions[$i]->DeliveryTime." ";
                    $sString .= "($".$pOptions[$i]->Price.")";
                    echo "<option>".$sString."</option>";
                }
            echo "</select>";
        }
    echo "</body>";
echo "</html>";

?>

I reformatted the display of the dropdown text a little bit so that it was easier to read.
In this example, it makes this dropdown:

<select>
  <option>
    USPS First Class Mail, Delivery Time: 2-5 business days ($0.66)
  </option>
  <option>
    UPS Ground, Delivery Time: 1-5 business days ($17.17)
  </option>
  <option>
    UPS 2nd Day Air, Delivery Time: 2 business days ($30.42)
  </option>
  <option>
    UPS Next Day Air Saver, Delivery Time: 1 business day ($50.17)
  </option>
</select>

One of your issues was, you were putting the data only into the value attribute of the dropdown items.

Example:

<option value="test"></option>

Which would only display:

<select>
  <option value="test"></option>
</select>

So what you were after, was something more like this:

<select>
  <option>Test</option>
</select>

Other than that, you were only trying to display the first returned option, not all of them.
That's where that for() loop comes into play, it will loop through and display all of the returned shipping options, irregardless of how many there are.

Hope this helps!


问:
Delete batch operation in Azure Storage
I have been trying to implement a DAO method for delete operation for Azure Storage entities. Delete using TableOperation was ok.

```<code>TableOperation deleteEntity = TableOperation.delete(entity);
</code>```

But when I tried it using Batch Operation, It was not supported.

Any suggestions to overcome this issue is highly appreciated.

答:
But when I tried it using Batch Operation, It was not supported.

I assumed that you could group your items for deleting by partition key, then execute the TableBatchOperation.

Here I wrote a helper class via C# language for achieving this purpose, you could refer to it:

```<code>public class TableBatchHelper<T> where T : ITableEntity
{
    const int batchMaxSize = 100;

    public static IEnumerable<TableBatchOperation> GetBatchesForDelete(IEnumerable<T> items)
    {
        var list = new List<TableBatchOperation>();
        var partitionGroups = items.GroupBy(arg => arg.PartitionKey).ToArray();
        foreach (var group in partitionGroups)
        {
            T[] groupList = group.ToArray();
            int offSet = batchMaxSize;
            T[] entities = groupList.Take(offSet).ToArray();
            while (entities.Any())
            {
                var tableBatchOperation = new TableBatchOperation();
                foreach (var entity in entities)
                {
                    tableBatchOperation.Add(TableOperation.Delete(entity));
                }
                list.Add(tableBatchOperation);
                entities = groupList.Skip(offSet).Take(batchMaxSize).ToArray();
                offSet += batchMaxSize;
            }
        }
        return list;
    }

    public static async Task BatchDeleteAsync(CloudTable table, IEnumerable<T> items)
    {
        var batches = GetBatchesForDelete(items);
        await Task.WhenAll(batches.Select(table.ExecuteBatchAsync));
    }
}
</code>```

Then, you could you execute the batch deleting as follows:

```<code>await TableBatchHelper<ClassName>.BatchDeleteAsync(cloudTable,items);
</code>```

Or

```<code>var batches = TableBatchHelper<ClassName>.GetBatchesForDelete(entities);
Parallel.ForEach(batches, new ParallelOptions()
{
    MaxDegreeOfParallelism = 5
}, (batchOperation) =>
    {
        try
        {
            table.ExecuteBatch(batchOperation);
            Console.WriteLine("Writing {0} records", batchOperation.Count);
        }
        catch (Exception ex)
        {
            Console.WriteLine("ExecuteBatch throw a exception:" + ex.Message);
        }
    });
</code>```

Title: Delete batch operation in Azure Storage

Body:
I have been trying to implement a DAO method for delete operation for Azure Storage entities. Delete using TableOperation was ok.

TableOperation deleteEntity = TableOperation.delete(entity);

But when I tried it using Batch Operation, It was not supported.

Any suggestions to overcome this issue is highly appreciated.

Body:
But when I tried it using Batch Operation, It was not supported.

I assumed that you could group your items for deleting by partition key, then execute the TableBatchOperation.

Here I wrote a helper class via C# language for achieving this purpose, you could refer to it:

public class TableBatchHelper<T> where T : ITableEntity
{
    const int batchMaxSize = 100;

    public static IEnumerable<TableBatchOperation> GetBatchesForDelete(IEnumerable<T> items)
    {
        var list = new List<TableBatchOperation>();
        var partitionGroups = items.GroupBy(arg => arg.PartitionKey).ToArray();
        foreach (var group in partitionGroups)
        {
            T[] groupList = group.ToArray();
            int offSet = batchMaxSize;
            T[] entities = groupList.Take(offSet).ToArray();
            while (entities.Any())
            {
                var tableBatchOperation = new TableBatchOperation();
                foreach (var entity in entities)
                {
                    tableBatchOperation.Add(TableOperation.Delete(entity));
                }
                list.Add(tableBatchOperation);
                entities = groupList.Skip(offSet).Take(batchMaxSize).ToArray();
                offSet += batchMaxSize;
            }
        }
        return list;
    }

    public static async Task BatchDeleteAsync(CloudTable table, IEnumerable<T> items)
    {
        var batches = GetBatchesForDelete(items);
        await Task.WhenAll(batches.Select(table.ExecuteBatchAsync));
    }
}

Then, you could you execute the batch deleting as follows:

await TableBatchHelper<ClassName>.BatchDeleteAsync(cloudTable,items);

Or

var batches = TableBatchHelper<ClassName>.GetBatchesForDelete(entities);
Parallel.ForEach(batches, new ParallelOptions()
{
    MaxDegreeOfParallelism = 5
}, (batchOperation) =>
    {
        try
        {
            table.ExecuteBatch(batchOperation);
            Console.WriteLine("Writing {0} records", batchOperation.Count);
        }
        catch (Exception ex)
        {
            Console.WriteLine("ExecuteBatch throw a exception:" + ex.Message);
        }
    });


问:
Converting fat arrow to standard notation
How do I convert this piece of code to not use the fat arrow?

```<code>propertyOf = object => {
  return propName => {
    for (let key in object) {
  if(key === propName) return object[key]
    }
  }
}
</code>```

I changed the first line to

```<code>propertyOf = function (object) {
</code>```

and the code still worked. When I changed also the second line to

```<code>return propName = function () {
</code>```

I got an error saying "undefined" when I tried to call the function. I also got an error beside the second line saying 'Did you mean to run a conditional instead of an assignment?'

The full code is this:

```<code>let bob = {
  name: 'Bob',
  age: 87
},
searchBob;

propertyOf = object => {
  return propName => {
    for (let key in object) {
  if(key === propName) return object[key]
    }
  }
}

searchBob = propertyOf(bob);

console.log(searchBob('age'));
</code>```

答:
In the return propName => {, propName is the parameter of the function, so it translates to

```<code>return function(propName) {
</code>```

In the documentation of the arrow function, it is specified that when there is only one parameter, the parenthesis can be omitted.

Body:
How do I convert this piece of code to not use the fat arrow?

propertyOf = object => {
  return propName => {
    for (let key in object) {
  if(key === propName) return object[key]
    }
  }
}

I changed the first line to

propertyOf = function (object) {

and the code still worked. When I changed also the second line to

return propName = function () {

I got an error saying "undefined" when I tried to call the function. I also got an error beside the second line saying 'Did you mean to run a conditional instead of an assignment?'

The full code is this:

let bob = {
  name: 'Bob',
  age: 87
},
searchBob;

propertyOf = object => {
  return propName => {
    for (let key in object) {
  if(key === propName) return object[key]
    }
  }
}

searchBob = propertyOf(bob);

console.log(searchBob('age'));

Body:
In the return propName => {, propName is the parameter of the function, so it translates to

return function(propName) {

In the documentation of the arrow function, it is specified that when there is only one parameter, the parenthesis can be omitted.


问:
how to mark "executed command" for custom script extension in shell script given
How to mark a configured shell script to executed command in Azure VM Custom Script Extension ?

It is running the shell commands in configured CSE but it has not ending up the script due to one of my command. My command will be running a small HTTP listener kind of server.

If make "exit 0" will mark CSE as command executed and so it will exits in my powershell script where i encountered this CSE.

答:
If my understanding is right. You could run HTTP listener in the background and exit your script. Just use below:

```<code>nohup <bash shell> &
</code>```

man nohup

nohup - run a command immune to hangups, with output to a non-tty

& to the command line to run in the background:

Body:
If my understanding is right. You could run HTTP listener in the background and exit your script. Just use below:

nohup <bash shell> &

man nohup

nohup - run a command immune to hangups, with output to a non-tty

& to the command line to run in the background:


问:
Jquery and Javascript combined. Code not working
I have written the below code to display a selection of images within a
 tag when a certain button is clicked on a page. The Jquery to hide the
 elements on page load works, but the rest of the code does nothing. Can anyone help me figure this out please?

```<code>    $(document).ready(function(){
    //Create Array for images
    var vanImgArr = new Array("<img src='img\yvr\coalharbour.jpg'>", "<img src='img\yvr\lgbridge.jpg'>", "<img src='img/yvr/yaletown.jpg'/>", "<img src='img\yvr\lgbridge2.jpg'>");
    var sgpImgArr = new Array("<img src='img\sgp\elginbridge.jpg'>", "<img src='img\sgp\mbfc.jpg'>", "<img src='img\sgp\sgpdusk.jpg'>", "<img src='img\sgp\sgppano.jpg'>");
    var aniImgArr = new Array("<img src='img\ani\cat1.jpg'>", "<img src='img\ani\cat2.jpg'>", "<img src='img\ani\dog1.jpg'>", "<img src='img\ani\tandd.jpg'>");
    var absImgArr = new Array("<img src='img\abs\abs1.jpg'>", "<img src='img\abs\abs2.jpg'>", "<img src='img\abs\abs3.jpg'>", "<img src='img\abs\abs4.jpg'>");
    var clickedId;
    var idx = 0;
    //to display images
    function displayImgs(arr)
    {

        if(idx <= arr.length)
        {
            ('#pic').hide();
            ('#pic').html(arr[idx]);
            ('#pic').fadeIn('slow');
            if(idx > arr.length)
            {
                idx = 0;
            }
            else
            {
                idx++;
            }
        };  //button click close
    }//displayImgs method close

    //on page load
    $('p').hide();

    //More info Action
    $('#more').hover(function(){
        $('#info, #info2').fadeIn('slow');
    });

    //Button Click Action
    $(':button').click(function(){
        clickedId = this.id;
        alert(clickedId); //testing
        switch(clickedId)
        {
            case 'yvr':
                displayImgs(vanImgArr);
                break;

            case 'sgp':
                displayImgs(sgpImgArr);
                break;

            case 'ani':
                displayImgs(aniImgArr);
                break;

            case 'abs':
                displayImgs(absImgArr);
                break;
        }//switch/case close
    });//button click close
});
</code>```

Here is my HTML code to go with the above

```<code><!DOCTYPE html>
</code>```

```<code><title>Ricky Deacon CSIS3380-001, Assignment 2, Summer 2017</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="script.js"></script>
</code>```

```<code><table class="t1">

    <tr>
        <th width="25%" rowspan="3"><img src="img\rick2.JPG" alt="RD portrait goes here"></th>
        <th width="50%" colspan="2">Rick Deacon</th>
        <th width="25%" rowspan="3"><img src="img\rick1.JPG" alt="RD portrait goes here"></th>
    </tr>
    <tr>
        <td id="subtitle" colspan="2">Photography Showcase</td>
    </tr>
    <tr>
        <td id="desc" colspan="2">Click the corresponding button to display images from your chosen category.</td>
    </tr>
</table>
<br/>
<br/>
<table class="t2">
    <tr>
        <th>
             <input id="van" type="button" name="submit" value="Show Vancouver Images"/>
         </th>
         <th>
             <input id="sgp" type="button" name="submit" value="Show Singapore Images"/>
         </th>
         <th>
             <input id="ani" type="button" name="submit" value="Show Animal Images"/>
         </th>
         <th>
             <input id="abs" type="button" name="submit" value="Show Abstract Images"/>
         </th>
    </tr>
    <tr>
        <th>
             <p id="info"><a href="https://flickr.com/rick-deacon">Rick Deacon's Flickr</a></p>
        </th>
        <th colspan="2">
            <h1 id="more">More Info and Portfolio Links</h1>
        </th>
        <th>
             <p id="info2"><a href="https://rick-deacon.pixels.com/">Prints For Sale</a></p>
        </th>
    </tr>
</table>
<br/>
<br/>
<p id="pic" align="center">Image Goes Here</p>
</code>```

答:
I think you've forgotten about the $ sign on your code.
Your display function should be like this

```<code>function displayImgs(arr){

    if(idx <= arr.length)
    {
        $('#pic').hide();
        $('#pic').html(arr[idx]);
        $('#pic').fadeIn('slow');
        if(idx > arr.length)
        {
            idx = 0;
        }
        else
        {
            idx++;
        }
    };  //button click close
}//displayImgs
</code>```

Also, shouldn't you use one idX for each array?

Body:
I have written the below code to display a selection of images within a
 tag when a certain button is clicked on a page. The Jquery to hide the
 elements on page load works, but the rest of the code does nothing. Can anyone help me figure this out please?

    $(document).ready(function(){
    //Create Array for images
    var vanImgArr = new Array("", "", "", "");
    var sgpImgArr = new Array("", "", "", "");
    var aniImgArr = new Array("", "", "", "");
    var absImgArr = new Array("", "", "", "");
    var clickedId;
    var idx = 0;
    //to display images
    function displayImgs(arr)
    {

        if(idx <= arr.length)
        {
            ('#pic').hide();
            ('#pic').html(arr[idx]);
            ('#pic').fadeIn('slow');
            if(idx > arr.length)
            {
                idx = 0;
            }
            else
            {
                idx++;
            }
        };  //button click close
    }//displayImgs method close

    //on page load
    $('p').hide();

    //More info Action
    $('#more').hover(function(){
        $('#info, #info2').fadeIn('slow');
    });

    //Button Click Action
    $(':button').click(function(){
        clickedId = this.id;
        alert(clickedId); //testing
        switch(clickedId)
        {
            case 'yvr':
                displayImgs(vanImgArr);
                break;

            case 'sgp':
                displayImgs(sgpImgArr);
                break;

            case 'ani':
                displayImgs(aniImgArr);
                break;

            case 'abs':
                displayImgs(absImgArr);
                break;
        }//switch/case close
    });//button click close
});

Here is my HTML code to go with the above

<!DOCTYPE html>

<title>Ricky Deacon CSIS3380-001, Assignment 2, Summer 2017</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css"/>

        Rick Deacon

        Photography Showcase

        Click the corresponding button to display images from your chosen category.

             <input id="van" type="button" name="submit" value="Show Vancouver Images"/>

             <input id="sgp" type="button" name="submit" value="Show Singapore Images"/>

             <input id="ani" type="button" name="submit" value="Show Animal Images"/>

             <input id="abs" type="button" name="submit" value="Show Abstract Images"/>

Rick Deacon's Flickr

More Info and Portfolio Links

Prints For Sale

Image Goes Here

Body:
I think you've forgotten about the $ sign on your code.
Your display function should be like this

function displayImgs(arr){

    if(idx <= arr.length)
    {
        $('#pic').hide();
        $('#pic').html(arr[idx]);
        $('#pic').fadeIn('slow');
        if(idx > arr.length)
        {
            idx = 0;
        }
        else
        {
            idx++;
        }
    };  //button click close
}//displayImgs

Also, shouldn't you use one idX for each array?


问:
Subclassed UIAlertView not drawn correctly in iOS 4.2
I've subclassed an UIAlertView as follow:

```<code>@interface NarrationAlertView : UIAlertView {
    UIImage * backgroundImage; //The image I want as custom background
    UILabel * textualNarrationView; //The test I wanna be displayed on the view
}
</code>```

And implemented it this way :

```<code>- (id)initNarrationViewWithImage:(UIImage *)image{

    if (self = [super init]){
        UILabel * alertTextLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        self.textualNarrationView = alertTextLabel;
        [alertTextLabel release];
        [self addSubview:alertTextLabel];
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    /* Here I draw the image as background */
    CGSize imageSize = self.backgroundImage.size;
    [self.backgroundImage drawInRect:CGRectMake(0, 0, imageSize.width, imageSize.height)];
}

- (void)layoutSubviews {
    /* To fit the text */
    [textualNarrationView sizeToFit];

    CGRect textRect = textualNarrationView.frame;
    textRect.origin.x = (CGRectGetWidth(self.bounds) - CGRectGetWidth(textRect)) / 2;
    textRect.origin.y = (CGRectGetHeight(self.bounds) - CGRectGetHeight(textRect)) / 2;
    textRect.origin.y -= 70;
    textualNarrationView.frame = textRect;
}

- (void)show{
    /* Showing the view */
    [super show];
    CGSize imageSize = self.backgroundImage.size;
    self.bounds = CGRectMake(0, 0, imageSize.width, imageSize.height);
}
</code>```

On the previous versions of iOS (I'm always testing on the simulator) the subclass run fine and when shown it displayed the custom background image drawn correctly and just text upon it, whereas in the 4.2 version it draws the UIAlertView classic background (the blue rounded corners rectangle) on top of my image.

What am I doing wrong? Any suggestion about UIAlertView programming and UIView too will be appreciated.

UPDATE Has anyone got some UIAlertView replacement class to share?

答:
Prior to iOS 4.2 UIAlertView's standard dark blue rounded rectangle was drawn in drawRect. the rounded rectangle could be removed by subclassing UIAlertView and implementing drawRect without calling super. however in 4.2 the rounded rectangle is a UIImageView subview.
the quick, easy (not best) solution: If you are not adding any UIImageView instances to your UIAlertView subclass you can simply remove the default UIImageView that is loaded by observing subview additions:</p>

```<code>- (void)didAddSubview:(UIView *)subview {
  if ([subview isMemberOfClass:[UIImageView class]]) {
    [subview removeFromSuperview];
  }
}
</code>```

Body:
I've subclassed an UIAlertView as follow:

@interface NarrationAlertView : UIAlertView {
    UIImage * backgroundImage; //The image I want as custom background
    UILabel * textualNarrationView; //The test I wanna be displayed on the view
}

And implemented it this way :

- (id)initNarrationViewWithImage:(UIImage *)image{

    if (self = [super init]){
        UILabel * alertTextLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        self.textualNarrationView = alertTextLabel;
        [alertTextLabel release];
        [self addSubview:alertTextLabel];
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    /* Here I draw the image as background */
    CGSize imageSize = self.backgroundImage.size;
    [self.backgroundImage drawInRect:CGRectMake(0, 0, imageSize.width, imageSize.height)];
}

- (void)layoutSubviews {
    /* To fit the text */
    [textualNarrationView sizeToFit];

    CGRect textRect = textualNarrationView.frame;
    textRect.origin.x = (CGRectGetWidth(self.bounds) - CGRectGetWidth(textRect)) / 2;
    textRect.origin.y = (CGRectGetHeight(self.bounds) - CGRectGetHeight(textRect)) / 2;
    textRect.origin.y -= 70;
    textualNarrationView.frame = textRect;
}

- (void)show{
    /* Showing the view */
    [super show];
    CGSize imageSize = self.backgroundImage.size;
    self.bounds = CGRectMake(0, 0, imageSize.width, imageSize.height);
}

On the previous versions of iOS (I'm always testing on the simulator) the subclass run fine and when shown it displayed the custom background image drawn correctly and just text upon it, whereas in the 4.2 version it draws the UIAlertView classic background (the blue rounded corners rectangle) on top of my image.

What am I doing wrong? Any suggestion about UIAlertView programming and UIView too will be appreciated.

UPDATE Has anyone got some UIAlertView replacement class to share?

Body:
Prior to iOS 4.2 UIAlertView's standard dark blue rounded rectangle was drawn in drawRect. the rounded rectangle could be removed by subclassing UIAlertView and implementing drawRect without calling super. however in 4.2 the rounded rectangle is a UIImageView subview.
the quick, easy (not best) solution: If you are not adding any UIImageView instances to your UIAlertView subclass you can simply remove the default UIImageView that is loaded by observing subview additions:

- (void)didAddSubview:(UIView *)subview {
  if ([subview isMemberOfClass:[UIImageView class]]) {
    [subview removeFromSuperview];
  }
}


问:
IIS Rewrite Rule not behaving as expected
I'm trying to route http://www.domain.com/some/url(.*) (everything behind /url) to http://some.other.com/some/url{R:1} (where {R:1} becomes the contents of (.*) in the matched url.

I tried the rule below and all sorts of variations but none seem to rewrite correctly:

```<code><rule name="Reverse Proxy" stopProcessing="true">
    <match url="^some\/url\/(.*)" />
    <action type="Rewrite" url="http://some.other.com/some/url/{R:1}" />
</rule>
</code>```

Any help is greatly appreciated!

答:
I had struggled on this for several days. 10-20 rewrite rule I tried and  reasons of failure are:

If you trying redirecting in VisualStudio(2012/2013/2015) it could not work in actual IIS hosted site as VS generates its own cert while debugging(when you specify in project properties) as well as permission issues are taken care by VS.

The site in IIS should have valid (no copy paste of file from thawte/verisign enabled website or even self signed generated by snk.exe) certificate; please don't assume that without valid cert you can. (self signed (also known as dev cert) in IIS 8 and 10 worked for me; difference between purchased and self signed is here). The certificate should be installed as IIS can have multiple certs but each web site should use its own separate cert.

The site bindings should have both http(80) and https(443)

Now redirection syntax comes in picture; several are out there on Internet; you can get the correct regular expression easily

Another side of story also has to be considered that redirecting can be handle using Global.asax->Application_BeginRequest or ActionFilter in MVC 4/5.

Doing redirection using config or programmatically can lead to different errors(TOO_MANY_REDIRECTS, <validation validateIntegratedModeConfiguration="false" />  <modules runAllManagedModulesForAllRequests="true"> in web.config)

Another gotcha I faced is redirecting from http->https is working fine but I am not able to comeback from https->http;

Consider your scenario(and generally should not mix) out of the available choices

```<code>HttpRedirect::
Request 1 (from client):    Get file.htm
Response 1 (from server): The file is moved, please request the file newFileName.htm
Request 2 (from client):    Get newFileName.htm
Response 2 (from server): Here is the content of newFileName.htm

UrlRewrite::
Request 1 (from client):     Get file.htm
URL Rewriting (on server):   Translate the URL file.htm to file.asp
Web application (on server): Process the request (run any code in file.asp)
Response 1 (from server):    Here is the content of file.htm (note that the client does not know that this is the content of file.asp)
</code>```

whether you need HttpRedirect or UrlRewrite

https://weblogs.asp.net/owscott/rewrite-vs-redirect-what-s-the-difference

Body:
I'm trying to route http://www.domain.com/some/url(.*) (everything behind /url) to http://some.other.com/some/url{R:1} (where {R:1} becomes the contents of (.*) in the matched url.

I tried the rule below and all sorts of variations but none seem to rewrite correctly:

<rule name="Reverse Proxy" stopProcessing="true">
    <match url="^some\/url\/(.*)" />
    <action type="Rewrite" url="http://some.other.com/some/url/{R:1}" />
</rule>

Any help is greatly appreciated!

Body:
I had struggled on this for several days. 10-20 rewrite rule I tried and  reasons of failure are:

If you trying redirecting in VisualStudio(2012/2013/2015) it could not work in actual IIS hosted site as VS generates its own cert while debugging(when you specify in project properties) as well as permission issues are taken care by VS.

The site in IIS should have valid (no copy paste of file from thawte/verisign enabled website or even self signed generated by snk.exe) certificate; please don't assume that without valid cert you can. (self signed (also known as dev cert) in IIS 8 and 10 worked for me; difference between purchased and self signed is here). The certificate should be installed as IIS can have multiple certs but each web site should use its own separate cert.

The site bindings should have both http(80) and https(443)

Now redirection syntax comes in picture; several are out there on Internet; you can get the correct regular expression easily

Another side of story also has to be considered that redirecting can be handle using Global.asax->Application_BeginRequest or ActionFilter in MVC 4/5.

Doing redirection using config or programmatically can lead to different errors(TOO_MANY_REDIRECTS, <validation validateIntegratedModeConfiguration="false" />  <modules runAllManagedModulesForAllRequests="true"> in web.config)

Another gotcha I faced is redirecting from http->https is working fine but I am not able to comeback from https->http;

Consider your scenario(and generally should not mix) out of the available choices

HttpRedirect::
Request 1 (from client):    Get file.htm
Response 1 (from server): The file is moved, please request the file newFileName.htm
Request 2 (from client):    Get newFileName.htm
Response 2 (from server): Here is the content of newFileName.htm

UrlRewrite::
Request 1 (from client):     Get file.htm
URL Rewriting (on server):   Translate the URL file.htm to file.asp
Web application (on server): Process the request (run any code in file.asp)
Response 1 (from server):    Here is the content of file.htm (note that the client does not know that this is the content of file.asp)

whether you need HttpRedirect or UrlRewrite

https://weblogs.asp.net/owscott/rewrite-vs-redirect-what-s-the-difference


问:
1064, "You have an error in your SQL syntax MySQL server version for the right syntax to use near '1select f.name
I am getting this error in django when I am trying hit mysql database. but when I ran this query in db I got proper result my query is like

```<code>"select f.name,scheduleDepart.depart_time,scheduleArrive.arrival_time,ai.name from
                flight as f,airline as ai,flight_schedule as scheduleDepart inner join
                flight_schedule as scheduleArrive on scheduleDepart.flight_id=scheduleArrive.flight_id
                where scheduleArrive.location_id=%d and scheduleDepart.location_id=%d
                 and scheduleArrive.flight_id=f.id and f.airline_code_id=ai.id;""".join(''.join(elems) for elems in data)
</code>```

this is my stack trace

```<code>raceback (most recent call last):
  File "C:\Program Files (x86)\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
    response = get_response(request)
  File "C:\Program Files (x86)\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Program Files (x86)\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "E:\kepsla-workspace\WS\demoWS\flightBooking\booking\views.py", line 30, in flightBooking
    and scheduleArrive.flight_id=f.id and f.airline_code_id=ai.id;""".join(''.join(elems) for elems in data))
  File "C:\Program Files (x86)\lib\site-packages\django\db\backends\utils.py", line 80, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "C:\Program Files (x86)\lib\site-packages\django\db\backends\utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "C:\Program Files (x86)\lib\site-packages\django\db\utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "C:\Program Files (x86)\lib\site-packages\django\utils\six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "C:\Program Files (x86)\lib\site-packages\django\db\backends\utils.py", line 63, in execute
    return self.cursor.execute(sql)
  File "C:\Program Files (x86)\lib\site-packages\django\db\backends\mysql\base.py", line 101, in execute
    return self.cursor.execute(query, args)
  File "C:\Program Files (x86)\lib\site-packages\MySQLdb\cursors.py", line 250, in execute
    self.errorhandler(self, exc, value)
  File "C:\Program Files (x86)\lib\site-packages\MySQLdb\connections.py", line 50, in defaulterrorhandler
    raise errorvalue
  File "C:\Program Files (x86)\lib\site-packages\MySQLdb\cursors.py", line 247, in execute
    res = self._query(query)
  File "C:\Program Files (x86)\lib\site-packages\MySQLdb\cursors.py", line 411, in _query
    rowcount = self._do_query(q)
  File "C:\Program Files (x86)\lib\site-packages\MySQLdb\cursors.py", line 374, in _do_query
    db.query(q)
  File "C:\Program Files (x86)\lib\site-packages\MySQLdb\connections.py", line 292, in query
    _mysql.connection.query(self, query)
django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1select f.name,scheduleDepart.depart_time,scheduleArrive.arrival_time,ai.name fr' at line 1")
[06/Jul/2017 23:28:28] "POST /booking HTTP/1.1" 500 162085
</code>```

any help???
here is python file of view it doesn't have anywhere 1

```<code>def flightBooking(request):
    if request.method=='POST':
        form= SearchForm(request.POST)
        if not form.is_valid():
          return render(request, 'booking/search.html',{'form':form})
        else:
                form.is_valid()
                data=( form.cleaned_data['fromLocation'],form.cleaned_data['toLocation'])
                cursor=connection.cursor()
                cursor.execute("""select f.name,scheduleDepart.depart_time,scheduleArrive.arrival_time,ai.name from
                flight as f,airline as ai,flight_schedule as scheduleDepart inner join
                flight_schedule as scheduleArrive on scheduleDepart.flight_id=scheduleArrive.flight_id
                where scheduleArrive.location_id=%d and scheduleDepart.location_id=%d
                 and scheduleArrive.flight_id=f.id and f.airline_code_id=ai.id;""".join(''.join(elems) for elems in data))
                results=dictFetchAll(cursor)
                return render(results,'booking/searchResult.html')
                #return HttpResponse(results,'booking/searchResult.html')

    def dictFetchAll(cursor):
        "return all rows with column name"
        columns=[col[0] for col in cursor.description]
        return [
                dict(zip(columns,row))
                for row in cursor.fetchall()
            ]
</code>```

EDIT 2:
here is my query after joining datainside date validation

```<code>1select f.name,scheduleDepart.depart_time,scheduleArrive.arrival_time,ai.name from
                flight as f,airline as ai,flight_schedule as scheduleDepart inner join
                flight_schedule as scheduleArrive on scheduleDepart.flight_id=scheduleArrive.flight_id
                where scheduleArrive.location_id=%d and scheduleDepart.location_id=%d
                 and scheduleArrive.flight_id=f.id and f.airline_code_id=ai.id;2
</code>```

答: Django provide a DB based in ORM sytem but if you want continue with raw sql check this https://docs.djangoproject.com/en/1.11/topics/db/sql/</p>

Body:
I am getting this error in django when I am trying hit mysql database. but when I ran this query in db I got proper result my query is like

"select f.name,scheduleDepart.depart_time,scheduleArrive.arrival_time,ai.name from
                flight as f,airline as ai,flight_schedule as scheduleDepart inner join
                flight_schedule as scheduleArrive on scheduleDepart.flight_id=scheduleArrive.flight_id
                where scheduleArrive.location_id=%d and scheduleDepart.location_id=%d
                 and scheduleArrive.flight_id=f.id and f.airline_code_id=ai.id;""".join(''.join(elems) for elems in data)

this is my stack trace

raceback (most recent call last):
  File "C:\Program Files (x86)\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
    response = get_response(request)
  File "C:\Program Files (x86)\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Program Files (x86)\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "E:\kepsla-workspace\WS\demoWS\flightBooking\booking\views.py", line 30, in flightBooking
    and scheduleArrive.flight_id=f.id and f.airline_code_id=ai.id;""".join(''.join(elems) for elems in data))
  File "C:\Program Files (x86)\lib\site-packages\django\db\backends\utils.py", line 80, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "C:\Program Files (x86)\lib\site-packages\django\db\backends\utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "C:\Program Files (x86)\lib\site-packages\django\db\utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "C:\Program Files (x86)\lib\site-packages\django\utils\six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "C:\Program Files (x86)\lib\site-packages\django\db\backends\utils.py", line 63, in execute
    return self.cursor.execute(sql)
  File "C:\Program Files (x86)\lib\site-packages\django\db\backends\mysql\base.py", line 101, in execute
    return self.cursor.execute(query, args)
  File "C:\Program Files (x86)\lib\site-packages\MySQLdb\cursors.py", line 250, in execute
    self.errorhandler(self, exc, value)
  File "C:\Program Files (x86)\lib\site-packages\MySQLdb\connections.py", line 50, in defaulterrorhandler
    raise errorvalue
  File "C:\Program Files (x86)\lib\site-packages\MySQLdb\cursors.py", line 247, in execute
    res = self._query(query)
  File "C:\Program Files (x86)\lib\site-packages\MySQLdb\cursors.py", line 411, in _query
    rowcount = self._do_query(q)
  File "C:\Program Files (x86)\lib\site-packages\MySQLdb\cursors.py", line 374, in _do_query
    db.query(q)
  File "C:\Program Files (x86)\lib\site-packages\MySQLdb\connections.py", line 292, in query
    _mysql.connection.query(self, query)
django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1select f.name,scheduleDepart.depart_time,scheduleArrive.arrival_time,ai.name fr' at line 1")
[06/Jul/2017 23:28:28] "POST /booking HTTP/1.1" 500 162085

any help???
here is python file of view it doesn't have anywhere 1

def flightBooking(request):
    if request.method=='POST':
        form= SearchForm(request.POST)
        if not form.is_valid():
          return render(request, 'booking/search.html',{'form':form})
        else:
                form.is_valid()
                data=( form.cleaned_data['fromLocation'],form.cleaned_data['toLocation'])
                cursor=connection.cursor()
                cursor.execute("""select f.name,scheduleDepart.depart_time,scheduleArrive.arrival_time,ai.name from
                flight as f,airline as ai,flight_schedule as scheduleDepart inner join
                flight_schedule as scheduleArrive on scheduleDepart.flight_id=scheduleArrive.flight_id
                where scheduleArrive.location_id=%d and scheduleDepart.location_id=%d
                 and scheduleArrive.flight_id=f.id and f.airline_code_id=ai.id;""".join(''.join(elems) for elems in data))
                results=dictFetchAll(cursor)
                return render(results,'booking/searchResult.html')
                #return HttpResponse(results,'booking/searchResult.html')

    def dictFetchAll(cursor):
        "return all rows with column name"
        columns=[col[0] for col in cursor.description]
        return [
                dict(zip(columns,row))
                for row in cursor.fetchall()
            ]

EDIT 2:
here is my query after joining datainside date validation

1select f.name,scheduleDepart.depart_time,scheduleArrive.arrival_time,ai.name from
                flight as f,airline as ai,flight_schedule as scheduleDepart inner join
                flight_schedule as scheduleArrive on scheduleDepart.flight_id=scheduleArrive.flight_id
                where scheduleArrive.location_id=%d and scheduleDepart.location_id=%d
                 and scheduleArrive.flight_id=f.id and f.airline_code_id=ai.id;2


问:
How to stop gamemaker object from leaving tracer
I have just started to use gamemaker and have made my first very basic game, it's just a circle that moves with the arrow keys.

My problem is that when it moves it leaves behind an image of itself in every space that it occupies.
All I have is $motion_set(0, 5);$ as the action.

Any help is much appreciated!

答:
I am not really familiar with Studio 2 but in 1.4 your code causes my sprite to move across the screen without leaving anything behind. Are you sure there is nothing else in your code. It seems to be re-creating a new sprite either at the old location or  creating a new object at the old location.

You can also you x += (the ammount of pixels you want to move) This works for x and y.

Thanks, Jonathan Greene


问:
Preventing subelement from exceeding parent's height?
Given this code:

```<code>.yourHeaderContainer {background-color:#EEEEEE; line-height:34px; height:34px;}

.yourHeaderContainer .challengeSomeone {float:right; margin-right:10px; font-size:12px; font-weight:bold; padding:0px 0px 0px 0px;}
</code>```

Is there any way I can prevent the child element from exceeding the line height (or height) of the parent container?

答: Do an overflow:hidden on the parent (overflow-y:hidden should work too).</p>

Body:
Given this code:

.yourHeaderContainer {background-color:#EEEEEE; line-height:34px; height:34px;}

.yourHeaderContainer .challengeSomeone {float:right; margin-right:10px; font-size:12px; font-weight:bold; padding:0px 0px 0px 0px;}

Is there any way I can prevent the child element from exceeding the line height (or height) of the parent container?


问:
Find all subdocuments which meet a criteria
I would like to get only those subdocuments from my two object arrays file_history and uploaded_files which meet a criteira. Even though I've found this stackoverflow answer #2 (Mongoose - finding subdocuments by criteria)  it doesn't work as desired for me or I am missing something.

```<code>var projectId = req.params.projectId
var uploadId = req.body.uploadId

let populateQuery = [
    {path: 'owner'},
    {path: 'uploaded_files.file', match: {upload_id: uploadId}},
    {path: 'file_history.file', match: {upload_id: uploadId}}
]

Project.findOne({ project_id: projectId }).populate(populateQuery).then(project => {
    console.log(project)
})
</code>```

My document looks like this:

```<code>{
    "_id" : ObjectId("5935a41f12f3fac949a5f925"),
    "project_id" : 13,
    "updated_at" : ISODate("2017-07-05T21:45:46.754Z"),
    "created_at" : ISODate("2017-06-05T18:34:07.150Z"),
    "owner" : ObjectId("591eea4439e1ce33b47e73c3"),
    "name" : "RDemo project",
    "uploaded_files" : [
        {
            "display_name" : "Log_28-6-2017_14-17-53-562.txt",
            "file" : ObjectId("595c4c4f3ae2470700ea07e2"),
            "upload_id" : ObjectId("595c0f7ea1d20247285be5f5"),
            "created_at" : ISODate("2017-07-05T02:17:51.000Z")
        },
        {
            "display_name" : "Coon.png",
            "file" : ObjectId("595c4c553ae2470700ea07e4"),
            "upload_id" : ObjectId("595c4c553ae2470700ea07e5"),
            "created_at" : ISODate("2017-07-05T02:17:57.000Z")
        }
    ],
    "file_history" : [
        {
            "display_name" : "account working.txt",
            "file" : ObjectId("595c0f7ea1d20247285be5f4"),
            "upload_id" : ObjectId("595c0f7ea1d20247285be5f5"),
            "created_at" : ISODate("2017-07-04T21:58:22.000Z")
        },
        {
            "display_name" : "Log_28-6-2017_14-17-53-562.txt",
            "file" : ObjectId("595c4c4f3ae2470700ea07e2"),
            "upload_id" : ObjectId("595c0f7ea1d20247285be5f5"),
            "created_at" : ISODate("2017-07-05T02:17:51.000Z")
        }
    ]
}
</code>```

It will print the project with all it's subdocuments in file_history and uploaded_files. However I only want to get those subdocuments which match the given upload_id. What am I doing wrong?

Edit: This question refers to solving it using mongoose. I wasn't able to use the aggregate statement from this question (Retrieve only the queried element in an object array in MongoDB collection) in Mongoose as it returned an empty array, however I was able to run it via MongoDB and it returned indeed the desired result. That's the code I've tried:

```<code>    let projectId = req.params.projectId // Project ID is an integer and no objectId
    let uploadId = new mongoose.Types.ObjectId(req.body.uploadId)
    console.log(`ProjectID: ${projectId}, uploadId: ${uploadId}, params: ${req.body.uploadId}`)

    let populateQuery = [
        {path: 'owner'},
        {path: 'uploaded_files.file'},
        {path: 'file_history.file'}
    ]

    Project.aggregate(
        {$match: {"project_id": projectId}},
        {$project: {
            uploaded_files: {$filter: {
                    input: '$uploaded_files',
                    as: 'uploadedFile',
                    cond: {$eq: ['$$uploadedFile.upload_id', uploadId]}
                }}
            }
        }
    ).then(project => {
        console.log(project)
})
</code>```

console.log returns: ProjectID: 13, uploadId: 595c0f7ea1d20247285be5f5, params: 595c0f7ea1d20247285be5f5 which is correct (ids are existent)

答:
You are doing something horribly wrong and it unclear what that is. The best way to show you is therefore by example.

Also note that $filter is not even needed for a "single match" and a standard positional projection will simply just do here:

```<code>const async = require('async'),
      mongoose = require('mongoose'),
      Schema = mongoose.Schema,
      ObjectId = require('mongodb').ObjectID

mongoose.set('debug',true)
mongoose.Promise = global.Promise;

mongoose.connect('mongodb://localhost/test');

const doc =
{
    "_id" : ObjectId("5935a41f12f3fac949a5f925"),
    "project_id" : 13,
    "updated_at" : new Date("2017-07-05T21:45:46.754Z"),
    "created_at" : new Date("2017-06-05T18:34:07.150Z"),
    "owner" : ObjectId("591eea4439e1ce33b47e73c3"),
    "name" : "RDemo project",
    "uploaded_files" : [
        {
            "display_name" : "Log_28-6-2017_14-17-53-562.txt",
            "file" : ObjectId("595c4c4f3ae2470700ea07e2"),
            "upload_id" : ObjectId("595c0f7ea1d20247285be5f5"),
            "created_at" : new Date("2017-07-05T02:17:51.000Z")
        },
        {
            "display_name" : "Coon.png",
            "file" : ObjectId("595c4c553ae2470700ea07e4"),
            "upload_id" : ObjectId("595c4c553ae2470700ea07e5"),
            "created_at" : new Date("2017-07-05T02:17:57.000Z")
        }
    ],
    "file_history" : [
        {
            "display_name" : "account working.txt",
            "file" : ObjectId("595c0f7ea1d20247285be5f4"),
            "upload_id" : ObjectId("595c0f7ea1d20247285be5f5"),
            "created_at" : new Date("2017-07-04T21:58:22.000Z")
        },
        {
            "display_name" : "Log_28-6-2017_14-17-53-562.txt",
            "file" : ObjectId("595c4c4f3ae2470700ea07e2"),
            "upload_id" : ObjectId("595c0f7ea1d20247285be5f5"),
            "created_at" : new Date("2017-07-05T02:17:51.000Z")
        },
        {
            "display_name" : "Coon.png",
            "file" : ObjectId("595c4c553ae2470700ea07e4"),
            "upload_id" : ObjectId("595c4c553ae2470700ea07e5"),
            "created_at" : new Date("2017-07-05T02:17:57.000Z")
        },
        {
            "display_name" : "Coon.png",
            "file" : ObjectId("595c4c553ae2470700ea07e4"),
            "upload_id" : ObjectId("595c4c553ae2470700ea07e5"),
            "created_at" : new Date("2017-07-05T02:17:57.000Z")
        }
    ]
};

const Test = mongoose.model('Test', new Schema({}, { strict: false }) );

function log(data) {
  console.log(JSON.stringify(data, undefined, 2))
}

async.series(
  [
    // Clean data
    (callback) =>
      async.each(mongoose.models,(model,callback) =>
        model.remove({},callback),callback),

    // Insert data
    (callback) => Test.insertMany(doc,callback),

    // Correct usage of $filter
    (callback) =>
      Test.aggregate(
        [
          { "$match": { "project_id": 13 } },
          { "$addFields": {
            "uploaded_files": {
              "$filter": {
                "input": "$uploaded_files",
                "as": "f",
                "cond": {
                  "$eq": [
                    "$$f.upload_id", ObjectId("595c0f7ea1d20247285be5f5")
                  ]
                }
              }
            },
            "file_history": {
              "$filter": {
                "input": "$file_history",
                "as": "f",
                "cond": {
                  "$eq": [
                    "$$f.upload_id", ObjectId("595c0f7ea1d20247285be5f5")
                  ]
                }
              }
            }

          }}
        ],
        (err,results) => {
          if (err) callback(err);
          log(results);
          callback();
        }
      ),

      // Just a normal positional project for 1 match
      (callback) => Test.findOne(
        { "uploaded_files.upload_id": ObjectId("595c0f7ea1d20247285be5f5") },
        { "uploaded_files.$": 1 },
        (err,result) => {
          if (err) callback(err);
          log(result);
          callback();
        }
      )

  ],
  (err) => {
    if (err) throw err;
    mongoose.disconnect();
  }
)
</code>```

Produces the desired output:

```<code>[
  {
    "_id": "5935a41f12f3fac949a5f925",
    "__v": 0,
    "project_id": 13,
    "updated_at": "2017-07-05T21:45:46.754Z",
    "created_at": "2017-06-05T18:34:07.150Z",
    "owner": "591eea4439e1ce33b47e73c3",
    "name": "RDemo project",
    "uploaded_files": [
      {
        "created_at": "2017-07-05T02:17:51.000Z",
        "upload_id": "595c0f7ea1d20247285be5f5",
        "file": "595c4c4f3ae2470700ea07e2",
        "display_name": "Log_28-6-2017_14-17-53-562.txt"
      }
    ],
    "file_history": [
      {
        "created_at": "2017-07-04T21:58:22.000Z",
        "upload_id": "595c0f7ea1d20247285be5f5",
        "file": "595c0f7ea1d20247285be5f4",
        "display_name": "account working.txt"
      },
      {
        "created_at": "2017-07-05T02:17:51.000Z",
        "upload_id": "595c0f7ea1d20247285be5f5",
        "file": "595c4c4f3ae2470700ea07e2",
        "display_name": "Log_28-6-2017_14-17-53-562.txt"
      }
    ]
  }
]
Mongoose: tests.findOne({ 'uploaded_files.upload_id': ObjectId("595c0f7ea1d20247285be5f5") }, { fields: { 'uploaded_files.$': 1 } })
{
  "_id": "5935a41f12f3fac949a5f925",
  "uploaded_files": [
    {
      "display_name": "Log_28-6-2017_14-17-53-562.txt",
      "file": "595c4c4f3ae2470700ea07e2",
      "upload_id": "595c0f7ea1d20247285be5f5",
      "created_at": "2017-07-05T02:17:51.000Z"
    }
  ]
}
</code>```

Body:
I would like to get only those subdocuments from my two object arrays file_history and uploaded_files which meet a criteira. Even though I've found this stackoverflow answer #2 (Mongoose - finding subdocuments by criteria)  it doesn't work as desired for me or I am missing something.

var projectId = req.params.projectId
var uploadId = req.body.uploadId

let populateQuery = [
    {path: 'owner'},
    {path: 'uploaded_files.file', match: {upload_id: uploadId}},
    {path: 'file_history.file', match: {upload_id: uploadId}}
]

Project.findOne({ project_id: projectId }).populate(populateQuery).then(project => {
    console.log(project)
})

My document looks like this:

{
    "_id" : ObjectId("5935a41f12f3fac949a5f925"),
    "project_id" : 13,
    "updated_at" : ISODate("2017-07-05T21:45:46.754Z"),
    "created_at" : ISODate("2017-06-05T18:34:07.150Z"),
    "owner" : ObjectId("591eea4439e1ce33b47e73c3"),
    "name" : "RDemo project",
    "uploaded_files" : [
        {
            "display_name" : "Log_28-6-2017_14-17-53-562.txt",
            "file" : ObjectId("595c4c4f3ae2470700ea07e2"),
            "upload_id" : ObjectId("595c0f7ea1d20247285be5f5"),
            "created_at" : ISODate("2017-07-05T02:17:51.000Z")
        },
        {
            "display_name" : "Coon.png",
            "file" : ObjectId("595c4c553ae2470700ea07e4"),
            "upload_id" : ObjectId("595c4c553ae2470700ea07e5"),
            "created_at" : ISODate("2017-07-05T02:17:57.000Z")
        }
    ],
    "file_history" : [
        {
            "display_name" : "account working.txt",
            "file" : ObjectId("595c0f7ea1d20247285be5f4"),
            "upload_id" : ObjectId("595c0f7ea1d20247285be5f5"),
            "created_at" : ISODate("2017-07-04T21:58:22.000Z")
        },
        {
            "display_name" : "Log_28-6-2017_14-17-53-562.txt",
            "file" : ObjectId("595c4c4f3ae2470700ea07e2"),
            "upload_id" : ObjectId("595c0f7ea1d20247285be5f5"),
            "created_at" : ISODate("2017-07-05T02:17:51.000Z")
        }
    ]
}

It will print the project with all it's subdocuments in file_history and uploaded_files. However I only want to get those subdocuments which match the given upload_id. What am I doing wrong?

Edit: This question refers to solving it using mongoose. I wasn't able to use the aggregate statement from this question (Retrieve only the queried element in an object array in MongoDB collection) in Mongoose as it returned an empty array, however I was able to run it via MongoDB and it returned indeed the desired result. That's the code I've tried:

    let projectId = req.params.projectId // Project ID is an integer and no objectId
    let uploadId = new mongoose.Types.ObjectId(req.body.uploadId)
    console.log(`ProjectID: ${projectId}, uploadId: ${uploadId}, params: ${req.body.uploadId}`)

    let populateQuery = [
        {path: 'owner'},
        {path: 'uploaded_files.file'},
        {path: 'file_history.file'}
    ]

    Project.aggregate(
        {$match: {"project_id": projectId}},
        {$project: {
            uploaded_files: {$filter: {
                    input: '$uploaded_files',
                    as: 'uploadedFile',
                    cond: {$eq: ['$$uploadedFile.upload_id', uploadId]}
                }}
            }
        }
    ).then(project => {
        console.log(project)
})

console.log returns: ProjectID: 13, uploadId: 595c0f7ea1d20247285be5f5, params: 595c0f7ea1d20247285be5f5 which is correct (ids are existent)

Body:
You are doing something horribly wrong and it unclear what that is. The best way to show you is therefore by example.

Also note that $filter is not even needed for a "single match" and a standard positional projection will simply just do here:

const async = require('async'),
      mongoose = require('mongoose'),
      Schema = mongoose.Schema,
      ObjectId = require('mongodb').ObjectID

mongoose.set('debug',true)
mongoose.Promise = global.Promise;

mongoose.connect('mongodb://localhost/test');

const doc =
{
    "_id" : ObjectId("5935a41f12f3fac949a5f925"),
    "project_id" : 13,
    "updated_at" : new Date("2017-07-05T21:45:46.754Z"),
    "created_at" : new Date("2017-06-05T18:34:07.150Z"),
    "owner" : ObjectId("591eea4439e1ce33b47e73c3"),
    "name" : "RDemo project",
    "uploaded_files" : [
        {
            "display_name" : "Log_28-6-2017_14-17-53-562.txt",
            "file" : ObjectId("595c4c4f3ae2470700ea07e2"),
            "upload_id" : ObjectId("595c0f7ea1d20247285be5f5"),
            "created_at" : new Date("2017-07-05T02:17:51.000Z")
        },
        {
            "display_name" : "Coon.png",
            "file" : ObjectId("595c4c553ae2470700ea07e4"),
            "upload_id" : ObjectId("595c4c553ae2470700ea07e5"),
            "created_at" : new Date("2017-07-05T02:17:57.000Z")
        }
    ],
    "file_history" : [
        {
            "display_name" : "account working.txt",
            "file" : ObjectId("595c0f7ea1d20247285be5f4"),
            "upload_id" : ObjectId("595c0f7ea1d20247285be5f5"),
            "created_at" : new Date("2017-07-04T21:58:22.000Z")
        },
        {
            "display_name" : "Log_28-6-2017_14-17-53-562.txt",
            "file" : ObjectId("595c4c4f3ae2470700ea07e2"),
            "upload_id" : ObjectId("595c0f7ea1d20247285be5f5"),
            "created_at" : new Date("2017-07-05T02:17:51.000Z")
        },
        {
            "display_name" : "Coon.png",
            "file" : ObjectId("595c4c553ae2470700ea07e4"),
            "upload_id" : ObjectId("595c4c553ae2470700ea07e5"),
            "created_at" : new Date("2017-07-05T02:17:57.000Z")
        },
        {
            "display_name" : "Coon.png",
            "file" : ObjectId("595c4c553ae2470700ea07e4"),
            "upload_id" : ObjectId("595c4c553ae2470700ea07e5"),
            "created_at" : new Date("2017-07-05T02:17:57.000Z")
        }
    ]
};

const Test = mongoose.model('Test', new Schema({}, { strict: false }) );

function log(data) {
  console.log(JSON.stringify(data, undefined, 2))
}

async.series(
  [
    // Clean data
    (callback) =>
      async.each(mongoose.models,(model,callback) =>
        model.remove({},callback),callback),

    // Insert data
    (callback) => Test.insertMany(doc,callback),

    // Correct usage of $filter
    (callback) =>
      Test.aggregate(
        [
          { "$match": { "project_id": 13 } },
          { "$addFields": {
            "uploaded_files": {
              "$filter": {
                "input": "$uploaded_files",
                "as": "f",
                "cond": {
                  "$eq": [
                    "$$f.upload_id", ObjectId("595c0f7ea1d20247285be5f5")
                  ]
                }
              }
            },
            "file_history": {
              "$filter": {
                "input": "$file_history",
                "as": "f",
                "cond": {
                  "$eq": [
                    "$$f.upload_id", ObjectId("595c0f7ea1d20247285be5f5")
                  ]
                }
              }
            }

          }}
        ],
        (err,results) => {
          if (err) callback(err);
          log(results);
          callback();
        }
      ),

      // Just a normal positional project for 1 match
      (callback) => Test.findOne(
        { "uploaded_files.upload_id": ObjectId("595c0f7ea1d20247285be5f5") },
        { "uploaded_files.$": 1 },
        (err,result) => {
          if (err) callback(err);
          log(result);
          callback();
        }
      )

  ],
  (err) => {
    if (err) throw err;
    mongoose.disconnect();
  }
)

Produces the desired output:

[
  {
    "_id": "5935a41f12f3fac949a5f925",
    "__v": 0,
    "project_id": 13,
    "updated_at": "2017-07-05T21:45:46.754Z",
    "created_at": "2017-06-05T18:34:07.150Z",
    "owner": "591eea4439e1ce33b47e73c3",
    "name": "RDemo project",
    "uploaded_files": [
      {
        "created_at": "2017-07-05T02:17:51.000Z",
        "upload_id": "595c0f7ea1d20247285be5f5",
        "file": "595c4c4f3ae2470700ea07e2",
        "display_name": "Log_28-6-2017_14-17-53-562.txt"
      }
    ],
    "file_history": [
      {
        "created_at": "2017-07-04T21:58:22.000Z",
        "upload_id": "595c0f7ea1d20247285be5f5",
        "file": "595c0f7ea1d20247285be5f4",
        "display_name": "account working.txt"
      },
      {
        "created_at": "2017-07-05T02:17:51.000Z",
        "upload_id": "595c0f7ea1d20247285be5f5",
        "file": "595c4c4f3ae2470700ea07e2",
        "display_name": "Log_28-6-2017_14-17-53-562.txt"
      }
    ]
  }
]
Mongoose: tests.findOne({ 'uploaded_files.upload_id': ObjectId("595c0f7ea1d20247285be5f5") }, { fields: { 'uploaded_files.$': 1 } })
{
  "_id": "5935a41f12f3fac949a5f925",
  "uploaded_files": [
    {
      "display_name": "Log_28-6-2017_14-17-53-562.txt",
      "file": "595c4c4f3ae2470700ea07e2",
      "upload_id": "595c0f7ea1d20247285be5f5",
      "created_at": "2017-07-05T02:17:51.000Z"
    }
  ]
}


问:
How to make 'submit' button disabled?
How to disable the "Submit" button until the form is valid?

Does angular2 have an equivalent to ng-disabled that can be used on the Submit button? (ng-disabled doesn't work for me.)

答:
Here is a working example (you'll have to trust me that there's a submit() method on the controller - it prints an Object, like {user: 'abc'} if 'abc' is entered in the input field):

```<code><form #loginForm="ngForm" (ngSubmit)="submit(loginForm.value)">
    <input type="text" name="user" ngModel required>
    <button  type="submit"  [disabled]="loginForm.invalid">
        Submit
    </button>
</form>
</code>```

As you can see:

don't use loginForm.form, just use loginForm

loginForm.invalid works as well as !loginForm.valid

if you want submit() to be passed the correct value(s), the input element should have name and ngModel attributes

Also, this is when you're NOT using the new FormBuilder, which I recommend. Things are very different when using FormBuilder.

Title: How to make 'submit' button disabled?

Body:
Here is a working example (you'll have to trust me that there's a submit() method on the controller - it prints an Object, like {user: 'abc'} if 'abc' is entered in the input field):

<form #loginForm="ngForm" (ngSubmit)="submit(loginForm.value)">
    <input type="text" name="user" ngModel required>
    <button  type="submit"  [disabled]="loginForm.invalid">
        Submit
    </button>
</form>

As you can see:

don't use loginForm.form, just use loginForm

loginForm.invalid works as well as !loginForm.valid

if you want submit() to be passed the correct value(s), the input element should have name and ngModel attributes

Also, this is when you're NOT using the new FormBuilder, which I recommend. Things are very different when using FormBuilder.


问:
Akka: How to combine OneForOneStrategy and AllForOneStrategy
If I define the supervisor strategy for an actor in Scala, how can I use both the OneForOneStrategy and the AllForOneStrategy? Is there a simple way to combine them or do I have to define a custom SupervisorStrategy?
Here is an example:

```<code>class MyActor extends Actor {
  override val supervisorStrategy = OneForOneStrategy() {
    case _: NullPointerException  => Restart
    case _: FileNotFoundException => Restart // here I want to restart all children
    case _: Exception             => Escalate
  }
}
</code>```

If I have to write my own supervisor strategy, how can I do this? I found no example for that.

答:
You would have to define a custom supervisor strategy. For your specific use case, the following custom strategy would work:

```<code>package akka.actor

import java.io.FileNotFoundException
import scala.concurrent.duration._

case class CustomStrategy(
  maxNrOfRetries:              Int      = -1,
  withinTimeRange:             Duration = Duration.Inf,
  override val loggingEnabled: Boolean  = true)(val decider: SupervisorStrategy.Decider)
  extends SupervisorStrategy {

  import SupervisorStrategy._

  private val retriesWindow = (maxNrOfRetriesOption(maxNrOfRetries), withinTimeRangeOption(withinTimeRange).map(_.toMillis.toInt))

  def handleChildTerminated(context: ActorContext, child: ActorRef, children: Iterable[ActorRef]): Unit = ()

  def processFailure(context: ActorContext, restart: Boolean, child: ActorRef, cause: Throwable, stats: ChildRestartStats, children: Iterable[ChildRestartStats]): Unit = {
    if (cause.isInstanceOf[FileNotFoundException]) {
      // behave like AllForOneStrategy
      if (children.nonEmpty) {
        if (restart && children.forall(_.requestRestartPermission(retriesWindow)))
          children foreach (crs ⇒ restartChild(crs.child, cause, suspendFirst = (crs.child != child)))
        else
          for (c ← children) context.stop(c.child)
      }
    } else {
      // behave like OneForOneStrategy
      if (restart && stats.requestRestartPermission(retriesWindow))
        restartChild(child, cause, suspendFirst = false)
      else
        context.stop(child)
    }
  }
}
</code>```

Here is a gist that tests the above strategy. The spec creates a supervisor that uses CustomStrategy and it creates two children. When one child throws a NullPointerException, only that child is restarted; when a child throws a FileNotFoundException, both children are restarted.

A few notes about the custom strategy:

It extends SupervisorStrategy and is modeled after the existing strategies defined here.

It is defined inside the akka.actor package to have access to the package-private members there.

processFailure, one of the methods that must be overridden in classes that extend SupervisorStrategy, is called on Restart and Stop, so for your scenario, we define the custom behavior there.

Body:
If I define the supervisor strategy for an actor in Scala, how can I use both the OneForOneStrategy and the AllForOneStrategy? Is there a simple way to combine them or do I have to define a custom SupervisorStrategy?
Here is an example:

class MyActor extends Actor {
  override val supervisorStrategy = OneForOneStrategy() {
    case _: NullPointerException  => Restart
    case _: FileNotFoundException => Restart // here I want to restart all children
    case _: Exception             => Escalate
  }
}

If I have to write my own supervisor strategy, how can I do this? I found no example for that.

Body:
You would have to define a custom supervisor strategy. For your specific use case, the following custom strategy would work:

package akka.actor

import java.io.FileNotFoundException
import scala.concurrent.duration._

case class CustomStrategy(
  maxNrOfRetries:              Int      = -1,
  withinTimeRange:             Duration = Duration.Inf,
  override val loggingEnabled: Boolean  = true)(val decider: SupervisorStrategy.Decider)
  extends SupervisorStrategy {

  import SupervisorStrategy._

  private val retriesWindow = (maxNrOfRetriesOption(maxNrOfRetries), withinTimeRangeOption(withinTimeRange).map(_.toMillis.toInt))

  def handleChildTerminated(context: ActorContext, child: ActorRef, children: Iterable[ActorRef]): Unit = ()

  def processFailure(context: ActorContext, restart: Boolean, child: ActorRef, cause: Throwable, stats: ChildRestartStats, children: Iterable[ChildRestartStats]): Unit = {
    if (cause.isInstanceOf[FileNotFoundException]) {
      // behave like AllForOneStrategy
      if (children.nonEmpty) {
        if (restart && children.forall(_.requestRestartPermission(retriesWindow)))
          children foreach (crs ⇒ restartChild(crs.child, cause, suspendFirst = (crs.child != child)))
        else
          for (c ← children) context.stop(c.child)
      }
    } else {
      // behave like OneForOneStrategy
      if (restart && stats.requestRestartPermission(retriesWindow))
        restartChild(child, cause, suspendFirst = false)
      else
        context.stop(child)
    }
  }
}

Here is a gist that tests the above strategy. The spec creates a supervisor that uses CustomStrategy and it creates two children. When one child throws a NullPointerException, only that child is restarted; when a child throws a FileNotFoundException, both children are restarted.

A few notes about the custom strategy:

It extends SupervisorStrategy and is modeled after the existing strategies defined here.

It is defined inside the akka.actor package to have access to the package-private members there.

processFailure, one of the methods that must be overridden in classes that extend SupervisorStrategy, is called on Restart and Stop, so for your scenario, we define the custom behavior there.