问:
read matrix issue C language
This code should read and display a matrix. But it doesnt work, I cant find the problem.  Why it doesnt work?

```<code>#include <stdio.h>

#define MAX 100

void read_matrix(int a[MAX][MAX], int n)
{
    int i, j;

    scanf("%d", &n);
    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++)
            scanf("%d", &a[i][j]);
}

int main(void)
{
    int a[MAX][MAX], n = 1, i, j;

    read_matrix(a, n);

    for(i = 0; i < n; i++) {
        for (j = 0; j < n; j++)
            printf("%d ", a[i][j]);
        printf("\n");
    }

    return 0;
}
</code>```

For input:

```<code>2
1 2
3 4
</code>```

The output is:

```<code>1
</code>```

答:
First of all, let's deal with a fact "In C there is nothing called pass by reference".

But yes we emulate that with what is available in C, that is pass by value.

So in the first case there are things that happened

You call the function like this read_matrix(a, n);

A copy of the variable is there in read_matrix.

We make changes to the copy.

Function ends and story ends there. That local variable's scope ends. It is not alive now.

You come back to main(). Do you expect to see any change in n? Nope. Because all change was there in read_matrix.

Now to change that we write it this way.

```<code>void read_matrix(int a[MAX][MAX], int* nn)
{
    if( scanf("%d", nn) != 1){
        fprintf(stderr,"Error in input");
        exit(1);
    }
    for (size_t i = 0; i < *nn; i++)
        for (size_t j = 0; j < *nn; j++)
            if( scanf("%d", &a[i][j]) != 1){
                fprintf(stderr,"Error in input");
                exit(1);
            }
}
</code>```

Now here also couple of things happened

You pass the &n or the address of n.

Then nn is a local variable (local to read_matrix) containing the address of n.

scanf() wants the address of what it will write something.

We pass the address of n or content of nn.

Then scanf() writes where? In the memory of n. So n in main() changes.

Now we want to get while looping the value of n or the value in address of n or the value in the address contained by nn.

So we use * on nn. Or *nn.

Now you back to main() and the local variable nn is not there and it's lifetime ended when the function read_matrix ended.

You see the changed value in n.

Do you see any difference in two method?

In one we pass the value. In another we pass as value the address of n.

Both are pass by value. But in second method due to the side effect of accessing memory we see he change in main(). Story ends.

Title: read matrix issue C language

Body:
This code should read and display a matrix. But it doesnt work, I cant find the problem.  Why it doesnt work?

#include <stdio.h>

#define MAX 100

void read_matrix(int a[MAX][MAX], int n)
{
    int i, j;

    scanf("%d", &n);
    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++)
            scanf("%d", &a[i][j]);
}

int main(void)
{
    int a[MAX][MAX], n = 1, i, j;

    read_matrix(a, n);

    for(i = 0; i < n; i++) {
        for (j = 0; j < n; j++)
            printf("%d ", a[i][j]);
        printf("\n");
    }

    return 0;
}

For input:

2
1 2
3 4

The output is:

1

Body:
First of all, let's deal with a fact "In C there is nothing called pass by reference".

But yes we emulate that with what is available in C, that is pass by value.

So in the first case there are things that happened

You call the function like this read_matrix(a, n);

A copy of the variable is there in read_matrix.

We make changes to the copy.

Function ends and story ends there. That local variable's scope ends. It is not alive now.

You come back to main(). Do you expect to see any change in n? Nope. Because all change was there in read_matrix.

Now to change that we write it this way.

void read_matrix(int a[MAX][MAX], int* nn)
{
    if( scanf("%d", nn) != 1){
        fprintf(stderr,"Error in input");
        exit(1);
    }
    for (size_t i = 0; i < *nn; i++)
        for (size_t j = 0; j < *nn; j++)
            if( scanf("%d", &a[i][j]) != 1){
                fprintf(stderr,"Error in input");
                exit(1);
            }
}

Now here also couple of things happened

You pass the &n or the address of n.

Then nn is a local variable (local to read_matrix) containing the address of n.

scanf() wants the address of what it will write something.

We pass the address of n or content of nn.

Then scanf() writes where? In the memory of n. So n in main() changes.

Now we want to get while looping the value of n or the value in address of n or the value in the address contained by nn.

So we use * on nn. Or *nn.

Now you back to main() and the local variable nn is not there and it's lifetime ended when the function read_matrix ended.

You see the changed value in n.

Do you see any difference in two method?

In one we pass the value. In another we pass as value the address of n.

Both are pass by value. But in second method due to the side effect of accessing memory we see he change in main(). Story ends.


来源: stackexchange

问:
Unable to read file using java and smbj on shared drive
I am trying to use the SMBJ jar (https://github.com/hierynomus/smbj) to fetch a file from shared drive. I am able to connect to the shared disk. After the connect, any operation I perform is throwing exception.

For my shared drive location: //x.x.x.x/containing/folder/filename.txt, I am using the parameters as:

```<code>//SERVER_ADDRESS = x.x.x.x
//SHARE_NAME = /containing/folder/
//FILE_NAME = filename.txt
//LOCAL_PATH = "D:\\";

    SMBClient client = new SMBClient();
    try (Connection connection = client.connect(SERVER_ADDRESS)) {
        AuthenticationContext ac = new AuthenticationContext(USERNAME, PASSWORD.toCharArray(), DOMAIN);
        Session session = connection.authenticate(ac);
        // Connect to Share
        try (DiskShare share = (DiskShare) session.connectShare(SHARE_NAME)) {
            Set<SMB2ShareAccess> s = new HashSet<>();
            s.add(SMB2ShareAccess.ALL.iterator().next()); // this is to get READ only
            com.hierynomus.smbj.share.File remoteSmbjFile =  share.openFile(SHARE_NAME+FILE_NAME, EnumSet.of(AccessMask.GENERIC_READ), null, s, null, null);
            java.io.File dest = new java.io.File(LOCAL_PATH + FILE_NAME);
            try (InputStream is = remoteSmbjFile.getInputStream();
                    OutputStream os = new FileOutputStream(dest);) {
                byte[] buffer = new byte[1024];
                int length;
                while ((length = is.read(buffer)) > 0) {
                    os.write(buffer, 0, length);
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        LOGGER.error("", e);
        return "ERROR";
    } catch (Exception e) {
        e.printStackTrace();
        LOGGER.error("", e);
        return "ERROR";
    }
</code>```

I am getting the exception as below. I think that I am not getting the right combination for the parameters.

```<code>com.hierynomus.mssmb2.SMBApiException: STATUS_INVALID_PARAMETER(3221225485/3221225485): Create failed for \containing\folder\
    at com.hierynomus.smbj.share.Share.receive(Share.java:364)
    at com.hierynomus.smbj.share.Share.sendReceive(Share.java:344)
    at com.hierynomus.smbj.share.Share.createFile(Share.java:136)
    at com.hierynomus.smbj.share.DiskShare.open(DiskShare.java:59)
    at com.hierynomus.smbj.share.DiskShare.openDirectory(DiskShare.java:82)
    at com.hierynomus.smbj.share.DiskShare.list(DiskShare.java:169)
    at com.hierynomus.smbj.share.DiskShare.list(DiskShare.java:151)
</code>```

I am unable to get what is wrong here. Can you please suggest what I am missing here.

答:
The share name should not contain a \. It should be set to containing in your example. The file name to open should be folder\filename.txt.
Also remember, SMB paths use \ and not /.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to use the SMBJ jar (https://github.com/hierynomus/smbj) to fetch a file from shared drive. I am able to connect to the shared disk. After the connect, any operation I perform is throwing exception.

For my shared drive location: //x.x.x.x/containing/folder/filename.txt, I am using the parameters as:

//SERVER_ADDRESS = x.x.x.x
//SHARE_NAME = /containing/folder/
//FILE_NAME = filename.txt
//LOCAL_PATH = "D:\\";

    SMBClient client = new SMBClient();
    try (Connection connection = client.connect(SERVER_ADDRESS)) {
        AuthenticationContext ac = new AuthenticationContext(USERNAME, PASSWORD.toCharArray(), DOMAIN);
        Session session = connection.authenticate(ac);
        // Connect to Share
        try (DiskShare share = (DiskShare) session.connectShare(SHARE_NAME)) {
            Set<SMB2ShareAccess> s = new HashSet<>();
            s.add(SMB2ShareAccess.ALL.iterator().next()); // this is to get READ only
            com.hierynomus.smbj.share.File remoteSmbjFile =  share.openFile(SHARE_NAME+FILE_NAME, EnumSet.of(AccessMask.GENERIC_READ), null, s, null, null);
            java.io.File dest = new java.io.File(LOCAL_PATH + FILE_NAME);
            try (InputStream is = remoteSmbjFile.getInputStream();
                    OutputStream os = new FileOutputStream(dest);) {
                byte[] buffer = new byte[1024];
                int length;
                while ((length = is.read(buffer)) > 0) {
                    os.write(buffer, 0, length);
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        LOGGER.error("", e);
        return "ERROR";
    } catch (Exception e) {
        e.printStackTrace();
        LOGGER.error("", e);
        return "ERROR";
    }

I am getting the exception as below. I think that I am not getting the right combination for the parameters.

com.hierynomus.mssmb2.SMBApiException: STATUS_INVALID_PARAMETER(3221225485/3221225485): Create failed for \containing\folder\
    at com.hierynomus.smbj.share.Share.receive(Share.java:364)
    at com.hierynomus.smbj.share.Share.sendReceive(Share.java:344)
    at com.hierynomus.smbj.share.Share.createFile(Share.java:136)
    at com.hierynomus.smbj.share.DiskShare.open(DiskShare.java:59)
    at com.hierynomus.smbj.share.DiskShare.openDirectory(DiskShare.java:82)
    at com.hierynomus.smbj.share.DiskShare.list(DiskShare.java:169)
    at com.hierynomus.smbj.share.DiskShare.list(DiskShare.java:151)

I am unable to get what is wrong here. Can you please suggest what I am missing here.


问:
Appium unable to identify element using resource-id
Appium is unable to identify an element using the id locator(resource-id) instead we can identify the same using Accessibility Id locator.

Please refer to attached image.enter image description here

答:
What is your version of Appium? Could you open it with Appium Inspector to check if there is any difference with UI Automator Viewer?

Anyway... Try this

```<code>#Can't see at your screenshot the whole resource-id so I put what I see.
driver.find_element_by_xpath("//android.view.View[@resource-id='rptRole__ctl0_rptCommunicationlt...']")

#You could also try these two options:
driver.find_element_by_xpath("//android.view.View[@content-desc='1_gr_selected_stores_flex_update.xls']")

driver.find_element_by_xpath("//android.view.View[@text='1_gr_selected_stores_flex_update.xls']")
</code>```

If none of this work, you will have to provide more information

Body:
What is your version of Appium? Could you open it with Appium Inspector to check if there is any difference with UI Automator Viewer?

Anyway... Try this

#Can't see at your screenshot the whole resource-id so I put what I see.
driver.find_element_by_xpath("//android.view.View[@resource-id='rptRole__ctl0_rptCommunicationlt...']")

#You could also try these two options:
driver.find_element_by_xpath("//android.view.View[@content-desc='1_gr_selected_stores_flex_update.xls']")

driver.find_element_by_xpath("//android.view.View[@text='1_gr_selected_stores_flex_update.xls']")

If none of this work, you will have to provide more information


问:
How to put a text and a string inside array
I've create this code

```<code> $S_Jenis = $_POST['JenisTrx'];
 $S_Keterangan = $_POST['KeteranganTrx'];
 $S_Jumlah = $_POST['JumlahTrx'];
</code>```

and I call it here

```<code>$msg = array
      (
    'body'  => $S_Keterangan Rp$S_Jumlah,
    'title' => Kas $S_Jenis,
            'icon'  => 'myicon',
            'sound' => 'mySound'
      );
</code>```

but it's an error if I put "Kas" inside title and 2 String inside body, anyone know how to fix this?

答:
Try Following code</p>

```<code>$msg = array
      (
    'body'  => $S_Keterangan ."Rp".$S_Jumlah,
    'title' => "Kas".$S_Jenis,
            'icon'  => 'myicon',
            'sound' => 'mySound'
      );
</code>```

Body:
I've create this code

 $S_Jenis = $_POST['JenisTrx'];
 $S_Keterangan = $_POST['KeteranganTrx'];
 $S_Jumlah = $_POST['JumlahTrx'];

and I call it here

$msg = array
      (
    'body'  => $S_Keterangan Rp$S_Jumlah,
    'title' => Kas $S_Jenis,
            'icon'  => 'myicon',
            'sound' => 'mySound'
      );

but it's an error if I put "Kas" inside title and 2 String inside body, anyone know how to fix this?

Body:
Try Following code

$msg = array
      (
    'body'  => $S_Keterangan ."Rp".$S_Jumlah,
    'title' => "Kas".$S_Jenis,
            'icon'  => 'myicon',
            'sound' => 'mySound'
      );


问:
How to do GET API Request with URL params?
```<code>Client client = ClientBuilder.newClient();
urlApi="https://localhost:123/demo/api/v1/rows/search?";
WebTarget webTarget = client.target(urlApi);
for (Map.Entry<String, String> entry : queryParams.entrySet()) {
    webTarget.queryParam(entry.getKey(), entry.getValue());
}
webTarget.queryParam("searchConditions",webTarget.queryParam("mobileNo","+9999999999"));

Invocation.Builder builder = webTarget.request();

builder.header("id", "ABC");
String asB64 = Base64.getEncoder().encodeToString("ABC:PWD".getBytes("utf-8"));
logger.debug("Calling  API "+urlApi);
builder.header("Authorization", "Basic "+asB64);
builder.header("Content-type", MediaType.APPLICATION_JSON);
response = builder.get();
responseData = response.readEntity(String.class);
System.out.println(responseData);
</code>```

I am trying to do GET request with searchCondition as Key and value as {mobileNo="+919999999999"}, I am unable to get this to work.

Apart from that, how can I print the Request "Headers" along with "Query params"? Thank you in advance

答:
I think you need to encode the value inputs, something like this:

```<code>webTarget.queryParam("searchCondition", URLEncoder.encode("{mobileNo=\"+919999999999\"}", StandardCharsets.UTF_8.toString()));
</code>```

UDPATE:
Example of the rest  client with Spring:

```<code>@Test
public void testStack() throws Exception {
    RestTemplate rest = new RestTemplate();
    String fooResourceUrl="http://localhost:8080/usersParam?";
    RestTemplate restTemplate = new RestTemplate();
    String parameter = "{mobileNo=\"+919999999999\"}";

    ResponseEntity<String> response = restTemplate.getForEntity(fooResourceUrl + "parameter=" + URLEncoder.encode(parameter, StandardCharsets.UTF_8.toString() ), String.class);
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
}
</code>```

And this would be the rest service:

```<code>@RequestMapping(method = RequestMethod.GET, value="/usersParam")
    public User getUsersInfo(@RequestParam String parameter) throws UnsupportedEncodingException {
         System.out.println(URLDecoder.decode(parameter, StandardCharsets.UTF_8.toString() ));
        return null;
    }
</code>```

Body:
Client client = ClientBuilder.newClient();
urlApi="https://localhost:123/demo/api/v1/rows/search?";
WebTarget webTarget = client.target(urlApi);
for (Map.Entry<String, String> entry : queryParams.entrySet()) {
    webTarget.queryParam(entry.getKey(), entry.getValue());
}
webTarget.queryParam("searchConditions",webTarget.queryParam("mobileNo","+9999999999"));

Invocation.Builder builder = webTarget.request();

builder.header("id", "ABC");
String asB64 = Base64.getEncoder().encodeToString("ABC:PWD".getBytes("utf-8"));
logger.debug("Calling  API "+urlApi);
builder.header("Authorization", "Basic "+asB64);
builder.header("Content-type", MediaType.APPLICATION_JSON);
response = builder.get();
responseData = response.readEntity(String.class);
System.out.println(responseData);

I am trying to do GET request with searchCondition as Key and value as {mobileNo="+919999999999"}, I am unable to get this to work.

Apart from that, how can I print the Request "Headers" along with "Query params"? Thank you in advance

Body:
I think you need to encode the value inputs, something like this:

webTarget.queryParam("searchCondition", URLEncoder.encode("{mobileNo=\"+919999999999\"}", StandardCharsets.UTF_8.toString()));

UDPATE:
Example of the rest  client with Spring:

@Test
public void testStack() throws Exception {
    RestTemplate rest = new RestTemplate();
    String fooResourceUrl="http://localhost:8080/usersParam?";
    RestTemplate restTemplate = new RestTemplate();
    String parameter = "{mobileNo=\"+919999999999\"}";

    ResponseEntity<String> response = restTemplate.getForEntity(fooResourceUrl + "parameter=" + URLEncoder.encode(parameter, StandardCharsets.UTF_8.toString() ), String.class);
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
}

And this would be the rest service:

@RequestMapping(method = RequestMethod.GET, value="/usersParam")
    public User getUsersInfo(@RequestParam String parameter) throws UnsupportedEncodingException {
         System.out.println(URLDecoder.decode(parameter, StandardCharsets.UTF_8.toString() ));
        return null;
    }


问:
Separate tables for categories or use a join?
My site has various articles, always and only shown under specific categories, e.g. news, sport, business.

Would it be more efficient to have a table design where all articles were in a single table with a relational link to an article types table, then I could do a join to get all sports articles for example.

Or would it be more efficient to have separate tables for each type of article, one for news, one for sports and one for business.

Please note, I will never have any more than these three categories.

--- Edit

The table structure would be the same. e.g. title, article content, date etc.

答:
If the only difference between a news article, a sport article and a business article, is the category (i.e. all kinds of article only ever have a Title, Author, PublishDate, WordCount, Body, CommentsAllowed etc and there are no specialised columns) then you use one Articles table with a  CategoryID

If a sport article is so massively different to a business article that the only property they share is the Body, then different tables would be the way to go; you don't want an article table that has a bunch of null columns on row A "because those columns are only for sports articles and this is a business article" and a different bunch of nulls on row B "because this is a sports article and those columns are only for business"

it's acceptable to have the occasional null.. Like if you have a rule that "people can write tweets to the author of a business article because they'll be nice and polite, but putting the author's twitter handle on a sports article will incite rival team thuggery and fighting" then your Articles table AuthorTwitterHandle column can be null for a sports article and populated for a business article - but essentially here it's not specifically a property of a business article that can never be applied to other articles. One day a new CEO might decide to enable twittering on sports articles.. if you can think of e.g. 10 legitimate extra properties that a business article would have that other articles wouldn't, you can always make an extra table for those properties, and relate them back to the articles table via BusinessArticlesExtraProperties.ArticleID = Articles.ID type join.. This is something akin to object oriented programming's inheritance mechanism


问:
Preloading images with jQuery
I'm looking for a quick and easy way to preload images with JavaScript. I'm using jQuery if that's important.

I saw this here (http://nettuts.com...):

```<code>function complexLoad(config, fileNames) {
  for (var x = 0; x < fileNames.length; x++) {
    $("<img>").attr({
      id: fileNames[x],
      src: config.imgDir + fileNames[x] + config.imgFormat,
      title: "The " + fileNames[x] + " nebula"
    }).appendTo("#" + config.imgContainer).css({ display: "none" });
  }
};
</code>```

But, it looks a bit over-the-top for what I want!

I know there are jQuery plugins out there that do this but they all seem a bit big (in size); I just need a quick, easy and short way of preloading images!

答:
JP, After checking your solution, I was still having issues in Firefox where it wouldn't preload the images before moving along with loading the page. I discovered this by putting some sleep(5) in my server side script. I implemented the following solution based off yours which seems to solve this.

Basically I added a callback to your jQuery preload plugin, so that it gets called after all the images are properly loaded.

```<code>// Helper function, used below.
// Usage: ['img1.jpg','img2.jpg'].remove('img1.jpg');
Array.prototype.remove = function(element) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == element) { this.splice(i,1); }
  }
};

// Usage: $(['img1.jpg','img2.jpg']).preloadImages(function(){ ... });
// Callback function gets called after all images are preloaded
$.fn.preloadImages = function(callback) {
  checklist = this.toArray();
  this.each(function() {
    $('<img>').attr({ src: this }).load(function() {
      checklist.remove($(this).attr('src'));
      if (checklist.length == 0) { callback(); }
    });
  });
};
</code>```

Out of interest, in my context, I'm using this as follows:

```<code>$.post('/submit_stuff', { id: 123 }, function(response) {
  $([response.imgsrc1, response.imgsrc2]).preloadImages(function(){
    // Update page with response data
  });
});
</code>```

Hopefully this helps someone who comes to this page from Google (as I did) looking for a solution to preloading images on Ajax calls.

Title: Preloading images with jQuery

Body:
I'm looking for a quick and easy way to preload images with JavaScript. I'm using jQuery if that's important.

I saw this here (http://nettuts.com...):

function complexLoad(config, fileNames) {
  for (var x = 0; x < fileNames.length; x++) {
    $("").attr({
      id: fileNames[x],
      src: config.imgDir + fileNames[x] + config.imgFormat,
      title: "The " + fileNames[x] + " nebula"
    }).appendTo("#" + config.imgContainer).css({ display: "none" });
  }
};

But, it looks a bit over-the-top for what I want!

I know there are jQuery plugins out there that do this but they all seem a bit big (in size); I just need a quick, easy and short way of preloading images!

Body:
JP, After checking your solution, I was still having issues in Firefox where it wouldn't preload the images before moving along with loading the page. I discovered this by putting some sleep(5) in my server side script. I implemented the following solution based off yours which seems to solve this.

Basically I added a callback to your jQuery preload plugin, so that it gets called after all the images are properly loaded.

// Helper function, used below.
// Usage: ['img1.jpg','img2.jpg'].remove('img1.jpg');
Array.prototype.remove = function(element) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == element) { this.splice(i,1); }
  }
};

// Usage: $(['img1.jpg','img2.jpg']).preloadImages(function(){ ... });
// Callback function gets called after all images are preloaded
$.fn.preloadImages = function(callback) {
  checklist = this.toArray();
  this.each(function() {
    $('<img>').attr({ src: this }).load(function() {
      checklist.remove($(this).attr('src'));
      if (checklist.length == 0) { callback(); }
    });
  });
};

Out of interest, in my context, I'm using this as follows:

$.post('/submit_stuff', { id: 123 }, function(response) {
  $([response.imgsrc1, response.imgsrc2]).preloadImages(function(){
    // Update page with response data
  });
});

Hopefully this helps someone who comes to this page from Google (as I did) looking for a solution to preloading images on Ajax calls.

ContentLicense: CC BY-SA 2.5


问:
NoReverseMatch error in rendering Django
Below is my views.py. After the POST, user gets a success page showing the 5 Items. At the same time I also want to show environment to the user. So I did something like below (passed environment as an argument). I get that while the redirect happens, it tries to find something like success and the environment argument match which it is not able to get. Probably I need
 right regular expression to handle this and I am not sure how to handle this.

```<code>def order_create(request):
    cart = ItemObject.objects.all()

    if request.method == 'POST':
        ...
            environment = envi_dict1.difference(item_dict1)
            return HttpResponseRedirect(reverse('success', {'environment': environment}))

    else:
        form = ItemObjectCreateForm()
    return render(request,
                  'index.html',
                  {'form': form})

def successView(request):

    return render(request, 'success.html', {'items': ItemObject.objects.filter(gp_code='Unknown')[:5]})
</code>```

urls.py

```<code>urlpatterns = [

    url(r'^admin/', admin.site.urls),
    url(r'^export_action/', include("export_action.urls", namespace="export_action")),
    url('^business-logic/', include('business_logic.urls')),
    url('^index/', views.order_create),
    url(r'^success/', views.successView, name='success')
]
</code>```

The error I am getting is this

```<code>NoReverseMatch at /index/
Reverse for 'success' with keyword arguments '{u'environment': set([u'Test1'])}' not found. 1 pattern(s) tried: ['success/']
</code>```

答:
Try with

```<code>return HttpResponseRedirect(reverse('success/', {'environment': environment}))
</code>```

your url have  '/' in success

```<code>url(r'^success/', views.successView, name='success')
</code>```

but are not giving '/' in redirect url

Body:
Below is my views.py. After the POST, user gets a success page showing the 5 Items. At the same time I also want to show environment to the user. So I did something like below (passed environment as an argument). I get that while the redirect happens, it tries to find something like success and the environment argument match which it is not able to get. Probably I need
 right regular expression to handle this and I am not sure how to handle this.

def order_create(request):
    cart = ItemObject.objects.all()

    if request.method == 'POST':
        ...
            environment = envi_dict1.difference(item_dict1)
            return HttpResponseRedirect(reverse('success', {'environment': environment}))

    else:
        form = ItemObjectCreateForm()
    return render(request,
                  'index.html',
                  {'form': form})

def successView(request):

    return render(request, 'success.html', {'items': ItemObject.objects.filter(gp_code='Unknown')[:5]})

urls.py

urlpatterns = [

    url(r'^admin/', admin.site.urls),
    url(r'^export_action/', include("export_action.urls", namespace="export_action")),
    url('^business-logic/', include('business_logic.urls')),
    url('^index/', views.order_create),
    url(r'^success/', views.successView, name='success')
]

The error I am getting is this

NoReverseMatch at /index/
Reverse for 'success' with keyword arguments '{u'environment': set([u'Test1'])}' not found. 1 pattern(s) tried: ['success/']

Body:
Try with

return HttpResponseRedirect(reverse('success/', {'environment': environment}))

your url have  '/' in success

url(r'^success/', views.successView, name='success')

but are not giving '/' in redirect url


问:
Why is Toast notification using OnLaunched instead of OnActivated in windows 10 app?
When clicking on my Toast notification the OnLaunched method is being called instead of the OnActivated.  And nothing is in the e.Arguments - any ideas?

My Toast template is the default Visual Studio Server Explorer template:

```<code><?xml version="1.0" encoding="utf-8"?>
<toast>
  <visual>
    <binding template="ToastText01">
      <text id="1">Test message</text>
    </binding>
  </visual>
</toast>
</code>```

答:
OnLaunched is called because the legacy toast template is used:

Note: If you are using the legacy toast templates from Windows 8.1, OnLaunched will be called instead.
  [docs]

And e.Arguments is empty because the launch attribute of the toast is not set in XML (see this MSDN page for details).

Body:
When clicking on my Toast notification the OnLaunched method is being called instead of the OnActivated.  And nothing is in the e.Arguments - any ideas?

My Toast template is the default Visual Studio Server Explorer template:

<?xml version="1.0" encoding="utf-8"?>
<toast>
  <visual>
    <binding template="ToastText01">
      <text id="1">Test message</text>
    </binding>
  </visual>
</toast>


问:
Using move semantics to avoid copying when pushing_back to a custom container does not avoid copying
I have implemented a  custom container (same vein as std::vector) and I am trying to make it so that its 'push_back' function would use leverage on move semantics to avoid creating a copy of whatever is being pushed back - specially when the object to be pushed into the container is returned by an external function.

After reading quite a bit about move semantics and custom containers, I still can't find why my approach is still generating a copy instead of just moving the passed object into the container's inner dynamic array.

Here is a simplified version of my container looks like:

```<code>template<class T>
class Constructor
{
private:
    size_t size = 0;
    size_t cap = 0;
    T *data = nullptr;

public:
Constructor()
{
    cap = 1;
    size = 0;
    data = static_cast<T*>(malloc(cap * sizeof(T)));
}

~Constructor()
{ delete[] data; }

template<typename U>
void push_back(U &&value)
{
    if (size + 1 >= cap)
    {
        size_t new_cap = (cap * 2);
        T* new_data = static_cast<T*>(malloc(new_cap * sizeof(T)));
        memmove(new_data, data, (size) * sizeof(T));
        for (size_t i = 0; i<cap; i++)
        {
            data[i].~T();
        }

        delete[] data;

        cap = new_cap;
        data = new_data;
        new(data + size) T(std::forward<U>(value));
    }
    else
    {
        new(data + size) T(std::forward<U>(value));
    }

    ++size;
}

const T& operator[](const size_t index) const //access [] overloading
{
    return data[index];
}
};
</code>```

Here is a custom class that will print messages when its instances are created, copied or moved, in order to help debugging:

```<code>class MyClass
{
size_t id;

public:
MyClass(const size_t new_id)
{
    id = new_id;
    std::cout << "new instance with id " << id << std::endl;
}
MyClass(const MyClass &passedEntity)
{
    id = passedEntity.id;
    std::cout << "copied instance" << std::endl;
}
MyClass(MyClass &&passedEntity)
{
    id = passedEntity.id;
    std::cout << "moved instance" << std::endl;
}

void printID() const
{
    std::cout << "this instance's id is " << id << std::endl;
}
};
</code>```

And here is the external function:

```<code>MyClass &foo(MyClass &passed)
{
    return passed;
}
</code>```

Lastly, here is the main function that runs a test case using the above function and classes to show the problem:

```<code>int main()
{
MyClass a(33);
std::cout << std::endl;

std::cout << "Using my custom container: " << std::endl;
Constructor<MyClass> myContainer;
myContainer.push_back(foo(a));
myContainer[0].printID();
std::cout << std::endl;

std::cout << "Using dinamic array: " << std::endl;
MyClass *dinArray = static_cast<MyClass*>(malloc(1 * sizeof(MyClass)));
dinArray = new(dinArray + 1) MyClass(std::forward<MyClass>(foo(a)));
dinArray[0].printID();
std::cout << std::endl;

system("Pause");
return 0;
}
</code>```

The output is:

```<code>new instance with id 33

Using my custom container:
copied instance
this instance's id is 33

Using dinamic array:
moved instance
this instance's id is 33
</code>```

As it can be seen, if the instance of MyClass is put directly into a dynamic array, then just the move conmstructor is called and not the copy constructor. However, if I push_back the yClass instance into an instance of Container, a copy constructor is still being called.

Could someone help me understand what exactly am I doing wrong here? How could I make it so that elements are pushed into the container without generating a copy?

答:
When you call this line

```<code>myContainer.push_back(foo(a));
</code>```

L-value is passed into push_back method, and now read about using std::forward - http://www.cplusplus.com/reference/utility/forward/,

Returns an rvalue reference to arg if arg is not an lvalue reference.

If arg is an lvalue reference, the function returns arg without modifying its type.

and in your push_back you call

```<code>new(data + size) T(std::forward<U>(value));
</code>```

but value was passed as L-value, and only constructor MyClass(const MyClass &passedEntity) can be invoked.

If you want a object to be moved, you can write

```<code>myContainer.push_back(std::move(a)); // cast to R-reference
</code>```

EDIT

You should not use move in your push_back function, below is simple example.
Suppose you have class like this:

```<code> struct Foo {
 int i;
 Foo (int i = 0) : i(i) {
 }
 ~Foo () {
 }
 Foo (const Foo& ) {
 }
 Foo& operator=(const Foo&) {
    return *this;
 }
 Foo (Foo&& f)
 {
    i = f.i;
    f.i = 0;   // this is important
 }
 Foo& operator=(Foo&& f)
 {
    i = f.i;
    f.i = 0; // this is important
    return *this;
 }
};
</code>```

we have also 2 functions

```<code>template<class T>
void process1 (const T& ) {
    cout << "process1" << endl;
}

template<class T>
void process (T&& obj) {
    cout << "process2" << endl;
    T newObj = forward<T>(obj);
}
</code>```

and bars functions are counterparts of  your push_back method.

```<code>template <typename T>
void bar1 (T&& value) {
    process (move(value));   // you use move in your push_back method
}

template <typename T>
void bar2 (T&& value) {
    process (forward<T>(value));
}
</code>```

now we must consider 4 cases:

[1] pass L-value, version with forward

```<code>Foo f(20);
bar2 (f);
cout << (f.i) << endl; // 20
</code>```

[2] pass R-value, version with forward

```<code>Foo f(20);
bar2 (move(f));
cout << (f.i) << endl; // 0, it is OK bacuse we wanted to move 'f' object
</code>```

[3] pass R-value, version with move

```<code>Foo f(20);
bar1 (move(f));
cout << (f.i) << endl; // 0, ok, we wanted to move 'f' object
</code>```

[4] pass L-value, version with move in your push_back method

```<code>Foo f(20);
bar1 (f);
cout << (f.i) << endl; // 0 !!! is it OK ? WRONG
</code>```

in last case, we passed f as L-value, but this object was moved in bar1 function, for me this is strange behavior and is incorrect.

Body:
I have implemented a  custom container (same vein as std::vector) and I am trying to make it so that its 'push_back' function would use leverage on move semantics to avoid creating a copy of whatever is being pushed back - specially when the object to be pushed into the container is returned by an external function.

After reading quite a bit about move semantics and custom containers, I still can't find why my approach is still generating a copy instead of just moving the passed object into the container's inner dynamic array.

Here is a simplified version of my container looks like:

template<class T>
class Constructor
{
private:
    size_t size = 0;
    size_t cap = 0;
    T *data = nullptr;

public:
Constructor()
{
    cap = 1;
    size = 0;
    data = static_cast<T*>(malloc(cap * sizeof(T)));
}

~Constructor()
{ delete[] data; }

template<typename U>
void push_back(U &&value)
{
    if (size + 1 >= cap)
    {
        size_t new_cap = (cap * 2);
        T* new_data = static_cast<T*>(malloc(new_cap * sizeof(T)));
        memmove(new_data, data, (size) * sizeof(T));
        for (size_t i = 0; i<cap; i++)
        {
            data[i].~T();
        }

        delete[] data;

        cap = new_cap;
        data = new_data;
        new(data + size) T(std::forward(value));
    }
    else
    {
        new(data + size) T(std::forward(value));
    }

    ++size;
}

const T& operator[](const size_t index) const //access [] overloading
{
    return data[index];
}
};

Here is a custom class that will print messages when its instances are created, copied or moved, in order to help debugging:

class MyClass
{
size_t id;

public:
MyClass(const size_t new_id)
{
    id = new_id;
    std::cout << "new instance with id " << id << std::endl;
}
MyClass(const MyClass &passedEntity)
{
    id = passedEntity.id;
    std::cout << "copied instance" << std::endl;
}
MyClass(MyClass &&passedEntity)
{
    id = passedEntity.id;
    std::cout << "moved instance" << std::endl;
}

void printID() const
{
    std::cout << "this instance's id is " << id << std::endl;
}
};

And here is the external function:

MyClass &foo(MyClass &passed)
{
    return passed;
}

Lastly, here is the main function that runs a test case using the above function and classes to show the problem:

int main()
{
MyClass a(33);
std::cout << std::endl;

std::cout << "Using my custom container: " << std::endl;
Constructor<MyClass> myContainer;
myContainer.push_back(foo(a));
myContainer[0].printID();
std::cout << std::endl;

std::cout << "Using dinamic array: " << std::endl;
MyClass *dinArray = static_cast<MyClass*>(malloc(1 * sizeof(MyClass)));
dinArray = new(dinArray + 1) MyClass(std::forward<MyClass>(foo(a)));
dinArray[0].printID();
std::cout << std::endl;

system("Pause");
return 0;
}

The output is:

new instance with id 33

Using my custom container:
copied instance
this instance's id is 33

Using dinamic array:
moved instance
this instance's id is 33

As it can be seen, if the instance of MyClass is put directly into a dynamic array, then just the move conmstructor is called and not the copy constructor. However, if I push_back the yClass instance into an instance of Container, a copy constructor is still being called.

Could someone help me understand what exactly am I doing wrong here? How could I make it so that elements are pushed into the container without generating a copy?

Body:
When you call this line

myContainer.push_back(foo(a));

L-value is passed into push_back method, and now read about using std::forward - http://www.cplusplus.com/reference/utility/forward/,

Returns an rvalue reference to arg if arg is not an lvalue reference.

If arg is an lvalue reference, the function returns arg without modifying its type.

and in your push_back you call

new(data + size) T(std::forward<U>(value));

but value was passed as L-value, and only constructor MyClass(const MyClass &passedEntity) can be invoked.

If you want a object to be moved, you can write

myContainer.push_back(std::move(a)); // cast to R-reference

EDIT

You should not use move in your push_back function, below is simple example.
Suppose you have class like this:

 struct Foo {
 int i;
 Foo (int i = 0) : i(i) {
 }
 ~Foo () {
 }
 Foo (const Foo& ) {
 }
 Foo& operator=(const Foo&) {
    return *this;
 }
 Foo (Foo&& f)
 {
    i = f.i;
    f.i = 0;   // this is important
 }
 Foo& operator=(Foo&& f)
 {
    i = f.i;
    f.i = 0; // this is important
    return *this;
 }
};

we have also 2 functions

template<class T>
void process1 (const T& ) {
    cout << "process1" << endl;
}

template<class T>
void process (T&& obj) {
    cout << "process2" << endl;
    T newObj = forward<T>(obj);
}

and bars functions are counterparts of  your push_back method.

template <typename T>
void bar1 (T&& value) {
    process (move(value));   // you use move in your push_back method
}

template <typename T>
void bar2 (T&& value) {
    process (forward<T>(value));
}

now we must consider 4 cases:

[1] pass L-value, version with forward

Foo f(20);
bar2 (f);
cout << (f.i) << endl; // 20

[2] pass R-value, version with forward

Foo f(20);
bar2 (move(f));
cout << (f.i) << endl; // 0, it is OK bacuse we wanted to move 'f' object

[3] pass R-value, version with move

Foo f(20);
bar1 (move(f));
cout << (f.i) << endl; // 0, ok, we wanted to move 'f' object

[4] pass L-value, version with move in your push_back method

Foo f(20);
bar1 (f);
cout << (f.i) << endl; // 0 !!! is it OK ? WRONG

in last case, we passed f as L-value, but this object was moved in bar1 function, for me this is strange behavior and is incorrect.


问:
Return local variable by reference still shows me the right value
I have this class:

```<code>class A
{
private:
    int a;
public:
    int getA();
    void setA(int a=2) ;
};
</code>```

and a function:

```<code>A& func()
{
A a;
a.setA(777);
return a;
}
</code>```

and in main:

```<code>A a;
a=func();
cout<<a.getA();
</code>```

and i get "777".
but as i know it shouldnt get me any value since the local "a" in the function has been deleted. so why do i get the right value?

答:
Because the behaviour of your code is undefined, and appearing to work correctly on at least one occasion is an acceptable manifestation of undefined behaviour.

You may well get "777": a NUL-terminated const char[4] type.

Body:
I have this class:

class A
{
private:
    int a;
public:
    int getA();
    void setA(int a=2) ;
};

and a function:

A& func()
{
A a;
a.setA(777);
return a;
}

and in main:

A a;
a=func();
cout<<a.getA();

and i get "777".
but as i know it shouldnt get me any value since the local "a" in the function has been deleted. so why do i get the right value?


问:
Adding just one picturebox
i need to add just one picturebox. But the code adds infinite pictureboxes. if my score is 10, i want to add just one picturebox. Pls help me to fix this:</p>

```<code>if (score == 10)
{
    PictureBox zombie = new PictureBox();
    {

       zombie.Tag = "zombie"; // add a tag to it called zombie
       zombie.Image = Properties.Resources.beer_PNG2331;
       zombie.Left = rnd.Next(0, 900);
       zombie.Top = rnd.Next(0, 800);
       zombie.SizeMode = PictureBoxSizeMode.AutoSize;
       this.Controls.Add(zombie); /
       player.BringToFront();
    }
}
</code>```

答:
Edit: improving the answeer
remove the braces and make sure that there is no other part of your software that causes that part of code to be executed more than once with the same score value</p>

```<code>if (score == 10)
{
    PictureBox zombie = new PictureBox();
    zombie.Tag = "zombie"; // add a tag to it called zombie
    zombie.Image = Properties.Resources.beer_PNG2331;
    zombie.Left = rnd.Next(0, 900);
    zombie.Top = rnd.Next(0, 800);
    zombie.SizeMode = PictureBoxSizeMode.AutoSize;

    this.Controls.Add(zombie);

    player.BringToFront();
}
</code>```

Title: Adding just one picturebox

Body:
i need to add just one picturebox. But the code adds infinite pictureboxes. if my score is 10, i want to add just one picturebox. Pls help me to fix this:

if (score == 10)
{
    PictureBox zombie = new PictureBox();
    {

       zombie.Tag = "zombie"; // add a tag to it called zombie
       zombie.Image = Properties.Resources.beer_PNG2331;
       zombie.Left = rnd.Next(0, 900);
       zombie.Top = rnd.Next(0, 800);
       zombie.SizeMode = PictureBoxSizeMode.AutoSize;
       this.Controls.Add(zombie); /
       player.BringToFront();
    }
}

Body:
Edit: improving the answeer
remove the braces and make sure that there is no other part of your software that causes that part of code to be executed more than once with the same score value

if (score == 10)
{
    PictureBox zombie = new PictureBox();
    zombie.Tag = "zombie"; // add a tag to it called zombie
    zombie.Image = Properties.Resources.beer_PNG2331;
    zombie.Left = rnd.Next(0, 900);
    zombie.Top = rnd.Next(0, 800);
    zombie.SizeMode = PictureBoxSizeMode.AutoSize;

    this.Controls.Add(zombie);

    player.BringToFront();
}


问:
Replacing keyword in string that is HTML page using Java
I have following string:

```<code><html>
<head><meta>...</meta><head>
<body>
   <div id="foo">
     Text I want to search & replace occurrences
     of keywords such as Foo or foo while ignoring case
   </div>
</body>
</html>
</code>```

What I want to end up with is:

```<code><html>
<head><meta>...</meta><head>
<body>
   <div id="foo">
     Text I want to search & replace occurrences
     of keywords such as <b>Foo</b> or <b>foo</b> while ignoring case
   </div>
</body>
</html>
</code>```

So pretty much I'd like to search for and replace foo with foo or Foo. It is important to retain the case of the string that is being replace but match it with keyword foo while ignoring the case of the matches.

Another important thing is that the replacement ignores all html tags and their content. Notice that
 stays like it is.

I drafted this but didn't test it yet

```<code> text = text.replace("(?i)"+keyword+"(?!([^<]+)?>)", "<b>"+keyword+"</b>");
</code>```

The problem with the above is that it doesn't remember the case of word that is being replaced and just puts in the keyword.

答:
You need to use a capturing group, and, by the way, use replaceAll

```<code>text = text.replaceAll("(?i)("+keyword+")(?!([^<]+)?>)", "<b>$0</b>");
</code>```

Body:
I have following string:

<meta>...</meta>

     Text I want to search & replace occurrences
     of keywords such as Foo or foo while ignoring case

What I want to end up with is:

<meta>...</meta>

     Text I want to search & replace occurrences
     of keywords such as Foo or foo while ignoring case

So pretty much I'd like to search for and replace foo with foo or Foo. It is important to retain the case of the string that is being replace but match it with keyword foo while ignoring the case of the matches.

Another important thing is that the replacement ignores all html tags and their content. Notice that
 stays like it is.

I drafted this but didn't test it yet

 text = text.replace("(?i)"+keyword+"(?!([^<]+)?>)", ""+keyword+"");

The problem with the above is that it doesn't remember the case of word that is being replaced and just puts in the keyword.

Body:
You need to use a capturing group, and, by the way, use replaceAll

text = text.replaceAll("(?i)("+keyword+")(?!([^<]+)?>)", "<b>$0</b>");


问:
Passthrough input to output in AWS Step Functions
How can I passthrough the input to a Task state in an AWS Step Functions to the output?

After reading the Input and Output Processing page in the AWS docs, I have played with various combinations of InputPath, ResultPath and OutputPath.

State definition:

```<code>"First State": {
    "Type": "Task",
    "Resource": "[My Lambda ARN]",
    "Next": "Second State",
    "InputPath": "$.someKey",
    "OutputPath": "$"
}
</code>```

Input:

```<code>{
    "someKey": "someValue"
}
</code>```

Expected Result

I would like the output of the First State (and thus the input of Second State) to be

```<code>{
    "someKey": "someValue"
}
</code>```

Actual Result

```<code>[empty]
</code>```

What if the input is more complicated, e.g.

```<code>{
    "firstKey": "firstValue",
    "secondKey": "secondValue"
}
</code>```

I would like to forward all of it without worrying about (sub) paths.

答:
In the Amazon States Language spec it is stated that:

If the value of ResultPath is null, that means that the state’s own raw output is discarded and its raw input becomes its result.

Consequently, I updated my state definition to

```<code>"First State": {
    "Type": "Task",
    "Resource": "[My Lambda ARN]",
    "Next": "Second State",
    "ResultPath": null
}
</code>```

As a result, when passing the input example Task input payload will be copied to the output, even for rich objects like:

```<code>{
    "firstKey": "firstValue",
    "secondKey": "secondValue"
}
</code>```

Body:
How can I passthrough the input to a Task state in an AWS Step Functions to the output?

After reading the Input and Output Processing page in the AWS docs, I have played with various combinations of InputPath, ResultPath and OutputPath.

State definition:

"First State": {
    "Type": "Task",
    "Resource": "[My Lambda ARN]",
    "Next": "Second State",
    "InputPath": "$.someKey",
    "OutputPath": "$"
}

Input:

{
    "someKey": "someValue"
}

Expected Result

I would like the output of the First State (and thus the input of Second State) to be

{
    "someKey": "someValue"
}

Actual Result

[empty]

What if the input is more complicated, e.g.

{
    "firstKey": "firstValue",
    "secondKey": "secondValue"
}

I would like to forward all of it without worrying about (sub) paths.

Body:
In the Amazon States Language spec it is stated that:

If the value of ResultPath is null, that means that the state’s own raw output is discarded and its raw input becomes its result.

Consequently, I updated my state definition to

"First State": {
    "Type": "Task",
    "Resource": "[My Lambda ARN]",
    "Next": "Second State",
    "ResultPath": null
}

As a result, when passing the input example Task input payload will be copied to the output, even for rich objects like:

{
    "firstKey": "firstValue",
    "secondKey": "secondValue"
}

ContentLicense: CC BY-SA 4.0


问:
Cannot open Jmeter file in Jmeter 3.3
I recently updated Jmeter 3.3 and I am unable to open the old file.
Can you please help?

答:
Install the required (which have you used in your test scripts) plugins from plugin manager for JMeter 3.3. This error is showing because of your missing plugins in version 3.3.

Or you can download the required plugins and put it in your /lib directory and then again restart your JMeter 3.3 again.

Title: Cannot open Jmeter file in Jmeter 3.3


问:
Perl LWP Post form-data with my boundary
I want to post data with content type multipart/form-data:

```<code>use strict;
use warnings;

use LWP::UserAgent;

my $ua = LWP::UserAgent->new;
$ua->post (
    'http://127.0.0.1:12555',
    'Content-Type' => 'form-data',
    Content => {
        'data1' => rand,
        'data2' => rand,
    }
);
</code>```

And i tested the submitted data:

```<code>use strict;
use warnings;
use IO::Socket::INET;
use Socket qw ( inet_aton );

my $sock_listen = new IO::Socket::INET (
    LocalHost => '127.0.0.1',
    LocalPort => '12555',
    Proto => 'tcp',
    Listen => 3,
    Reuse => 1,
);
$sock_listen->autoflush ();

my $sock;
while ( $sock = $sock_listen->accept ( ) )
{
    my $data = '';
    $sock->recv ( $data, 4096 );
    print $data . "\n";
}
</code>```

Test #1 result:

```<code>POST / HTTP/1.1
TE: deflate,gzip;q=0.3
Connection: TE, close
Host: 127.0.0.1:12555
User-Agent: libwww-perl/6.05
Content-Length: 162
Content-Type: multipart/form-data; boundary=xYzZY

--xYzZY
Content-Disposition: form-data; name="data2"

0.876556396484375
--xYzZY
Content-Disposition: form-data; name="data1"

0.62921142578125
--xYzZY--
</code>```

Test #2 result:

```<code>POST / HTTP/1.1
TE: deflate,gzip;q=0.3
Connection: TE, close
Host: 127.0.0.1:12555
User-Agent: libwww-perl/6.05
Content-Length: 163
Content-Type: multipart/form-data; boundary=xYzZY

--xYzZY
Content-Disposition: form-data; name="data2"

0.896942138671875
--xYzZY
Content-Disposition: form-data; name="data1"

0.041656494140625
--xYzZY--
</code>```

I added a data:

```<code>        'data3' => '--xYzZY'
</code>```

and got:

```<code>POST / HTTP/1.1
TE: deflate,gzip;q=0.3
Connection: TE, close
Host: 127.0.0.1:12555
User-Agent: libwww-perl/6.05
Content-Length: 221
Content-Type: multipart/form-data; boundary=Tegj

--Tegj
Content-Disposition: form-data; name="data2"

0.34613037109375
--Tegj
Content-Disposition: form-data; name="data3"

--xYzZY
--Tegj
Content-Disposition: form-data; name="data1"

0.678955078125
--Tegj--
</code>```

The question is how i can set the boundary manually to 32 chars string like browser's ----WebKitFormBoundary[...] using LWP?

Or can just use IO::Socket?

答:
LWP allows you set the boundary manually when you do multipart/form-data requests. This feature is unfortunately not documented at all.

However, you have to do multipart explicitly. You can set your own boundary by appending the boundary as an additional field of the Content-Type. It will be converted to a header appropriately by HTTP::Request::Common.

```<code>my $ua = LWP::UserAgent->new;
$ua->post(
    'http://127.0.0.1:12555',
    'Content-Type' =>
        'multipart/form-data;boundary=Nobody-has-the-intention-to-erect-a-wall',
         # ^^^^^^^           ^^^^^^^^

    Content => {
        data1 => rand,
        data2 => rand,
    },
);
</code>```

With your listener, this result in the following output.

```<code>POST / HTTP/1.1
TE: deflate,gzip;q=0.3
Connection: TE, close
Host: 127.0.0.1:12555
User-Agent: libwww-perl/6.15
Content-Length: 269
Content-Type: multipart/form-data; boundary=Nobody-has-the-intention-to-erect-a-wall

--Nobody-has-the-intention-to-erect-a-wall
Content-Disposition: form-data; name="data2"

0.0575856828104122
--Nobody-has-the-intention-to-erect-a-wall
Content-Disposition: form-data; name="data1"

0.677908250902878
--Nobody-has-the-intention-to-erect-a-wall--
</code>```

Note that HTTP::Request::Common will replace your boundary with a random string if it finds the boundary string in the body of any of the parts. It will not just add a number to your boundary.

Body:
I want to post data with content type multipart/form-data:

use strict;
use warnings;

use LWP::UserAgent;

my $ua = LWP::UserAgent->new;
$ua->post (
    'http://127.0.0.1:12555',
    'Content-Type' => 'form-data',
    Content => {
        'data1' => rand,
        'data2' => rand,
    }
);

And i tested the submitted data:

use strict;
use warnings;
use IO::Socket::INET;
use Socket qw ( inet_aton );

my $sock_listen = new IO::Socket::INET (
    LocalHost => '127.0.0.1',
    LocalPort => '12555',
    Proto => 'tcp',
    Listen => 3,
    Reuse => 1,
);
$sock_listen->autoflush ();

my $sock;
while ( $sock = $sock_listen->accept ( ) )
{
    my $data = '';
    $sock->recv ( $data, 4096 );
    print $data . "\n";
}

Test #1 result:

POST / HTTP/1.1
TE: deflate,gzip;q=0.3
Connection: TE, close
Host: 127.0.0.1:12555
User-Agent: libwww-perl/6.05
Content-Length: 162
Content-Type: multipart/form-data; boundary=xYzZY

--xYzZY
Content-Disposition: form-data; name="data2"

0.876556396484375
--xYzZY
Content-Disposition: form-data; name="data1"

0.62921142578125
--xYzZY--

Test #2 result:

POST / HTTP/1.1
TE: deflate,gzip;q=0.3
Connection: TE, close
Host: 127.0.0.1:12555
User-Agent: libwww-perl/6.05
Content-Length: 163
Content-Type: multipart/form-data; boundary=xYzZY

--xYzZY
Content-Disposition: form-data; name="data2"

0.896942138671875
--xYzZY
Content-Disposition: form-data; name="data1"

0.041656494140625
--xYzZY--

I added a data:

        'data3' => '--xYzZY'

and got:

POST / HTTP/1.1
TE: deflate,gzip;q=0.3
Connection: TE, close
Host: 127.0.0.1:12555
User-Agent: libwww-perl/6.05
Content-Length: 221
Content-Type: multipart/form-data; boundary=Tegj

--Tegj
Content-Disposition: form-data; name="data2"

0.34613037109375
--Tegj
Content-Disposition: form-data; name="data3"

--xYzZY
--Tegj
Content-Disposition: form-data; name="data1"

0.678955078125
--Tegj--

The question is how i can set the boundary manually to 32 chars string like browser's ----WebKitFormBoundary[...] using LWP?

Or can just use IO::Socket?

Body:
LWP allows you set the boundary manually when you do multipart/form-data requests. This feature is unfortunately not documented at all.

However, you have to do multipart explicitly. You can set your own boundary by appending the boundary as an additional field of the Content-Type. It will be converted to a header appropriately by HTTP::Request::Common.

my $ua = LWP::UserAgent->new;
$ua->post(
    'http://127.0.0.1:12555',
    'Content-Type' =>
        'multipart/form-data;boundary=Nobody-has-the-intention-to-erect-a-wall',
         # ^^^^^^^           ^^^^^^^^

    Content => {
        data1 => rand,
        data2 => rand,
    },
);

With your listener, this result in the following output.

POST / HTTP/1.1
TE: deflate,gzip;q=0.3
Connection: TE, close
Host: 127.0.0.1:12555
User-Agent: libwww-perl/6.15
Content-Length: 269
Content-Type: multipart/form-data; boundary=Nobody-has-the-intention-to-erect-a-wall

--Nobody-has-the-intention-to-erect-a-wall
Content-Disposition: form-data; name="data2"

0.0575856828104122
--Nobody-has-the-intention-to-erect-a-wall
Content-Disposition: form-data; name="data1"

0.677908250902878
--Nobody-has-the-intention-to-erect-a-wall--

Note that HTTP::Request::Common will replace your boundary with a random string if it finds the boundary string in the body of any of the parts. It will not just add a number to your boundary.


问:
Apply CSS at module level in angular 2
I have developed an application with three big modules. I want to apply some common CSS to 2 modules but the third module will have a different CSS. I do not want to apply the css of the first 2 modules to the third module.

I cannot apply css at component level because each module has many sub modules, component and sub components.

Please suggest a way to implement the CSS at module level.

Thanks In Advance

答:
No, right now you can't do that. It is a pending feature (See this and this).

However you can apply style to bootstrapped component of your module with /deep/ strategy. See this for more info

Title: Apply CSS at module level in angular 2


问:
How to use an Aurelia JSPM plugin with WebPack
I would like to knnow how to use an Aurelia plugin that was made to be used with JSPM. I would like to use it with WebPack. The plugin is Aurelia-Chart and is working great when using it locally in my src folder with .feature('aurelia-chart') (inside the main.js file) but of course the end goal is to use it externally via the .plugin('aurelia-chart').

I believe that the biggest problem is that the plugin is called via an index.js file which is under node_modules\aurelia-chart\dist\commonjs\index.js. This index.js is referencing some other files in deeper directory and I think WebPack is getting lost with the path of these other files.

Inside the index.js

```<code>aurelia.globalResources("./elements/chart-element", "./attributes/chart-attribute");
</code>```

There error that I am getting is

```<code>Unhandled rejection Error: Cannot find module './aurelia-chart/elements/chart-element'.
</code>```

I did try to create the plugin from scratch via the Aurelia Skeleton-Plugin but even the skeleton is built (unless I misunderstood) to be used via JSPM and doesn't handle well WebPack or RequireJS. I also try to remove all the folders and change the paths references to be within the same folder but that didn't help.

I also found this Github issue to be very similar to my issue and the answer to that issue, near the end of the issue, was to use Resource and bundling configuration like so:

```<code>// (package.json)
"aurelia": {
    "build": {
        "resources": [
            {
                "path": "users",
                "bundle": "users",
                "lazy": true
            }
        ]
    }
},
</code>```

I tried reusing this piece of code and change it for the following:

```<code>// (package.json)
    "aurelia-chart": {
        "build": {
            "resources": [
                "./~/aurelia-chart/dist/commonjs/elements/chart-element",
                "./~/aurelia-chart/dist/commonjs/attributes/chart-attribute",
                "./~/aurelia-chart/dist/commonjs/observers/model-observer"
            ]
        }
    }
</code>```

I spent 2 days trying to get it working externally with the .plugin('aurelia-chart') via all kind of bundling process (I took example from aurelia-auth, aurealia-authentication, aurelia-animator-css.) but none of my attempts worked.

Please note again that it does work locally via the .feature('aurelia-chart'). I would like to help the author and the community to use this great plugin (and possibly my own plugins in the future). I have opened a Github issue about the problem, and the author is very great and very helpful but is also clueless on how to make this working in bundling like WebPack or RequireJS (CLI). I would like to have a solution that works with both WebPack and the new Aurelia CLI for bundling.

答:
for latest aurelia-cli (0.32.0) + webpack use chart.js 2.5.0 and use global resources in main.js</p>

```<code>aurelia.use.plugin(PLATFORM.moduleName('aurelia-chart'));
aurelia.use.globalResources(PLATFORM.moduleName('aurelia-chart/elements/chart-element'));
aurelia.use.globalResources(PLATFORM.moduleName('aurelia-chart/attributes/chart-attribute'));
</code>```

Body:
I would like to knnow how to use an Aurelia plugin that was made to be used with JSPM. I would like to use it with WebPack. The plugin is Aurelia-Chart and is working great when using it locally in my src folder with .feature('aurelia-chart') (inside the main.js file) but of course the end goal is to use it externally via the .plugin('aurelia-chart').

I believe that the biggest problem is that the plugin is called via an index.js file which is under node_modules\aurelia-chart\dist\commonjs\index.js. This index.js is referencing some other files in deeper directory and I think WebPack is getting lost with the path of these other files.

Inside the index.js

aurelia.globalResources("./elements/chart-element", "./attributes/chart-attribute");

There error that I am getting is

Unhandled rejection Error: Cannot find module './aurelia-chart/elements/chart-element'.

I did try to create the plugin from scratch via the Aurelia Skeleton-Plugin but even the skeleton is built (unless I misunderstood) to be used via JSPM and doesn't handle well WebPack or RequireJS. I also try to remove all the folders and change the paths references to be within the same folder but that didn't help.

I also found this Github issue to be very similar to my issue and the answer to that issue, near the end of the issue, was to use Resource and bundling configuration like so:

// (package.json)
"aurelia": {
    "build": {
        "resources": [
            {
                "path": "users",
                "bundle": "users",
                "lazy": true
            }
        ]
    }
},

I tried reusing this piece of code and change it for the following:

// (package.json)
    "aurelia-chart": {
        "build": {
            "resources": [
                "./~/aurelia-chart/dist/commonjs/elements/chart-element",
                "./~/aurelia-chart/dist/commonjs/attributes/chart-attribute",
                "./~/aurelia-chart/dist/commonjs/observers/model-observer"
            ]
        }
    }

I spent 2 days trying to get it working externally with the .plugin('aurelia-chart') via all kind of bundling process (I took example from aurelia-auth, aurealia-authentication, aurelia-animator-css.) but none of my attempts worked.

Please note again that it does work locally via the .feature('aurelia-chart'). I would like to help the author and the community to use this great plugin (and possibly my own plugins in the future). I have opened a Github issue about the problem, and the author is very great and very helpful but is also clueless on how to make this working in bundling like WebPack or RequireJS (CLI). I would like to have a solution that works with both WebPack and the new Aurelia CLI for bundling.

Body:
for latest aurelia-cli (0.32.0) + webpack use chart.js 2.5.0 and use global resources in main.js

aurelia.use.plugin(PLATFORM.moduleName('aurelia-chart'));
aurelia.use.globalResources(PLATFORM.moduleName('aurelia-chart/elements/chart-element'));
aurelia.use.globalResources(PLATFORM.moduleName('aurelia-chart/attributes/chart-attribute'));


问:
JSON from php to js
What is the best way to parse a php-variable with json data to js?
On the php-site I have the following:

```<code>  $pdo = new PDO('mysql:host=localhost;dbname=test', 'homedbuser', 'homedbuser');
    $sqlQuery ="SELECT `serie`, `abtrag` FROM `testem`";

    $q = $pdo->query($sqlQuery);

    $result = $q->fetch(PDO::FETCH_ASSOC);

    $rowcount = $q->rowCount();

    $data = array();

    for($x=0; $x < $rowcount-1;$x++){

    $data[]  = $q->fetch(PDO::FETCH_ASSOC);

    $myJson = json_encode($data);

    echo $myJson;

The Output looks like this:

  [
  {"serie":"KK718X","abtrag":"71"},
  {"serie":"KK712X","abtrag":"337"},
  {"serie":"LK719X","abtrag":"93"},
  {"serie":"KK790Y","abtrag":"78"}
 ]
</code>```

Now I want to put the data into a js-variable.

What kind of variable do I have to choose ?
I tried it with axaj / xmlhttp request but that did not work for jet.
Can some one tell, how to do this the right way?

```<code>var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myObj = JSON.parse(this.responseText);
        document.getElementById("show").innerHTML = "myObject[1].serie";
    }
};
xmlhttp.open("GET", "demo_file_array.php", true);
xmlhttp.send();``
</code>```

答:
Here is the code snippet you can use for your XMLHttpRequest's success handler:

```<code>var myObj = JSON.parse(this.responseText);
document.getElementById("show").innerHTML = myObj[1].serie;  // Use myObj not myObject and that too without `""`
</code>```

Title: JSON from php to js

Body:
What is the best way to parse a php-variable with json data to js?
On the php-site I have the following:

  $pdo = new PDO('mysql:host=localhost;dbname=test', 'homedbuser', 'homedbuser');
    $sqlQuery ="SELECT `serie`, `abtrag` FROM `testem`";

    $q = $pdo->query($sqlQuery);

    $result = $q->fetch(PDO::FETCH_ASSOC);

    $rowcount = $q->rowCount();

    $data = array();

    for($x=0; $x < $rowcount-1;$x++){

    $data[]  = $q->fetch(PDO::FETCH_ASSOC);

    $myJson = json_encode($data);

    echo $myJson;

The Output looks like this:

  [
  {"serie":"KK718X","abtrag":"71"},
  {"serie":"KK712X","abtrag":"337"},
  {"serie":"LK719X","abtrag":"93"},
  {"serie":"KK790Y","abtrag":"78"}
 ]

Now I want to put the data into a js-variable.

What kind of variable do I have to choose ?
I tried it with axaj / xmlhttp request but that did not work for jet.
Can some one tell, how to do this the right way?

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myObj = JSON.parse(this.responseText);
        document.getElementById("show").innerHTML = "myObject[1].serie";
    }
};
xmlhttp.open("GET", "demo_file_array.php", true);
xmlhttp.send();``

Body:
Here is the code snippet you can use for your XMLHttpRequest's success handler:

var myObj = JSON.parse(this.responseText);
document.getElementById("show").innerHTML = myObj[1].serie;  // Use myObj not myObject and that too without `""`


问:
Why do I get different results when calling gmock EXPECT_CALL with Times(n) on stack objects and heap objects?

I want to use gmock EXPECT_CALL with Times(n) in my code. I wrote a sample test and got wrong results when calling on objects created using new keyword.  But it worked accurately with stack objects.
Since I am planning to use heap objects in my real testing, I need to know what I am doing wrong here.
Here is my sample code.

```<code>#include <gmock/gmock.h>
#include <gtest/gtest.h>

class Point
{
private:
    int x;
    int y;

public:
    Point(int a, int b)
    {
        this->x = a;
        this->y = b;
    }

    virtual int getSum()
    {
        return x + y;
    }
};

class MockPoint :
        public Point
{
public:
    MockPoint(int a, int b):Point(a,b){}

    MOCK_METHOD0(getSum, int());
};

class PointTests :
        public ::testing::Test
{
};

TEST_F(PointTests, objectTest)
{
    MockPoint p(10, 20);
    EXPECT_CALL(p, getSum()).Times(10);
    p.getSum();
}

TEST_F(PointTests, pointerTest)
{
    MockPoint* p = new MockPoint(10,20);
    EXPECT_CALL(*p, getSum()).Times(10);
    p->getSum();
}
</code>```

I expect to fail both the tests because I call getSum() only one time.

But here are the results I actually get when running the test.

```<code>[ RUN      ] PointTests.objectTest
/home/lasantha/test/PointTests.cpp:44: Failure
Actual function call count doesn't match EXPECT_CALL(p, getSum())...
         Expected: to be called 10 times
           Actual: called once - unsatisfied and active
[  FAILED  ] PointTests.objectTest (0 ms)
[ RUN      ] PointTests.pointerTest
[       OK ] PointTests.pointerTest (0 ms)
[----------] 2 tests from PointTests (0 ms total)
</code>```

答:
You must delete MockPoint to check conditions:</p>

```<code>TEST_F(PointTests, pointerTest)
{
    MockPoint* p = new MockPoint(10,20);
    EXPECT_CALL(*p, getSum()).Times(10);
    p->getSum();
    **delete(p);**
}
</code>```

Body:
I want to use gmock EXPECT_CALL with Times(n) in my code. I wrote a sample test and got wrong results when calling on objects created using new keyword.  But it worked accurately with stack objects.
Since I am planning to use heap objects in my real testing, I need to know what I am doing wrong here.
Here is my sample code.

#include <gmock/gmock.h>
#include <gtest/gtest.h>

class Point
{
private:
    int x;
    int y;

public:
    Point(int a, int b)
    {
        this->x = a;
        this->y = b;
    }

    virtual int getSum()
    {
        return x + y;
    }
};

class MockPoint :
        public Point
{
public:
    MockPoint(int a, int b):Point(a,b){}

    MOCK_METHOD0(getSum, int());
};

class PointTests :
        public ::testing::Test
{
};

TEST_F(PointTests, objectTest)
{
    MockPoint p(10, 20);
    EXPECT_CALL(p, getSum()).Times(10);
    p.getSum();
}

TEST_F(PointTests, pointerTest)
{
    MockPoint* p = new MockPoint(10,20);
    EXPECT_CALL(*p, getSum()).Times(10);
    p->getSum();
}

I expect to fail both the tests because I call getSum() only one time.

But here are the results I actually get when running the test.

[ RUN      ] PointTests.objectTest
/home/lasantha/test/PointTests.cpp:44: Failure
Actual function call count doesn't match EXPECT_CALL(p, getSum())...
         Expected: to be called 10 times
           Actual: called once - unsatisfied and active
[  FAILED  ] PointTests.objectTest (0 ms)
[ RUN      ] PointTests.pointerTest
[       OK ] PointTests.pointerTest (0 ms)
[----------] 2 tests from PointTests (0 ms total)

Body:
You must delete MockPoint to check conditions:

TEST_F(PointTests, pointerTest)
{
    MockPoint* p = new MockPoint(10,20);
    EXPECT_CALL(*p, getSum()).Times(10);
    p->getSum();
    **delete(p);**
}


问:
Place Zooming Image center in UIScrollView in Xamarin.iOS
I want to center the UIImageView and perform the Zoom on That. As per the below code the Zooming is work fine. But my UIImageView start from below NavigationBar. But I want to UIImageView center and also Zoom in center and enlarge the contentSize of UIScrollView in center.

Code :

```<code>scrollView = new UIScrollView();
scrollView.Frame = new CGRect(0, 0, View.Frame.Width, View.Frame.Height - 20.0f);
View.AddSubview(scrollView);

dicom_image = new UIImageView(new CGRect(0, 0, View.Frame.Size.Width,300));
dicom_image.Image = dicomItem.uiimage;

dicom_image.UserInteractionEnabled = true;

if (dicomItem.uiimage != null)
{
    dicom_image.Image = ExtensionMethods.MaxResizeImage(dicomItem.uiimage, (float)UIScreen.MainScreen.Bounds.Width, (float)UIScreen.MainScreen.Bounds.Width);
    dicom_image.ClipsToBounds = true;
    dicom_image.TranslatesAutoresizingMaskIntoConstraints = false;
    dicom_image.SizeToFit();
};
dicom_image.Center = scrollView.Center;

scrollView.ContentSize = scrollView.Frame.Size;
scrollView.AddSubview(dicom_image);

scrollView.MaximumZoomScale = 3f;
scrollView.MinimumZoomScale = 1f;
scrollView.ViewForZoomingInScrollView += (UIScrollView sv) => { return dicom_image; };
</code>```

from the above code zooming is working fine but i want to UIImageView to be center.

Edit :

this code is work fine for Zoom but image start from beginning not the center.

```<code>scrollView = new UIScrollView();
                            scrollView.Frame = new CGRect(0, 0, View.Frame.Width, View.Frame.Height - 20.0f);
                            View.AddSubview(scrollView);

                            dicom_image = new UIImageView(new CGRect(0, 0, View.Frame.Size.Width,300));
                            dicom_image.Image = dicomItem.uiimage;
                                        dicom_image.ContentMode = UIViewContentMode.Center;

                            dicom_image.UserInteractionEnabled = true;

                            if (dicomItem.uiimage != null)
                            {
                                dicom_image.Image = ExtensionMethods.MaxResizeImage(dicomItem.uiimage, (float)UIScreen.MainScreen.Bounds.Width, (float)UIScreen.MainScreen.Bounds.Width);
                                dicom_image.ClipsToBounds = true;
                                dicom_image.TranslatesAutoresizingMaskIntoConstraints = false;
                                dicom_image.SizeToFit();
                            };

                            dicom_image.Center = scrollView.Center;

                            scrollView.ContentSize = dicom_image.Frame.Size;
                            scrollView.AddSubview(dicom_image);

                scrollView.ShowsVerticalScrollIndicator = false;
                scrollView.ShowsHorizontalScrollIndicator = false;

                scrollView.MaximumZoomScale = 3f;
                scrollView.MinimumZoomScale = 1f;
                scrollView.ViewForZoomingInScrollView += (UIScrollView sv) => { return dicom_image; };

                UITapGestureRecognizer doubletap = new UITapGestureRecognizer(OnDoubleTap)
                {
                    NumberOfTapsRequired = 2 // double tap
                };
                scrollView.AddGestureRecognizer(doubletap);
</code>```

Any help be Appreciated.

答:
Since you are not using constraints, you can set the bounds of the UIImageView.

This is a striped down example using a CIFilter to resize the image that I used for an Instagram viewer.

```<code>//someUIImageInstance is a CGImage-backed UIImage
var xScale = (float)(View.Frame.Size.Width / someUIImageInstance.CGImage.Width);
var yScale = (float)(View.Frame.Size.Height / someUIImageInstance.CGImage.Height);
var scale = Math.Max(xScale, yScale);
var lanczosScaleTransform = new CILanczosScaleTransform
{
    Image = someUIImageInstance.CGImage,
    Scale = scale
};
var yPosition = (scale * View.Frame.Size.Height) / 2;
imageView = new UIImageView(new CGRect(0, 0, View.Frame.Size.Width, View.Frame.Size.Height))
{
    Image = UIImage.FromImage(lanczosScaleTransform.OutputImage),
    Bounds = new CGRect(0, yPosition, View.Frame.Size.Width, View.Frame.Size.Height - yPosition),
    UserInteractionEnabled = true,
};
scrollView = new UIScrollView(new CGRect(0, 0, View.Frame.Width, View.Frame.Height))
{
    MinimumZoomScale = 1f,
    MaximumZoomScale = 3f,
    BackgroundColor = UIColor.LightGray
};
scrollView.ViewForZoomingInScrollView = (scrollView) => { return imageView; };

scrollView.AddSubview(imageView);
View.AddSubview(scrollView);
</code>```

Note: It is easier if you use constraints in terms of centering the UIImageView and controlling the center of the viewport as the image is zoomed...

Body:
I want to center the UIImageView and perform the Zoom on That. As per the below code the Zooming is work fine. But my UIImageView start from below NavigationBar. But I want to UIImageView center and also Zoom in center and enlarge the contentSize of UIScrollView in center.

Code :

scrollView = new UIScrollView();
scrollView.Frame = new CGRect(0, 0, View.Frame.Width, View.Frame.Height - 20.0f);
View.AddSubview(scrollView);

dicom_image = new UIImageView(new CGRect(0, 0, View.Frame.Size.Width,300));
dicom_image.Image = dicomItem.uiimage;

dicom_image.UserInteractionEnabled = true;

if (dicomItem.uiimage != null)
{
    dicom_image.Image = ExtensionMethods.MaxResizeImage(dicomItem.uiimage, (float)UIScreen.MainScreen.Bounds.Width, (float)UIScreen.MainScreen.Bounds.Width);
    dicom_image.ClipsToBounds = true;
    dicom_image.TranslatesAutoresizingMaskIntoConstraints = false;
    dicom_image.SizeToFit();
};
dicom_image.Center = scrollView.Center;

scrollView.ContentSize = scrollView.Frame.Size;
scrollView.AddSubview(dicom_image);

scrollView.MaximumZoomScale = 3f;
scrollView.MinimumZoomScale = 1f;
scrollView.ViewForZoomingInScrollView += (UIScrollView sv) => { return dicom_image; };

from the above code zooming is working fine but i want to UIImageView to be center.

Edit :

this code is work fine for Zoom but image start from beginning not the center.

scrollView = new UIScrollView();
                            scrollView.Frame = new CGRect(0, 0, View.Frame.Width, View.Frame.Height - 20.0f);
                            View.AddSubview(scrollView);

                            dicom_image = new UIImageView(new CGRect(0, 0, View.Frame.Size.Width,300));
                            dicom_image.Image = dicomItem.uiimage;
                                        dicom_image.ContentMode = UIViewContentMode.Center;

                            dicom_image.UserInteractionEnabled = true;

                            if (dicomItem.uiimage != null)
                            {
                                dicom_image.Image = ExtensionMethods.MaxResizeImage(dicomItem.uiimage, (float)UIScreen.MainScreen.Bounds.Width, (float)UIScreen.MainScreen.Bounds.Width);
                                dicom_image.ClipsToBounds = true;
                                dicom_image.TranslatesAutoresizingMaskIntoConstraints = false;
                                dicom_image.SizeToFit();
                            };

                            dicom_image.Center = scrollView.Center;

                            scrollView.ContentSize = dicom_image.Frame.Size;
                            scrollView.AddSubview(dicom_image);

                scrollView.ShowsVerticalScrollIndicator = false;
                scrollView.ShowsHorizontalScrollIndicator = false;

                scrollView.MaximumZoomScale = 3f;
                scrollView.MinimumZoomScale = 1f;
                scrollView.ViewForZoomingInScrollView += (UIScrollView sv) => { return dicom_image; };

                UITapGestureRecognizer doubletap = new UITapGestureRecognizer(OnDoubleTap)
                {
                    NumberOfTapsRequired = 2 // double tap
                };
                scrollView.AddGestureRecognizer(doubletap);

Any help be Appreciated.

Body:
Since you are not using constraints, you can set the bounds of the UIImageView.

This is a striped down example using a CIFilter to resize the image that I used for an Instagram viewer.

//someUIImageInstance is a CGImage-backed UIImage
var xScale = (float)(View.Frame.Size.Width / someUIImageInstance.CGImage.Width);
var yScale = (float)(View.Frame.Size.Height / someUIImageInstance.CGImage.Height);
var scale = Math.Max(xScale, yScale);
var lanczosScaleTransform = new CILanczosScaleTransform
{
    Image = someUIImageInstance.CGImage,
    Scale = scale
};
var yPosition = (scale * View.Frame.Size.Height) / 2;
imageView = new UIImageView(new CGRect(0, 0, View.Frame.Size.Width, View.Frame.Size.Height))
{
    Image = UIImage.FromImage(lanczosScaleTransform.OutputImage),
    Bounds = new CGRect(0, yPosition, View.Frame.Size.Width, View.Frame.Size.Height - yPosition),
    UserInteractionEnabled = true,
};
scrollView = new UIScrollView(new CGRect(0, 0, View.Frame.Width, View.Frame.Height))
{
    MinimumZoomScale = 1f,
    MaximumZoomScale = 3f,
    BackgroundColor = UIColor.LightGray
};
scrollView.ViewForZoomingInScrollView = (scrollView) => { return imageView; };

scrollView.AddSubview(imageView);
View.AddSubview(scrollView);

Note: It is easier if you use constraints in terms of centering the UIImageView and controlling the center of the viewport as the image is zoomed...


问:
Firebase 3 - We have blocked all requests from this device due to unusual activity
I was testing my login/sign up feature and for some reason I can't understand Firebase now is blocking all requests from my device.

I've waited one day to try again, but I still have the same problem.

ERROR:
     "We have blocked all requests from this device due to unusual activity. Try again later."

What should I do to have access to my database again?

答:
I've run into the same problem.

By default (for the free plan), firebase caps sign-ins to 100 per hour, per IP-address.
This broke our automated testing. You can change the setting like this:

open console

open your project

go to "authentication"

go to "sign-in method"

scroll down to "manage sign-in quota"

That's it. Currently the maximum setting for this quota is 1000 per hour
.


问:
How to keep the snakemake shell file while running in cluster
While running my snakemake file in cluster I keep getting an error,

```<code>snakemake -j 20 --cluster "qsub -o out.txt -e err.txt -q debug" -s
seadragon/scripts/viral_hisat.snake --config json="<input file>"
output="<output file>"
</code>```

Now this gives me the follwing error,

```<code>Error in job run_salmon while creating output file
/gpfs/home/user/seadragon/output/quant_v2_4/test.
ClusterJobException in line 58 of seadragon/scripts/viral_hisat.snake
:
Error executing rule run_salmon on cluster (jobid: 1, external: 156618.sn-mgmt.cm.cluster, jobscript: /gpfs/home/user/.snakemake/tmp.j9nb0hyo/snakejob.run_salmon.1.sh). For detailed error see the cluster log.
Will exit after finishing currently running jobs.
Exiting because a job execution failed. Look above for error message
</code>```

Now I don't find any way to track the error, since my cluster does not give me an way to store the log files, on the other hand /gpfs/home/user/.snakemake/tmp.j9nb0hyo/snakejob.run_salmon.1.sh file is deleted immediately after finishing.
Please let me know if there is an way to keep this shell file even if the snakemake fails.

答: I am not a qsub user anymore, but if I remember correctly, stdout and stderr are stored in the working directory, under the jobid that Snakemake gives you under external in the error message.

Body:
While running my snakemake file in cluster I keep getting an error,

snakemake -j 20 --cluster "qsub -o out.txt -e err.txt -q debug" -s
seadragon/scripts/viral_hisat.snake --config json="<input file>"
output="<output file>"

Now this gives me the follwing error,

Error in job run_salmon while creating output file
/gpfs/home/user/seadragon/output/quant_v2_4/test.
ClusterJobException in line 58 of seadragon/scripts/viral_hisat.snake
:
Error executing rule run_salmon on cluster (jobid: 1, external: 156618.sn-mgmt.cm.cluster, jobscript: /gpfs/home/user/.snakemake/tmp.j9nb0hyo/snakejob.run_salmon.1.sh). For detailed error see the cluster log.
Will exit after finishing currently running jobs.
Exiting because a job execution failed. Look above for error message

Now I don't find any way to track the error, since my cluster does not give me an way to store the log files, on the other hand /gpfs/home/user/.snakemake/tmp.j9nb0hyo/snakejob.run_salmon.1.sh file is deleted immediately after finishing.
Please let me know if there is an way to keep this shell file even if the snakemake fails.


问:
Write permission when cloning repository in OSX
Whenever I clone a repository using git in OSX Sierra, the default permissions for my applications are read-only. That means that if I open a file of the repo with my IDE of choice, I can't edit it. I know I can chmod 777 the file and then edit it, but it means I'm modifying the file and that counts as a change for git. In addition, doing that each time I clone a repo is an unnecessary mess.

So I have tried setting a custom umask to 000 (write, execute and read by default for all new files), but looks like files from cloned repos keep having read-only permissions.

Any idea on how to fix this? Thanks in advance.

答: So turns out I was using sudo everytime I cloned a repo, so the user got set to root. Using git clone without sudo solved the issue.


问:
How can I implement Text which will support styles object in this reusable component?

I've found this small library on github. I would like to make some changes on it. How can I add a text that supports style object inside the radio button (this component)? So  when use it on the other screens can implement any text inside it and change the default styles. At the moment it doesn't include even default text implementation. Here is the code.

import React, { Component } from 'react'
import { StyleSheet, TouchableOpacity } from 'react-native'
import { View } from 'react-native-animatable'
import PropTypes from 'prop-types'

const DEFAULT_SIZE_MULTIPLIER = 0.7
const DEFAULT_OUTER_BORDER_WIDTH_MULTIPLIER = 0.2

export default class RadioButton extends Component {
  static propTypes = {
    size: PropTypes.number,
    innerColor: PropTypes.string,
    outerColor: PropTypes.string,
    isSelected: PropTypes.bool,
    onPress: PropTypes.func
  }

  static defaultProps = {
    size: 35,
    innerColor: 'dodgerblue',
    outerColor: 'dodgerblue',
    isSelected: false,
    onPress: () => null
  }

  render () {
    const { size, innerColor, outerColor, isSelected, onPress } = this.props
    const outerStyle = {
      borderColor: outerColor,
      width: size + size * DEFAULT_SIZE_MULTIPLIER,
      height: size + size * DEFAULT_SIZE_MULTIPLIER,
      borderRadius: (size + size * DEFAULT_SIZE_MULTIPLIER) / 2,
      borderWidth: size * DEFAULT_OUTER_BORDER_WIDTH_MULTIPLIER
    }

    const innerStyle = {
      width: size,
      height: size,
      borderRadius: size / 2,
      backgroundColor: innerColor
    }

    return (
      <TouchableOpacity style={[styles.radio, outerStyle]} onPress={onPress}>
        {isSelected ? <View style={innerStyle} {...this.props} /> : null}
      </TouchableOpacity>
    )
  }
}

const styles = StyleSheet.create({
  radio: {
    justifyContent: 'center',
    alignItems: 'center',
    alignSelf: 'center'
  }
})
```

How can I implement that new feature that was described in the above?

答:
If you really want to modify it, this could helps.

<Text /> added inside the <RadioButton />.

See comment below.

import React, { Component } from 'react'
import { StyleSheet, TouchableOpacity } from 'react-native'
import { View } from 'react-native-animatable'
import PropTypes from 'prop-types'

const DEFAULT_SIZE_MULTIPLIER = 0.7
const DEFAULT_OUTER_BORDER_WIDTH_MULTIPLIER = 0.2

export default class RadioButton extends Component {
  static propTypes = {
    size: PropTypes.number,
    innerColor: PropTypes.string,
    outerColor: PropTypes.string,
    isSelected: PropTypes.bool,
    onPress: PropTypes.func,

    /// 1) Added new props
    text: PropTypes.string,
    textStyle: PropTypes.oneOfType([
        PropTypes.object,
        PropTypes.number,
    ]),
  }

  static defaultProps = {
    size: 35,
    innerColor: 'dodgerblue',
    outerColor: 'dodgerblue',
    isSelected: false,
    onPress: () => null
  }

  render () {
    const { size, innerColor, outerColor, isSelected, onPress } = this.props
    const outerStyle = {
      borderColor: outerColor,
      width: size + size * DEFAULT_SIZE_MULTIPLIER,
      height: size + size * DEFAULT_SIZE_MULTIPLIER,
      borderRadius: (size + size * DEFAULT_SIZE_MULTIPLIER) / 2,
      borderWidth: size * DEFAULT_OUTER_BORDER_WIDTH_MULTIPLIER
    }

    const innerStyle = {
      width: size,
      height: size,
      borderRadius: size / 2,
      backgroundColor: innerColor
    }

    /// 2) Style for unselected radio - was null in open source
    const innerStyleUnselected = {
        ...innerStyle,
        backgroundColor: transparent,
    }

    /// 3) Put text in. Make sure inner View not null
    return (
      <TouchableOpacity style={[styles.radio, outerStyle]} onPress={onPress}>
        <View style={isSelected ? innerStyle : innerStyleUnselected}>
            <Text style={this.props.textStyle}>{this.props.text}</Text>
        </View>
      </TouchableOpacity>
    )
  }
}

const styles = StyleSheet.create({
  radio: {
    justifyContent: 'center',
    alignItems: 'center',
    alignSelf: 'center'
  }
})
```

Body:
I've found this small library on github. I would like to make some changes on it. How can I add a text that supports style object inside the radio button (this component)? So  when use it on the other screens can implement any text inside it and change the default styles. At the moment it doesn't include even default text implementation. Here is the code.

import React, { Component } from 'react'
import { StyleSheet, TouchableOpacity } from 'react-native'
import { View } from 'react-native-animatable'
import PropTypes from 'prop-types'

const DEFAULT_SIZE_MULTIPLIER = 0.7
const DEFAULT_OUTER_BORDER_WIDTH_MULTIPLIER = 0.2

export default class RadioButton extends Component {
  static propTypes = {
    size: PropTypes.number,
    innerColor: PropTypes.string,
    outerColor: PropTypes.string,
    isSelected: PropTypes.bool,
    onPress: PropTypes.func
  }

  static defaultProps = {
    size: 35,
    innerColor: 'dodgerblue',
    outerColor: 'dodgerblue',
    isSelected: false,
    onPress: () => null
  }

  render () {
    const { size, innerColor, outerColor, isSelected, onPress } = this.props
    const outerStyle = {
      borderColor: outerColor,
      width: size + size * DEFAULT_SIZE_MULTIPLIER,
      height: size + size * DEFAULT_SIZE_MULTIPLIER,
      borderRadius: (size + size * DEFAULT_SIZE_MULTIPLIER) / 2,
      borderWidth: size * DEFAULT_OUTER_BORDER_WIDTH_MULTIPLIER
    }

    const innerStyle = {
      width: size,
      height: size,
      borderRadius: size / 2,
      backgroundColor: innerColor
    }

    return (
      <TouchableOpacity style={[styles.radio, outerStyle]} onPress={onPress}>
        {isSelected ? <View style={innerStyle} {...this.props} /> : null}
      </TouchableOpacity>
    )
  }
}

const styles = StyleSheet.create({
  radio: {
    justifyContent: 'center',
    alignItems: 'center',
    alignSelf: 'center'
  }
})

How can I implement that new feature that was described in the above?


问:
How to get ansible to stay on the machine after finishing a task?
I am using ansible to run a task which starts up build engines. Once they have all started, ansible returns control to me and I see that they all stop at once. When I add an async: 10 flag to the running of the script it works, but the problem is when there are multiple build engines it takes longer than 10 seconds for them to start, which makes the async kind of null.

I have tried using a

```<code>- pause:
  seconds: 10
</code>```

task below the running of the script, but the build engines stop, then it does the pause.

What I am asking is - Is there a way to make ansible stick around on the machine for a few seconds after it has finished running the command (i.e. after control has been returned to user)?

答:
Tried wait_for but that seems to exit the environment and then perform the task.
I fixed this problem by using the following in my shell execution task:

```<code>async: 300
poll: 5
</code>```

This runs the task asynchronously and polls every 5 seconds for a response.

Body:
I am using ansible to run a task which starts up build engines. Once they have all started, ansible returns control to me and I see that they all stop at once. When I add an async: 10 flag to the running of the script it works, but the problem is when there are multiple build engines it takes longer than 10 seconds for them to start, which makes the async kind of null.

I have tried using a

- pause:
  seconds: 10

task below the running of the script, but the build engines stop, then it does the pause.

What I am asking is - Is there a way to make ansible stick around on the machine for a few seconds after it has finished running the command (i.e. after control has been returned to user)?

Body:
Tried wait_for but that seems to exit the environment and then perform the task.
I fixed this problem by using the following in my shell execution task:

async: 300
poll: 5

This runs the task asynchronously and polls every 5 seconds for a response.


问:
How can I deploy an application to Hololens without VS?
I've developed an application for Hololens, so the only way I know to install the application in hololens is by visual studio, so I want an application package to be able to install without needing Visual Studio. I tried to follow this tutorial here

"https://learn.microsoft.com/pt-br/windows/uwp/packaging/create-app-package-with-makeappx-tool"

but I can not find these two .appx and .appxsym files.

If anyone knew, I appreciate that.

答:
Maybe you know some steps, but I will go the full way (it's only deploying without visual Studio):

In Unity:

File> Build Settings

Choose Universal Windows Plattform (older Versions Windows Store). Make sure your settings are right (for hololens, sdk enabled...)

hit "Build"

Now you have to select a Folder to build. In my Projects I create just an "App" Folder

Once it is build navigate to this Folder (if it's not opening automatically).

Open the Solution (in the App Folder, not the Unity one)

In the Explorer right Click on the "Project Properties" which are named like your Project and Select "Store>create App Package (or maybe build, i got it on German)"

If you want only the appx File select "no" at the Windows Store question

Select an Output Folder and Version Number (count's up itself, newer numbers will overwrite older versions on Hololens automatically) and for Hololens only select x86 (the others are not needed. Just consume time). Now hit the "create"(again i hope i translate it right) Button.

Apply on Hololens:

Connect the hololens via USB (you can do it with wifi too, but not in our Network, so i never tried)

Open a browser and type "127.0.0.1:10080" so you get access to your hololens

Navigate to "System>Apps" and under Install App select the appx file (in my case under: (myUnityProject/App/AppPackages/myUnityProject/myUnityProject_1.0.0.0_Win32_Master_Test)

First time deploying select the dependencies (Dependencies/x86)

Hit "go" to Deploy (wait until everything is uploaded)

Some Notes:

To build the Apps i needed mvs 2015 installed (just installed), but this was before the Fall creators Update. Now newer Versions (should) work fine. Also I needed to install the windows "buildtools 2015"
https://www.microsoft.com/de-de/download/details.aspx?id=48159

Hope it works and have fun!