问:
Reset dropdown menu details after re-open or close it
CODE :

```<code><head>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script
    src="https://code.jquery.com/ui/1.9.2/jquery-ui.min.js"
    integrity="sha256-eEa1kEtgK9ZL6h60VXwDsJ2rxYCwfxi40VZ9E0XwoEA="
    crossorigin="anonymous"></script>
</head>
<body>

<div class="dropdown bigdiv">
  <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Dropdown Example
    <span class="caret"></span></button>
  <ul class="dropdown-menu bigul">
    <li>
        <a href="#" id="open_input">open_input</a>
    </li>

    <ul class="list-group test">
    </ul>
  </ul>
</div>

</body>
<script>
    $(document).ready(function () {
        var availableTags = [
            "ActionScript",
            "AppleScript",
            "Asp",
            "BASIC",
            "C",
            "C++",
            "Clojure",
            "COBOL",
            "ColdFusion",
            "Erlang",
            "Fortran",
        ];

        var ul_text = '    <li class="ui-widget">\n' +
            '<form role="form" style="">\n' +
            '                <div class="input-group input-group-sm" style="">\n' +
            '                  <input type="text" class="form-control" id="tags" placeholder="Enter email">\n' +
            '                </div>\n' +
            '              </form>\n' +
            '    </li>'

        $('#open_input').click(function (e) {
            $('.bigul').append(ul_text)

            $('#tags').autocomplete({
                    search: function(event, ui) {
                        $('.test').empty();
                    },
                    source: availableTags,
                    messages: {
                        noResults: '',
                        results: function() {}
                    }
                }).data('autocomplete')._renderItem = function(ul, item) {
                    return $('<li class="list-group-item"></li>')
                        .data('item.autocomplete', item)
                        .append(item.value)
                        .appendTo($('.test'));
                    };
            e.stopPropagation();
        });
    });
</script>
</code>```

And jsfiddle : http://jsfiddle.net/uMqyn/919/

On my code, dropdown menu can be changed by click open_input or search things with input bar.

But I want that if i close dropdown menu whether by re-click dropdown button or by other empty space clicking or something, dropdown menu will be refreshing as initial status.

In other words, whenever I open dropdown menu, I want that what I can see on dropdown menu is staying the same-just only -

```<code>  <ul class="dropdown-menu bigul">
    <li>
        <a href="#" id="open_input">open_input</a>
    </li>

    <ul class="list-group test">
    </ul>
  </ul>
</code>```

Question : I ask that any changed things on dropdown menu cannot be seen when next dropdown re-open. I want to make dropdown menu's initial status remain unchanged.

How can I do this?

答:
Edits: I realized we cannot use .focusout because clicking on the dropdown menu's children elements (e.g. the input texts) will clear out the dropdown menu of its li.ui-widget children.

The solution is to use the Bootstrap dropdown close event hide.bs.dropdown to detect whether we've closed the menu.

```<code>$('.bigdiv').on('hide.bs.dropdown', function () {
    $('.bigul .ui-widget').remove()
    console.log('removing')
})
</code>```

Fiddle: http://jsfiddle.net/uMqyn/924/

Got the idea from: https://stackoverflow.com/a/31444063/3891117

If you're using Bootstrap v2.3.2, in the same link says to use click.dropdown.data-api event.

Body:
CODE :

    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">

  <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Dropdown Example
    </button>

        open_input

And jsfiddle : http://jsfiddle.net/uMqyn/919/

On my code, dropdown menu can be changed by click open_input or search things with input bar.

But I want that if i close dropdown menu whether by re-click dropdown button or by other empty space clicking or something, dropdown menu will be refreshing as initial status.

In other words, whenever I open dropdown menu, I want that what I can see on dropdown menu is staying the same-just only -

        open_input

Question : I ask that any changed things on dropdown menu cannot be seen when next dropdown re-open. I want to make dropdown menu's initial status remain unchanged.

How can I do this?

Body:
Edits: I realized we cannot use .focusout because clicking on the dropdown menu's children elements (e.g. the input texts) will clear out the dropdown menu of its li.ui-widget children.

The solution is to use the Bootstrap dropdown close event hide.bs.dropdown to detect whether we've closed the menu.

$('.bigdiv').on('hide.bs.dropdown', function () {
    $('.bigul .ui-widget').remove()
    console.log('removing')
})

Fiddle: http://jsfiddle.net/uMqyn/924/

Got the idea from: https://stackoverflow.com/a/31444063/3891117

If you're using Bootstrap v2.3.2, in the same link says to use click.dropdown.data-api event.


来源: stackexchange

问:
Cannot resolve method findViewById(int) - Edit Text to Date Picker
Can anyone tell me what the error is with my code shown below. Trying to use Edit Text to open a date picker dialog but it's showing error cannot resolve method findViewById(int)

package com.example.claire.townapp;
import java.util.Calendar;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;

@SuppressLint("ValidFragment")
public class DateDialog extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
EditText txtdate;
public DateDialog(View view){
    txtdate=(EditText)view;
}
public Dialog onCreateDialog(Bundle savedInstanceState) {

// Use the current date as the default date in the dialog
    final Calendar c = Calendar.getInstance();
    int year = c.get(Calendar.YEAR);
    int month = c.get(Calendar.MONTH);
    int day = c.get(Calendar.DAY_OF_MONTH);
    // Create a new instance of DatePickerDialog and return it
    return new DatePickerDialog(getActivity(), this, year, month, day);

}

public void onDateSet(DatePicker view, int year, int month, int day) {
    //show to the selected date in the text box
    String date=day+"-"+(month+1)+"-"+year;
    txtdate.setText(date);
}

public void onStart(){
    super.onStart();

    EditText txtDate = (EditText)findViewById(R.id.txtdate);
    txtDate.setOnFocusChangeListener(new View.OnFocusChangeListener(){
        public void onFocusChange(View view, boolean hasfocus){
            if(hasfocus){
                DateDialog dialog=new DateDialog(view);
                FragmentTransaction ft =getFragmentManager().beginTransaction();
                dialog.show(ft, "DatePicker");

    }
}
```

Does anyone know how I can resolve this error? Any help is much appreciated!

答:
The reason you're code isn't working is because findViewById(int resID) isn't a method on Fragment like it is for Activity. You need a valid object such as a  view to call  findViewById(). AlertDialogs happen to have a utility method that allows you to check its layout for a View similar to View (in fact, behind the scenes it's simply passing the call through to its own View object 'mWindow'). Get a reference to the dialog and and call findViewById() passing a reference to the EditText you want.

I don't believe your code will work because you don't have any control over your layout since you are simply wrapping a DatePickerDialog with a fragment. Be careful since you are using a framework class you need to be aware of the View's inside of its window. For example. I peeked into the source code of DataPickerDialog and I didn't find any references to a View with the id of 'txtdate' or even a EditText (I may be wrong, didn't look to thoroughly). Passing that value in to findViewById(int resid) you will return a null. You could also get a ClassCastException, if it happens to contains a View with that id but of a different View type, so pay special care to view type as well.

ContentLicense: CC BY-SA 3.0

Body:
Can anyone tell me what the error is with my code shown below. Trying to use Edit Text to open a date picker dialog but it's showing error cannot resolve method findViewById(int)

package com.example.claire.townapp;
import java.util.Calendar;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;

@SuppressLint("ValidFragment")
public class DateDialog extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
EditText txtdate;
public DateDialog(View view){
    txtdate=(EditText)view;
}
public Dialog onCreateDialog(Bundle savedInstanceState) {

// Use the current date as the default date in the dialog
    final Calendar c = Calendar.getInstance();
    int year = c.get(Calendar.YEAR);
    int month = c.get(Calendar.MONTH);
    int day = c.get(Calendar.DAY_OF_MONTH);
    // Create a new instance of DatePickerDialog and return it
    return new DatePickerDialog(getActivity(), this, year, month, day);

}

public void onDateSet(DatePicker view, int year, int month, int day) {
    //show to the selected date in the text box
    String date=day+"-"+(month+1)+"-"+year;
    txtdate.setText(date);
}

public void onStart(){
    super.onStart();

    EditText txtDate = (EditText)findViewById(R.id.txtdate);
    txtDate.setOnFocusChangeListener(new View.OnFocusChangeListener(){
        public void onFocusChange(View view, boolean hasfocus){
            if(hasfocus){
                DateDialog dialog=new DateDialog(view);
                FragmentTransaction ft =getFragmentManager().beginTransaction();
                dialog.show(ft, "DatePicker");

    }
}

Does anyone know how I can resolve this error? Any help is much appreciated!

ContentLicense: CC BY-SA 4.0


问:
How does Hyperledger composer handle endorsements
I have been reading about endorsement policies e.g.here and do understand that they determine which transactions are saved in the block chain in Hyperledger Fabric v1.

I am wondering how I can be able to transfer an asset across multiple stages e.g. as shown here. Is it one transaction that goes through multiple stages in order to be approved i.e. using endorsement policies? Or there are many transactions, each with its own policies.

Either way, I would like to have a transaction approved by a different user e.g. admin MANUALLY before it's saved or rejected on the block chain. Could endorsement policies help me in this?

My thinking is that each transaction is usually submitted by 1 participant. Then, how do the endorsement policies that require a transaction to be signed by two participants work? Is it that there is another signing process separately where endorsers sign transactions explicitly?

Any guidance in the right direction will be highly appreciated.

答:
To some degree, you may be slightly confusing Fabric endorsement policies with application (business logic) based multi-stage approval (across multi-orgs) as shown in the car lease demo, and following the lifecycle of a vehicle (post-approvals etc).

A Fabric endorsement policy can be based on Fabric keys or identities relating to the deployed network for example - and define a set of endorsers based on identity in a multi-org setup.

As mentioned in the issue https://github.com/hyperledger/composer/issues/1251 you refer to - Composer provides a (multi-org) example of what is (ultimately) a Fabric endorsement policy (eg the -O example on July 4) and the ability to 'pass those on' as a passthrough mechanism for what is ultimately Fabric policy parameters if that's what you want to do. As shown in the example, they can be related to the Fabric identities. See more here -> http://hyperledger-fabric.readthedocs.io/en/release/arch-deep-dive.html?highlight=endorsement#endorsement-policies

As for your approval process you described - you can capture the approval process (its a business approvals process) using Composer, so the 'appropriate participant' (application user from whatever org) gets notified of a request transaction (eg notified using Composer Events) that he/she needs to generate an approval (a separate transaction - so the ledger shows it was approved), and then the asset can be transferred (triggered upon approval - based on approver from a role in an Org for example**).

**If you wish, you can create a Participant that is a role to be the 'Approver' (a participant can have multiple identities, that have authority to 'approve' - and you can always trace 'which' identity performed the approval). The asset may then (potentially) move on to another, intermediate transfer stage, and then there is another [business] process step that takes it to the next stage (whatever that is). The organisations are sharing the same business network on the same ledger/channel, so to me you would do this through Composer.


问:
laravel image upload error
i'm using intervention package to upload images with laravel and all things are fine from creating to saving image but the problem in the image column in database it stores this name with path

/private/var/folders/18/0w78rt691m99y_kv8xln4n0c0000gn/T/phpFkP3Gh

this is my code:

```<code>if($request->hasFile('image')) {
  $image = $request->file('image');
  $filename = time() . '.' . $image->getClientOriginalExtension();
  $location = public_path('images/' . $filename);
  \Image::make($image)->save($location);
 }
</code>```

and this is the image name stored in images file 1503847676.jpg

please help me to find, where is the problem?

this is my whole method

```<code>public function update(Request $request, $id)
    {

        // Validating fields requests
        $this->validate($request, [

            'title'     =>  'required|min:6',
            'subtitle'  =>  'required|min:6',
            'slug'      =>  'required',
            'body'      =>  'required',
            'image'     =>  'required|mimes:jpeg,png,jpg,gif,svg'
        ]);

        if($request->hasFile('image')) {
           $image = $request->file('image');
           $filename = time() . '.' . $image->getClientOriginalExtension();
           $location = public_path('images/' . $filename);
           \Image::make($image)->save($location);
        }

        //find target post
        $post = Post::find($id);

        //create upadeted data from inputs fields
        $post->title = $request->title;
        $post->subtitle = $request->subtitle;
        $post->image = $filename;
        $post->slug = $request->slug;
        $post->image = $request->image;
        $post->status = $request->status;
        $post->body = $request->body;

        //save the new data to database
        $post->save();
        $post->tags()->sync($request->tags);
        $post->categories()->sync($request->categories);

        return redirect('/admin/post');

    }
</code>```

答:
You can try this if you use Intervention image</p>

```<code>$image = Input::file('image');
$filename  = time() . '.' . $image->getClientOriginalName();
$path = public_path('images/' . $filename);
Image::make($image->getRealPath())->save($path);
$post->image = 'images/' . $filename;
</code>```

Title: laravel image upload error

Body:
i'm using intervention package to upload images with laravel and all things are fine from creating to saving image but the problem in the image column in database it stores this name with path

/private/var/folders/18/0w78rt691m99y_kv8xln4n0c0000gn/T/phpFkP3Gh

this is my code:

if($request->hasFile('image')) {
  $image = $request->file('image');
  $filename = time() . '.' . $image->getClientOriginalExtension();
  $location = public_path('images/' . $filename);
  \Image::make($image)->save($location);
 }

and this is the image name stored in images file 1503847676.jpg

please help me to find, where is the problem?

this is my whole method

public function update(Request $request, $id)
    {

        // Validating fields requests
        $this->validate($request, [

            'title'     =>  'required|min:6',
            'subtitle'  =>  'required|min:6',
            'slug'      =>  'required',
            'body'      =>  'required',
            'image'     =>  'required|mimes:jpeg,png,jpg,gif,svg'
        ]);

        if($request->hasFile('image')) {
           $image = $request->file('image');
           $filename = time() . '.' . $image->getClientOriginalExtension();
           $location = public_path('images/' . $filename);
           \Image::make($image)->save($location);
        }

        //find target post
        $post = Post::find($id);

        //create upadeted data from inputs fields
        $post->title = $request->title;
        $post->subtitle = $request->subtitle;
        $post->image = $filename;
        $post->slug = $request->slug;
        $post->image = $request->image;
        $post->status = $request->status;
        $post->body = $request->body;

        //save the new data to database
        $post->save();
        $post->tags()->sync($request->tags);
        $post->categories()->sync($request->categories);

        return redirect('/admin/post');

    }

Body:
You can try this if you use Intervention image

$image = Input::file('image');
$filename  = time() . '.' . $image->getClientOriginalName();
$path = public_path('images/' . $filename);
Image::make($image->getRealPath())->save($path);
$post->image = 'images/' . $filename;


问:
How to return all movies with the same crew in neo4j?
As I am new to neo4j, I am currently experimenting with the neo4j movie database sample.

I was wondering what the best way was to compare subgraphs and relationships, for example, how to get all movies with identical crew.

Based on other questions here on stackoverflow, I got it to work to return all movies where specific actors acted in together:

```<code>WITH ['Tom Hanks', 'Meg Ryan'] as names
MATCH (p:Person)
WHERE p.name in names
WITH collect(p) as persons
WITH head(persons) as head, tail(persons) as persons
MATCH (head)-[:ACTED_IN]->(m:Movie)
WHERE ALL(p in persons WHERE (p)-[:ACTED_IN]->(m))
RETURN m.title
</code>```

But, how could I retrieve movies with identical actors without specifying the actors names?

答:
Some alternate approaches that may be more efficient (check using PROFILE):

Only match from movies to actors once, then collect them and UNWIND them the number of times you need to generate cross products, then filter out and compare. This saves you from having to hit the db multiple times, since all you need is the data obtained from the first match. I'm going to borrow Bruno's query and tweak it a bit.

```<code>// match the first movie and all its actors
match (m1:Movie)<-[:ACTED_IN]-(a1:Person)
// order actors by name
with m1, a1 order by a1.name
// store ordered actors into actors1 variable
with m1, collect(a1) as actors1
// collect this data into a single collection
with collect({m:m1, actors:actors1}) as data
// generate cross product of the data
unwind data as d1
unwind data as d2
with d1, d2
// prevent comparison against the same movie, or the same pairs in different orders
where id(d1.m) < id(d2.m) and d1.actors = d2.actors
// return movies that have the same actors
return d1.m, d2.m
</code>```

Alternately, you can group movies by their actors and only return movies that are grouped accordingly:

```<code>// match the first movie and all its actors
match (m1:Movie)<-[:ACTED_IN]-(a1:Person)
// order actors by name
with m1, a1 order by a1.name
// store ordered actors into actors1 variable
with m1, collect(a1) as actors1
// group movies with their sets of actors
with collect(m1) as movies, actors1
// only interested in where multiple movies have the same actor sets
where size(movies) > 1
// return the collection of movies with the same actors
return movies
</code>```

The second query is likely better here, as you get all movies with the same cast, rather than getting pairs per row.

Body:
As I am new to neo4j, I am currently experimenting with the neo4j movie database sample.

I was wondering what the best way was to compare subgraphs and relationships, for example, how to get all movies with identical crew.

Based on other questions here on stackoverflow, I got it to work to return all movies where specific actors acted in together:

WITH ['Tom Hanks', 'Meg Ryan'] as names
MATCH (p:Person)
WHERE p.name in names
WITH collect(p) as persons
WITH head(persons) as head, tail(persons) as persons
MATCH (head)-[:ACTED_IN]->(m:Movie)
WHERE ALL(p in persons WHERE (p)-[:ACTED_IN]->(m))
RETURN m.title

But, how could I retrieve movies with identical actors without specifying the actors names?

Body:
Some alternate approaches that may be more efficient (check using PROFILE):

Only match from movies to actors once, then collect them and UNWIND them the number of times you need to generate cross products, then filter out and compare. This saves you from having to hit the db multiple times, since all you need is the data obtained from the first match. I'm going to borrow Bruno's query and tweak it a bit.

// match the first movie and all its actors
match (m1:Movie)<-[:ACTED_IN]-(a1:Person)
// order actors by name
with m1, a1 order by a1.name
// store ordered actors into actors1 variable
with m1, collect(a1) as actors1
// collect this data into a single collection
with collect({m:m1, actors:actors1}) as data
// generate cross product of the data
unwind data as d1
unwind data as d2
with d1, d2
// prevent comparison against the same movie, or the same pairs in different orders
where id(d1.m) < id(d2.m) and d1.actors = d2.actors
// return movies that have the same actors
return d1.m, d2.m

Alternately, you can group movies by their actors and only return movies that are grouped accordingly:

// match the first movie and all its actors
match (m1:Movie)<-[:ACTED_IN]-(a1:Person)
// order actors by name
with m1, a1 order by a1.name
// store ordered actors into actors1 variable
with m1, collect(a1) as actors1
// group movies with their sets of actors
with collect(m1) as movies, actors1
// only interested in where multiple movies have the same actor sets
where size(movies) > 1
// return the collection of movies with the same actors
return movies

The second query is likely better here, as you get all movies with the same cast, rather than getting pairs per row.


问:
Rest vs Soap consuming
Can anyone help me understanding difference between consuming rest service is different from consuming soap service code wise ?

I need core difference in consuming them

答:
To me core difference is:

SOAP resides on payload format level while REST is on communication level. Nothing prevents to send SOAP payload through the REST endpoint.

Because of that:

SOAP is XML based payload, strictly following WSDL specification and code must consume it accordingly, while REST defines nothing about payload, just a communication.

SOAP does not define any transport layers, while REST is only about communication through HTTP. SOAP can be send through any channels - HTTP, JMS, FTP, physically CD/DVD ... who cares :-)

Through HTTP SOAP webservice uses only HTTP POST method, while REST defines different HTTP methods for different operations - GET to retrive data, POST to add data, PATCH/POSt to modify existing data and so on...

Title: Rest vs Soap consuming


问:
How to query database for case sensitive values
I'm checking a few values in my database and it appears that the strings being compared are not being case sensitive enforced. I'm using C# and LINQ to SQL.</p>

答:
Check the collation matrix provided here:

http://msdn.microsoft.com/en-us/library/ms144250.aspx

I think you will need something like SQL_Latin1_General_Cp437_CS_AS_KI_WI

ContentLicense: CC BY-SA 2.5


问:
UICollectionView not showing images after unhiding it
I have an UICollectionView that starts hidden in the viewDidLoad, then when an image is added with the UIImagePicker delegate the collection goes "unhidden" and then reloads, here is the code below

```<code>func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        self.imagesToSend.append(pickedImage)
    }

    self.imagenesCollectionView.isHidden = false
    self.imagenesCollectionView.reloadData()
    dismiss(animated: true, completion:nil)
}
</code>```

the problem is that when the collection shows it doesn't show any image, I have to add a second image so the image can show, I want the collection to show when there are images and to hide when there aren't images, until now the hiding functionality its working fine, but not the showing one.

答:
Try adding

```<code>self.imagenesCollectionView.isHidden = false
self.imagenesCollectionView.reloadData()
</code>```

in dismiss completion handler. Like

```<code>dismiss(animated: true, completion:{
    self.imagenesCollectionView.isHidden = false
    self.imagenesCollectionView.reloadData()
})
</code>```

Edit 1:
      Instead of reloading collection view in completion. add collection view reload in viewWillAppear method based on the array data availability.

eg:

```<code>if self.imagesToSend.count > 0 {
    self.imagenesCollectionView.isHidden = false
    self.imagenesCollectionView.reloadData()
} else {
    self.imagenesCollectionView.isHidden = true
}
</code>```

Body:
I have an UICollectionView that starts hidden in the viewDidLoad, then when an image is added with the UIImagePicker delegate the collection goes "unhidden" and then reloads, here is the code below

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        self.imagesToSend.append(pickedImage)
    }

    self.imagenesCollectionView.isHidden = false
    self.imagenesCollectionView.reloadData()
    dismiss(animated: true, completion:nil)
}

the problem is that when the collection shows it doesn't show any image, I have to add a second image so the image can show, I want the collection to show when there are images and to hide when there aren't images, until now the hiding functionality its working fine, but not the showing one.

Body:
Try adding

self.imagenesCollectionView.isHidden = false
self.imagenesCollectionView.reloadData()

in dismiss completion handler. Like

dismiss(animated: true, completion:{
    self.imagenesCollectionView.isHidden = false
    self.imagenesCollectionView.reloadData()
})

Edit 1:
      Instead of reloading collection view in completion. add collection view reload in viewWillAppear method based on the array data availability.

eg:

if self.imagesToSend.count > 0 {
    self.imagenesCollectionView.isHidden = false
    self.imagenesCollectionView.reloadData()
} else {
    self.imagenesCollectionView.isHidden = true
}


答:
In SQL Server, whether a column is case sensitive or not depends on what collation you've applied to it.

The default collation is likely "SQL_Latin1_General_CP1_CI_AS" (CI being "case insensitive"). If you change your database schema so that column has the collation "SQL_Latin1_General_CP1_CS_AS" instead, then queries on it will be case-sensitive.

Title: How to query database for case sensitive values

Body: I'm checking a few values in my database and it appears that the strings being compared are not being case sensitive enforced. I'm using C# and LINQ to SQL.


问:
Django signals creates for the same model
I am trying to make a signal that creates a Client object or Director object depending on the type of the CustomUser:

```<code>class CustomUser(AbstractEmailUser):
    TYPE = (
        (0, 'Client'),
        (1, 'Director'),

    type = models.PositiveSmallIntegerField(default=0, choices=TYPE)

class Client(models.Model):
    user = models.OneToOneField(CustomUser)

class Director(models.Model):
    user = models.OneToOneField(CustomUser)

def post_save_data(sender, instance, created, **kwargs):
    if created and CustomUser.objects.get(email=instance.email).type == 0:
        Client.objects.create(user=instance)
    elif created and CustomUser.objects.get(email=instance.email).type == 1:
        Director.objects.create(user=instance)

post_save.connect(post_save_data, sender=CustomUser)
</code>```

Whatever i do it always creates object for Client, even if i choose type 1.

答:
I am using the following code and from django admin if I create Custom user by selecting Client, it creates client and if select Director it creates Director.

```<code>class AbstractEmailUser(models.Model):
    email = models.TextField(max_length=100)

class CustomUser(AbstractEmailUser):
    TYPE = (
        (0, 'Client'),
        (1, 'Director'),
    )

    type = models.PositiveSmallIntegerField(default=0, choices=TYPE)

class Client(models.Model):
    user = models.OneToOneField(CustomUser)

class Director(models.Model):
    user = models.OneToOneField(CustomUser)

def post_save_data(sender, instance, created, **kwargs):
    # if created and CustomUser.objects.get(email=instance.email).type == 0:
    #     Client.objects.create(user=instance)
    # elif created and CustomUser.objects.get(email=instance.email).type == 1:
    #     Director.objects.create(user=instance)
    if created:
        c_user = CustomUser.objects.get(email=instance.email)
        print(c_user.type)
        if c_user.type == 0:
            Client.objects.create(user=instance)
        elif c_user.type == 1:
            Director.objects.create(user=instance)

post_save.connect(post_save_data, sender=CustomUser)
</code>```

The commented code above on post_save_data also worked for me. I have used AbstractEmailUser class as a sample.

Body:
I am trying to make a signal that creates a Client object or Director object depending on the type of the CustomUser:

class CustomUser(AbstractEmailUser):
    TYPE = (
        (0, 'Client'),
        (1, 'Director'),

    type = models.PositiveSmallIntegerField(default=0, choices=TYPE)

class Client(models.Model):
    user = models.OneToOneField(CustomUser)

class Director(models.Model):
    user = models.OneToOneField(CustomUser)

def post_save_data(sender, instance, created, **kwargs):
    if created and CustomUser.objects.get(email=instance.email).type == 0:
        Client.objects.create(user=instance)
    elif created and CustomUser.objects.get(email=instance.email).type == 1:
        Director.objects.create(user=instance)

post_save.connect(post_save_data, sender=CustomUser)

Whatever i do it always creates object for Client, even if i choose type 1.

Body:
I am using the following code and from django admin if I create Custom user by selecting Client, it creates client and if select Director it creates Director.

class AbstractEmailUser(models.Model):
    email = models.TextField(max_length=100)

class CustomUser(AbstractEmailUser):
    TYPE = (
        (0, 'Client'),
        (1, 'Director'),
    )

    type = models.PositiveSmallIntegerField(default=0, choices=TYPE)

class Client(models.Model):
    user = models.OneToOneField(CustomUser)

class Director(models.Model):
    user = models.OneToOneField(CustomUser)

def post_save_data(sender, instance, created, **kwargs):
    # if created and CustomUser.objects.get(email=instance.email).type == 0:
    #     Client.objects.create(user=instance)
    # elif created and CustomUser.objects.get(email=instance.email).type == 1:
    #     Director.objects.create(user=instance)
    if created:
        c_user = CustomUser.objects.get(email=instance.email)
        print(c_user.type)
        if c_user.type == 0:
            Client.objects.create(user=instance)
        elif c_user.type == 1:
            Director.objects.create(user=instance)

post_save.connect(post_save_data, sender=CustomUser)

The commented code above on post_save_data also worked for me. I have used AbstractEmailUser class as a sample.


问:
Hazelcast - Client mode - How to recover after cluster failure?
We are using hazelcast distributed lock and cache functions in our products. Usage of  distributed locking is vitally important for our business logic.

Currently we are using the embedded mode(each application node is also a hazelcast cluster member). We are going to switch to client - server mode.

The problem we have noticed for client - server is that, once the cluster is down for a period, after several attempts clients are destroyed and any objects (maps, sets, etc.) that were retrieved from that client are no longer usable.
Also the client instance does not recover even after the Hazelcast cluster comes back up (we receive HazelcastInstanceNotActiveException )

I know that this issue has been addressed several times and ended up as being a feature request:

issue1

issue2

issue3

My question : What should be the strategy to recover the client? Currently we are planning to enqueue a task in the client process as below. Based on a condition it will try to restart the client instance...
We will check whether the client is running or not via clientInstance.getLifecycleService().isRunning() check.

Here is the task code:

```<code>private class ClientModeHazelcastInstanceReconnectorTask implements Runnable {

    @Override
    public void run() {
        try {
            HazelCastService hazelcastService = HazelCastService.getInstance();
            HazelcastInstance clientInstance = hazelcastService.getHazelcastInstance();
            boolean running = clientInstance.getLifecycleService().isRunning();
            if (!running) {
                logger.info("Current clientInstance is NOT running. Trying to start hazelcastInstance from ClientModeHazelcastInstanceReconnectorTask...");
                hazelcastService.startHazelcastInstance(HazelcastOperationMode.CLIENT);
            }
        } catch (Exception ex) {
            logger.error("Error occured in ClientModeHazelcastInstanceReconnectorTask !!!", ex);
        }
    }

}
</code>```

Is this approach suitable? I also tried to listen LifeCycle events but could not make it work via events.

Regards

答:
In Hazelcast 3.9 we changed the way connection and reconnection works in clients. You can read about the new behavior in the docs: http://docs.hazelcast.org/docs/3.9.1/manual/html-single/index.html#configuring-client-connection-strategy

I hope this helps.

Body:
We are using hazelcast distributed lock and cache functions in our products. Usage of  distributed locking is vitally important for our business logic.

Currently we are using the embedded mode(each application node is also a hazelcast cluster member). We are going to switch to client - server mode.

The problem we have noticed for client - server is that, once the cluster is down for a period, after several attempts clients are destroyed and any objects (maps, sets, etc.) that were retrieved from that client are no longer usable.
Also the client instance does not recover even after the Hazelcast cluster comes back up (we receive HazelcastInstanceNotActiveException )

I know that this issue has been addressed several times and ended up as being a feature request:

issue1

issue2

issue3

My question : What should be the strategy to recover the client? Currently we are planning to enqueue a task in the client process as below. Based on a condition it will try to restart the client instance...
We will check whether the client is running or not via clientInstance.getLifecycleService().isRunning() check.

Here is the task code:

private class ClientModeHazelcastInstanceReconnectorTask implements Runnable {

    @Override
    public void run() {
        try {
            HazelCastService hazelcastService = HazelCastService.getInstance();
            HazelcastInstance clientInstance = hazelcastService.getHazelcastInstance();
            boolean running = clientInstance.getLifecycleService().isRunning();
            if (!running) {
                logger.info("Current clientInstance is NOT running. Trying to start hazelcastInstance from ClientModeHazelcastInstanceReconnectorTask...");
                hazelcastService.startHazelcastInstance(HazelcastOperationMode.CLIENT);
            }
        } catch (Exception ex) {
            logger.error("Error occured in ClientModeHazelcastInstanceReconnectorTask !!!", ex);
        }
    }

}

Is this approach suitable? I also tried to listen LifeCycle events but could not make it work via events.

Regards


问:
Rearrange a JSON
I have a JSON like this:

```<code>"hotel": [
{
    "id": 90091,
    "hotelGroup": "A1",
    "hotelRoom": [
    {
        "name":"Room1",
        "minimumQuantity": 1,
        "maximumQuantity": 6,
    },
    {
        "name":"Room2",
        "minimumQuantity": 7,
        "maximumQuantity": 12,
    }
]},
{
    "id": 90089,
    "hotelGroup": "A4",
    "hotelRoom": [
    {
        "name":"Room1",
        "minimumQuantity": 0,
        "maximumQuantity": 0,
    }]
}]
</code>```

And I try to rearrange the JSON to below format:

```<code>hotel = [{
    name: "Room1",
    RoomInfo: [{
        hotelGroup: "A1",
        Stops: [
            {"minimumQuantity": 1,"maximumQuantity": 6}
        ]},
        {
            hotelGroup: "A4",
            Stops: [
                {"minimumQuantity": 0,"maximumQuantity": 0}
            ]
        }
   ]},
   {
       name: "Room2",
       RoomInfo: [{
           Name: "A1",
           Stops: [
               {"minimumQuantity": 7,"maximumQuantity": 12}
           ]
      }]
 }]
</code>```

Is there someone who could help ?
I want to group by name of the hotel. And each of the hotels name has its own hotel group and its stop.

Thanks

答:
Obviously converted your JSON to just a regular array but you get the idea.

const hotel = [{
    "id": 90091,
    "hotelGroup": "A1",
    "hotelRoom": [{
        "name": "Room1",
        "minimumQuantity": 1,
        "maximumQuantity": 6,
      },
      {
        "name": "Room2",
        "minimumQuantity": 7,
        "maximumQuantity": 12,
      }
    ]
  },
  {
    "id": 90089,
    "hotelGroup": "A4",
    "hotelRoom": [{
      "name": "Room1",
      "minimumQuantity": 0,
      "maximumQuantity": 0,
    }]
  }
];

const newHotels = hotel.map(obj => {
  const { hotelGroup, hotelRoom } = obj;
  const newObj = {};

  newObj['name'] = hotelRoom[0]['name'];

  newObj['RoomInfo'] = hotelRoom.map(({ minimumQuantity, maximumQuantity }) => {
    return {
      hotelGroup,
      Stops: [{
        minimumQuantity,
        maximumQuantity
      }]
    };
  });

  return newObj;
});

console.log(newHotels);```

Title: Rearrange a JSON

Body:
I have a JSON like this:

"hotel": [
{
    "id": 90091,
    "hotelGroup": "A1",
    "hotelRoom": [
    {
        "name":"Room1",
        "minimumQuantity": 1,
        "maximumQuantity": 6,
    },
    {
        "name":"Room2",
        "minimumQuantity": 7,
        "maximumQuantity": 12,
    }
]},
{
    "id": 90089,
    "hotelGroup": "A4",
    "hotelRoom": [
    {
        "name":"Room1",
        "minimumQuantity": 0,
        "maximumQuantity": 0,
    }]
}]

And I try to rearrange the JSON to below format:

hotel = [{
    name: "Room1",
    RoomInfo: [{
        hotelGroup: "A1",
        Stops: [
            {"minimumQuantity": 1,"maximumQuantity": 6}
        ]},
        {
            hotelGroup: "A4",
            Stops: [
                {"minimumQuantity": 0,"maximumQuantity": 0}
            ]
        }
   ]},
   {
       name: "Room2",
       RoomInfo: [{
           Name: "A1",
           Stops: [
               {"minimumQuantity": 7,"maximumQuantity": 12}
           ]
      }]
 }]

Is there someone who could help ?
I want to group by name of the hotel. And each of the hotels name has its own hotel group and its stop.

Thanks


问:
how to resolve "The remote server returned an error: (413) Request Entity Too Large" error
Im getting the "The remote server returned an error: (413) Request Entity Too Large" error while im trying to access the save method in wcf using my MVC app, i double checked my web.config everything seemed correct, i have been trying to resolve this since two days , i tried everything that i found on google but i failed, please help me fix this.

this is system.servicemodel in web.config from MVC app (client)

```<code> <system.serviceModel>
<bindings>
  <basicHttpBinding>
    <binding name="IPersonProfileServiceEndpoint" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
      <readerQuotas maxDepth="2000000" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
      <security mode="Transport">
        <transport clientCredentialType="Windows" />
      </security>
    </binding>
    <binding name="IClientAssessmentEndpoint" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
      <readerQuotas maxDepth="2000000" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
      <security mode="None">
        <transport clientCredentialType="Basic" />
      </security>
    </binding>
    <binding name="ICMSServiceEndpoint" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
      <readerQuotas maxDepth="2000000" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
      <security mode="None">
        <transport clientCredentialType="Basic" />
      </security>
    </binding>
    <binding name="BasicHttpBinding_ICMSService" />
  </basicHttpBinding>
  <wsHttpBinding>
    <binding name="IPersonProfileServiceEndpoint" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
      <readerQuotas maxDepth="2000000" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
      <security mode="Transport">
        <transport clientCredentialType="Windows" />
      </security>
    </binding>
    <binding name="ICMSServiceEndpoint" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
      <readerQuotas maxDepth="2000000" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
      <security mode="Transport">
        <transport clientCredentialType="Windows" />
      </security>
    </binding>
    <binding name="IClientAssessmentEndpoint" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
      <readerQuotas maxDepth="2000000" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
      <security mode="Transport">
        <transport clientCredentialType="Windows" />
      </security>
    </binding>
  </wsHttpBinding>
</bindings>
<client>
  <endpoint address="https://servicetest.iltest.illinois.gov/AGE/PersonProfile/PersonProfileWCFService.svc" binding="wsHttpBinding" bindingConfiguration="IPersonProfileServiceEndpoint" contract="PersonProfileWCFService.IPersonProfileWCFService" name="IPersonProfileServiceEndpoint">
    <identity>
      <dns value="illinois.gov" />
    </identity>
  </endpoint>
  <endpoint address="http://localhost:24500/Services/ClientAssessmentService.svc" binding="basicHttpBinding" bindingConfiguration="IClientAssessmentEndpoint" contract="ClientAssessmentWCF.IClientAssessment" name="IClientAssessmentEndpoint" />
  <endpoint address="http://localhost:24500/Services/CMSService.svc" binding="basicHttpBinding" bindingConfiguration="ICMSServiceEndpoint" contract="CMSService.ICMSService" name="ICMSServiceEndpoint" />
</client>
<behaviors>
  <serviceBehaviors>
    <behavior name="debug">
      <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
  </serviceBehaviors>
</behaviors>
<protocolMapping>
  <add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<!--<services>
  <service name="TestService" behaviorConfiguration="debug" />
</services>-->
</code>```

below is my system.servicemodel in web.config from wcf Project (server)

```<code> <system.serviceModel>
<behaviors>
  <serviceBehaviors>
    <behavior name="ServiceBehavior">
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="false" />
      <serviceDebug httpHelpPageEnabled="true" includeExceptionDetailInFaults="true" />
    </behavior>
    <behavior name="">
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
  </serviceBehaviors>
</behaviors>
<protocolMapping>
  <add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

<bindings>
  <basicHttpBinding>
    <binding name="BasicHttpBindingConfig" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00">
      <readerQuotas maxDepth="2000000" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
      <security mode="Transport">
        <transport clientCredentialType="Windows" />

      </security>
    </binding>
  </basicHttpBinding>
  <!--<wsHttpBinding>
    <binding name="wsHttpBindingConfig" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00">
      <readerQuotas maxDepth="2000000" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
      <security mode="Transport">
        <transport clientCredentialType="Windows" />
      </security>
    </binding>
  </wsHttpBinding>-->
</bindings>

<services>
  <!--<service name="CMS.WCFApp.Services.CaseManagementService" behaviorConfiguration="ServiceBehavior">
    <endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicHttpBindingConfig" bindingNamespace="http://localhost:24500/Services/CaseManagementService.svc" name="ICaseManagementServiceEndpoint" contract="CMS.WCFApp.ServiceContract.ICaseManagementService">
      --><!--<identity>
        <dns value="illinois.gov"/>
      </identity>-->
    <!--
    </endpoint>
  </service>

  <service name="CMS.WCFApp.Services.ClientAssessmentService" behaviorConfiguration="ServiceBehavior">
    <endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicHttpBindingConfig" bindingNamespace="http://localhost:24500/Services/ClientAssessmentService.svc" name="IClientAssessmentEndpoint" contract="CMS.WCFApp.ServiceContract.IClientAssessment">
      -->
    <!--<identity>
        <dns value="illinois.gov"/>
      </identity>--><!--
    </endpoint>
  </service>-->

  <service name="CMS.WCFApp.Services.CMSService.svc" behaviorConfiguration="ServiceBehavior">
    <endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicHttpBindingConfig" bindingNamespace="http://localhost:24500/Services/CMSService.svc" name="ICMSServiceEndpoint" contract="CMS.WCFApp.ServiceContract.ICMSService">
      <!--<identity>
        <dns value="illinois.gov"/>
      </identity>-->
    </endpoint>
  </service>

  <!--<service name="CMS.WCFApp.Services.CManagementService" behaviorConfiguration="ServiceBehavior">
    <endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicHttpBindingConfig" bindingNamespace="http://localhost:24500/Services/CManagementService.svc" name="ICManagementServiceEndpoint" contract="CMS.WCFApp.ServiceContract.ICManagementService">

  --><!--<identity>
    <dns value="illinois.gov"/>
  </identity>--><!--

    </endpoint>
  </service>-->
</services>
</code>```

答: its a common mistake. i guess its your server side web config. try add the same config to your client and your problem will solve.</p>

Body:
Im getting the "The remote server returned an error: (413) Request Entity Too Large" error while im trying to access the save method in wcf using my MVC app, i double checked my web.config everything seemed correct, i have been trying to resolve this since two days , i tried everything that i found on google but i failed, please help me fix this.

this is system.servicemodel in web.config from MVC app (client)

 <system.serviceModel>
<bindings>
  <basicHttpBinding>
    <binding name="IPersonProfileServiceEndpoint" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
      <readerQuotas maxDepth="2000000" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
      <security mode="Transport">
        <transport clientCredentialType="Windows" />
      </security>
    </binding>
    <binding name="IClientAssessmentEndpoint" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
      <readerQuotas maxDepth="2000000" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
      <security mode="None">
        <transport clientCredentialType="Basic" />
      </security>
    </binding>
    <binding name="ICMSServiceEndpoint" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
      <readerQuotas maxDepth="2000000" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
      <security mode="None">
        <transport clientCredentialType="Basic" />
      </security>
    </binding>
    <binding name="BasicHttpBinding_ICMSService" />
  </basicHttpBinding>
  <wsHttpBinding>
    <binding name="IPersonProfileServiceEndpoint" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
      <readerQuotas maxDepth="2000000" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
      <security mode="Transport">
        <transport clientCredentialType="Windows" />
      </security>
    </binding>
    <binding name="ICMSServiceEndpoint" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
      <readerQuotas maxDepth="2000000" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
      <security mode="Transport">
        <transport clientCredentialType="Windows" />
      </security>
    </binding>
    <binding name="IClientAssessmentEndpoint" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
      <readerQuotas maxDepth="2000000" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
      <security mode="Transport">
        <transport clientCredentialType="Windows" />
      </security>
    </binding>
  </wsHttpBinding>
</bindings>
<client>
  <endpoint address="https://servicetest.iltest.illinois.gov/AGE/PersonProfile/PersonProfileWCFService.svc" binding="wsHttpBinding" bindingConfiguration="IPersonProfileServiceEndpoint" contract="PersonProfileWCFService.IPersonProfileWCFService" name="IPersonProfileServiceEndpoint">
    <identity>
      <dns value="illinois.gov" />
    </identity>
  </endpoint>
  <endpoint address="http://localhost:24500/Services/ClientAssessmentService.svc" binding="basicHttpBinding" bindingConfiguration="IClientAssessmentEndpoint" contract="ClientAssessmentWCF.IClientAssessment" name="IClientAssessmentEndpoint" />
  <endpoint address="http://localhost:24500/Services/CMSService.svc" binding="basicHttpBinding" bindingConfiguration="ICMSServiceEndpoint" contract="CMSService.ICMSService" name="ICMSServiceEndpoint" />
</client>
<behaviors>
  <serviceBehaviors>
    <behavior name="debug">
      <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
  </serviceBehaviors>
</behaviors>
<protocolMapping>
  <add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>

below is my system.servicemodel in web.config from wcf Project (server)

 <system.serviceModel>
<behaviors>
  <serviceBehaviors>
    <behavior name="ServiceBehavior">
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="false" />
      <serviceDebug httpHelpPageEnabled="true" includeExceptionDetailInFaults="true" />
    </behavior>
    <behavior name="">
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
  </serviceBehaviors>
</behaviors>
<protocolMapping>
  <add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

<bindings>
  <basicHttpBinding>
    <binding name="BasicHttpBindingConfig" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00">
      <readerQuotas maxDepth="2000000" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
      <security mode="Transport">
        <transport clientCredentialType="Windows" />

      </security>
    </binding>
  </basicHttpBinding>

</bindings>

<services>

  <service name="CMS.WCFApp.Services.CMSService.svc" behaviorConfiguration="ServiceBehavior">
    <endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicHttpBindingConfig" bindingNamespace="http://localhost:24500/Services/CMSService.svc" name="ICMSServiceEndpoint" contract="CMS.WCFApp.ServiceContract.ICMSService">

    </endpoint>
  </service>

</services>


问:
Get menu outside his calls
I want to change my menu dynamically, so I tried this but my app crash :

To get my menu in all my activity :

```<code>private Menu menu;
</code>```

Then in onCreateOptionsMenu before return statement:

```<code>this.menu = menu;
</code>```

And then in a function :

```<code>MenuItem parent = menu.findItem(R.id.parent_menu);
parent.setTitle("test");
</code>```

Crashing... I founded the same answer I did : Android - How to dynamically change menu item text outside of onOptionsItemsSelected or onCreateOptionsMenu but for me, not working.

Thanks in advance

PS : If MenuItem parent and setTitle are in commentary, it's works fine.

So the problem is onCreateOptionsMenu is called only when I want to view the menu for the first time... How can I call it before ?

```<code>04-20 17:00:19.170: D/dalvikvm(26887): GC_EXTERNAL_ALLOC freed 45K, 50% free 2729K/5379K, external 0K/0K, paused 27ms
04-20 17:00:19.230: D/dalvikvm(26887): GC_EXTERNAL_ALLOC freed 11K, 49% free 2747K/5379K, external 565K/576K, paused 33ms
04-20 17:00:19.300: D/dalvikvm(26887): GC_EXTERNAL_ALLOC freed 62K, 49% free 2787K/5379K, external 824K/1091K, paused 22ms
04-20 17:00:19.825: D/dalvikvm(26887): GC_CONCURRENT freed 314K, 50% free 2859K/5639K, external 1521K/1630K, paused 2ms+3ms
04-20 17:00:19.845: I/webclipboard(26887): clipservice: android.sec.clipboard.ClipboardExManager@40514930
04-20 17:00:20.145: D/WML_SISO(26887): InitPasteboardJni
04-20 17:00:20.185: D/dalvikvm(26887): GC_CONCURRENT freed 323K, 48% free 3062K/5831K, external 1591K/1630K, paused 3ms+2ms
04-20 17:00:20.210: D/CLIPBOARD(26887): Hide Clipboard dialog at Starting input: finished by someone else... !
04-20 17:00:20.340: D/dalvikvm(26887): GC_CONCURRENT freed 179K, 44% free 3423K/6087K, external 1425K/1630K, paused 1ms+2ms
04-20 17:00:21.935: D/AndroidRuntime(26887): Shutting down VM
04-20 17:00:21.935: W/dalvikvm(26887): threadid=1: thread exiting with uncaught exception (group=0x4001e578)
04-20 17:00:21.940: E/AndroidRuntime(26887): FATAL EXCEPTION: main
04-20 17:00:21.940: E/AndroidRuntime(26887): java.lang.NullPointerException
04-20 17:00:21.940: E/AndroidRuntime(26887):    at p.NewsRecovery.AddWebsiteActivity$1.onClick(AddWebsiteActivity.java:133)
04-20 17:00:21.940: E/AndroidRuntime(26887):    at android.view.View.performClick(View.java:2538)
04-20 17:00:21.940: E/AndroidRuntime(26887):    at android.view.View$PerformClick.run(View.java:9152)
04-20 17:00:21.940: E/AndroidRuntime(26887):    at android.os.Handler.handleCallback(Handler.java:587)
04-20 17:00:21.940: E/AndroidRuntime(26887):    at android.os.Handler.dispatchMessage(Handler.java:92)
04-20 17:00:21.940: E/AndroidRuntime(26887):    at android.os.Looper.loop(Looper.java:130)
04-20 17:00:21.940: E/AndroidRuntime(26887):    at android.app.ActivityThread.main(ActivityThread.java:3691)
04-20 17:00:21.940: E/AndroidRuntime(26887):    at java.lang.reflect.Method.invokeNative(Native Method)
04-20 17:00:21.940: E/AndroidRuntime(26887):    at java.lang.reflect.Method.invoke(Method.java:507)
04-20 17:00:21.940: E/AndroidRuntime(26887):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
04-20 17:00:21.940: E/AndroidRuntime(26887):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665)
04-20 17:00:21.940: E/AndroidRuntime(26887):    at dalvik.system.NativeStart.main(Native Method)
04-20 17:00:22.015: D/dalvikvm(26887): GC_EXTERNAL_ALLOC freed 586K, 50% free 3142K/6215K, external 1511K/1630K, paused 38ms
04-20 17:00:22.065: D/szipinf(26887): Initializing inflate state
04-20 17:00:22.065: D/szipinf(26887): Initializing zlib to inflate
04-20 17:00:22.170: D/dalvikvm(26887): GC_FOR_MALLOC freed 222K, 50% free 3282K/6535K, external 1933K/2370K, paused 17ms
04-20 17:00:22.170: I/dalvikvm-heap(26887): Grow heap (frag case) to 7.591MB for 129176-byte allocation
04-20 17:00:22.190: D/dalvikvm(26887): GC_FOR_MALLOC freed 18K, 50% free 3390K/6663K, external 1586K/2098K, paused 12ms
04-20 17:00:22.210: D/dalvikvm(26887): GC_FOR_MALLOC freed 134K, 51% free 3319K/6663K, external 1586K/2098K, paused 11ms
04-20 17:00:22.210: I/dalvikvm-heap(26887): Grow heap (frag case) to 7.412MB for 258336-byte allocation
04-20 17:00:22.230: D/dalvikvm(26887): GC_FOR_MALLOC freed 8K, 49% free 3563K/6919K, external 1586K/2098K, paused 11ms
04-20 17:00:22.255: D/dalvikvm(26887): GC_FOR_MALLOC freed 0K, 49% free 3563K/6919K, external 1586K/2098K, paused 12ms
04-20 17:00:22.255: I/dalvikvm-heap(26887): Grow heap (frag case) to 7.527MB for 129176-byte allocation
04-20 17:00:22.270: D/dalvikvm(26887): GC_FOR_MALLOC freed 253K, 52% free 3435K/7047K, external 1556K/2068K, paused 14ms
</code>```

答:
You must inflate the menu before setting it to your variable;

```<code>@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_visit_profile, menu);
    mOptionsMenu = menu;
    return super.onCreateOptionsMenu(menu);
}
</code>```

And then you can use it.

```<code>MenuItem item = mOptionsMenu.findItem(R.id.visit_profile_hi);
item.setTitle("Remover hi");
</code>```

Title: Get menu outside his calls

Body:
I want to change my menu dynamically, so I tried this but my app crash :

To get my menu in all my activity :

private Menu menu;

Then in onCreateOptionsMenu before return statement:

this.menu = menu;

And then in a function :

MenuItem parent = menu.findItem(R.id.parent_menu);
parent.setTitle("test");

Crashing... I founded the same answer I did : Android - How to dynamically change menu item text outside of onOptionsItemsSelected or onCreateOptionsMenu but for me, not working.

Thanks in advance

PS : If MenuItem parent and setTitle are in commentary, it's works fine.

So the problem is onCreateOptionsMenu is called only when I want to view the menu for the first time... How can I call it before ?

04-20 17:00:19.170: D/dalvikvm(26887): GC_EXTERNAL_ALLOC freed 45K, 50% free 2729K/5379K, external 0K/0K, paused 27ms
04-20 17:00:19.230: D/dalvikvm(26887): GC_EXTERNAL_ALLOC freed 11K, 49% free 2747K/5379K, external 565K/576K, paused 33ms
04-20 17:00:19.300: D/dalvikvm(26887): GC_EXTERNAL_ALLOC freed 62K, 49% free 2787K/5379K, external 824K/1091K, paused 22ms
04-20 17:00:19.825: D/dalvikvm(26887): GC_CONCURRENT freed 314K, 50% free 2859K/5639K, external 1521K/1630K, paused 2ms+3ms
04-20 17:00:19.845: I/webclipboard(26887): clipservice: android.sec.clipboard.ClipboardExManager@40514930
04-20 17:00:20.145: D/WML_SISO(26887): InitPasteboardJni
04-20 17:00:20.185: D/dalvikvm(26887): GC_CONCURRENT freed 323K, 48% free 3062K/5831K, external 1591K/1630K, paused 3ms+2ms
04-20 17:00:20.210: D/CLIPBOARD(26887): Hide Clipboard dialog at Starting input: finished by someone else... !
04-20 17:00:20.340: D/dalvikvm(26887): GC_CONCURRENT freed 179K, 44% free 3423K/6087K, external 1425K/1630K, paused 1ms+2ms
04-20 17:00:21.935: D/AndroidRuntime(26887): Shutting down VM
04-20 17:00:21.935: W/dalvikvm(26887): threadid=1: thread exiting with uncaught exception (group=0x4001e578)
04-20 17:00:21.940: E/AndroidRuntime(26887): FATAL EXCEPTION: main
04-20 17:00:21.940: E/AndroidRuntime(26887): java.lang.NullPointerException
04-20 17:00:21.940: E/AndroidRuntime(26887):    at p.NewsRecovery.AddWebsiteActivity$1.onClick(AddWebsiteActivity.java:133)
04-20 17:00:21.940: E/AndroidRuntime(26887):    at android.view.View.performClick(View.java:2538)
04-20 17:00:21.940: E/AndroidRuntime(26887):    at android.view.View$PerformClick.run(View.java:9152)
04-20 17:00:21.940: E/AndroidRuntime(26887):    at android.os.Handler.handleCallback(Handler.java:587)
04-20 17:00:21.940: E/AndroidRuntime(26887):    at android.os.Handler.dispatchMessage(Handler.java:92)
04-20 17:00:21.940: E/AndroidRuntime(26887):    at android.os.Looper.loop(Looper.java:130)
04-20 17:00:21.940: E/AndroidRuntime(26887):    at android.app.ActivityThread.main(ActivityThread.java:3691)
04-20 17:00:21.940: E/AndroidRuntime(26887):    at java.lang.reflect.Method.invokeNative(Native Method)
04-20 17:00:21.940: E/AndroidRuntime(26887):    at java.lang.reflect.Method.invoke(Method.java:507)
04-20 17:00:21.940: E/AndroidRuntime(26887):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
04-20 17:00:21.940: E/AndroidRuntime(26887):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665)
04-20 17:00:21.940: E/AndroidRuntime(26887):    at dalvik.system.NativeStart.main(Native Method)
04-20 17:00:22.015: D/dalvikvm(26887): GC_EXTERNAL_ALLOC freed 586K, 50% free 3142K/6215K, external 1511K/1630K, paused 38ms
04-20 17:00:22.065: D/szipinf(26887): Initializing inflate state
04-20 17:00:22.065: D/szipinf(26887): Initializing zlib to inflate
04-20 17:00:22.170: D/dalvikvm(26887): GC_FOR_MALLOC freed 222K, 50% free 3282K/6535K, external 1933K/2370K, paused 17ms
04-20 17:00:22.170: I/dalvikvm-heap(26887): Grow heap (frag case) to 7.591MB for 129176-byte allocation
04-20 17:00:22.190: D/dalvikvm(26887): GC_FOR_MALLOC freed 18K, 50% free 3390K/6663K, external 1586K/2098K, paused 12ms
04-20 17:00:22.210: D/dalvikvm(26887): GC_FOR_MALLOC freed 134K, 51% free 3319K/6663K, external 1586K/2098K, paused 11ms
04-20 17:00:22.210: I/dalvikvm-heap(26887): Grow heap (frag case) to 7.412MB for 258336-byte allocation
04-20 17:00:22.230: D/dalvikvm(26887): GC_FOR_MALLOC freed 8K, 49% free 3563K/6919K, external 1586K/2098K, paused 11ms
04-20 17:00:22.255: D/dalvikvm(26887): GC_FOR_MALLOC freed 0K, 49% free 3563K/6919K, external 1586K/2098K, paused 12ms
04-20 17:00:22.255: I/dalvikvm-heap(26887): Grow heap (frag case) to 7.527MB for 129176-byte allocation
04-20 17:00:22.270: D/dalvikvm(26887): GC_FOR_MALLOC freed 253K, 52% free 3435K/7047K, external 1556K/2068K, paused 14ms

Body:
You must inflate the menu before setting it to your variable;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_visit_profile, menu);
    mOptionsMenu = menu;
    return super.onCreateOptionsMenu(menu);
}

And then you can use it.

MenuItem item = mOptionsMenu.findItem(R.id.visit_profile_hi);
item.setTitle("Remover hi");


问:
Implementing HTTP client with Sockets (without http libraries) with Python
For educational purposes, and without any importance, I wanted to implement a script that could make simple HTTP requests and show the content of the answer at the console (in plain text). I have achieved it with this code:

```<code>import socket
import sys

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server_address = ('localhost', 8080)
print >>sys.stderr, 'connecting to %s port %s' % server_address
sock.connect(server_address)

message = 'GET /php.php HTTP/1.1\r\n'
message += 'Host: localhost:8080\r\n\r\n'
print >>sys.stderr, 'sending "%s"' % message
sock.sendall(message)

data = sock.recv(10000000)
print >>sys.stderr, 'received "%s"' % data

sock.close()
</code>```

I just build the HTTP request, send it to the server, and wait for an answer.

Now comes the question: I do not know how to read the whole answer, I know there is a header that is "content-lengt" (let's assume it will always be there). How can I read all the content of the answer without having to do sock.recv (1000000000000000000)?

答:
Typically you would read a certain ammount of bytes (eg 1024) in a loop. If recv returns any bytes append it to your data, else break the loop and close the connection.

```<code>import socket

server_address = ('httpbin.org', 80)
message  = b'GET / HTTP/1.1\r\n'
message += b'Host: httpbin.org:80\r\n'
message += b'Connection: close\r\n'
message += b'\r\n'

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(server_address)
sock.sendall(message)

data = b''
while True:
    buf = sock.recv(1024)
    if not buf:
        break
    data += buf

sock.close()
print(data.decode())
</code>```

Note that you'll have to set the Connection header to 'close' (or use HTTP 1.0). Otherwise the loop will hang due to persistent connections by default, as implemented in HTTP 1.1.

Alternatinely you could read the first bytes and parse them to get the HTTP headers. If there is a Content-Length header you can use it to calculate the ramaining bytes.

```<code>...
data = b''
while b'\r\n\r\n' not in data:
    data += sock.recv(1)

header = data[:-4].decode()
headers = dict([i.split(': ') for i in header.splitlines()[1:]])
content_length = int(headers.get('Content-Length', 0))

if content_length:
    data += sock.recv(content_length)
...
</code>```

By using bytes in send and recv, this should work for Python3 as well.  However this is a very basic example and will fail in many cases (HTTPS, cookies, redirects, etc), so it's best to use a library designed for HTTP requests.

Body:
For educational purposes, and without any importance, I wanted to implement a script that could make simple HTTP requests and show the content of the answer at the console (in plain text). I have achieved it with this code:

import socket
import sys

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server_address = ('localhost', 8080)
print >>sys.stderr, 'connecting to %s port %s' % server_address
sock.connect(server_address)

message = 'GET /php.php HTTP/1.1\r\n'
message += 'Host: localhost:8080\r\n\r\n'
print >>sys.stderr, 'sending "%s"' % message
sock.sendall(message)

data = sock.recv(10000000)
print >>sys.stderr, 'received "%s"' % data

sock.close()

I just build the HTTP request, send it to the server, and wait for an answer.

Now comes the question: I do not know how to read the whole answer, I know there is a header that is "content-lengt" (let's assume it will always be there). How can I read all the content of the answer without having to do sock.recv (1000000000000000000)?

Body:
Typically you would read a certain ammount of bytes (eg 1024) in a loop. If recv returns any bytes append it to your data, else break the loop and close the connection.

import socket

server_address = ('httpbin.org', 80)
message  = b'GET / HTTP/1.1\r\n'
message += b'Host: httpbin.org:80\r\n'
message += b'Connection: close\r\n'
message += b'\r\n'

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(server_address)
sock.sendall(message)

data = b''
while True:
    buf = sock.recv(1024)
    if not buf:
        break
    data += buf

sock.close()
print(data.decode())

Note that you'll have to set the Connection header to 'close' (or use HTTP 1.0). Otherwise the loop will hang due to persistent connections by default, as implemented in HTTP 1.1.

Alternatinely you could read the first bytes and parse them to get the HTTP headers. If there is a Content-Length header you can use it to calculate the ramaining bytes.

...
data = b''
while b'\r\n\r\n' not in data:
    data += sock.recv(1)

header = data[:-4].decode()
headers = dict([i.split(': ') for i in header.splitlines()[1:]])
content_length = int(headers.get('Content-Length', 0))

if content_length:
    data += sock.recv(content_length)
...

By using bytes in send and recv, this should work for Python3 as well.  However this is a very basic example and will fail in many cases (HTTPS, cookies, redirects, etc), so it's best to use a library designed for HTTP requests.


问:
gsutil copy with multithread doesn't finish copying all files
We have around 650 GB of data on google compute engine.

We need to move them to Cloud Storage to a Coldline bucket, so the best options we could find is to copy them with gsutil with parallel mode.

The files are from kilobytes to 10Mb max, and there are few million files.

The command we used is

gsutil -m cp -r userFiles/ gs://removed-websites/

On first run it copied around 200Gb and stopped with error

| [972.2k/972.2k files][207.9 GiB/207.9 GiB] 100% Done  29.4 MiB/s ETA 00:00:00
Operation completed over 972.2k objects/207.9 GiB.

CommandException: 1 file/object could not be transferred.

On second run it finished almost at the same place, and stopped again.

How can we copy these files successfully ?

Also the buckets that have the partial data are not being removed after deleting them. Console just says preparing to delete, and nothing happens, we waited more than 4 hours, any way to remove those buckets ?

答:
Answering your first question, I can propose the several options. All of them based on data split and uploading by small portions of data.

You can try distributed upload from several machines.
https://cloud.google.com/storage/docs/gsutil/commands/cp#copying-tofrom-subdirectories-distributing-transfers-across-machines

In this case you are splitting data by safe chunks, like 50GB, and uploading it from several machines in parallel. But it requires machines, that is not required actually.

You still can try such splited upload on a single machine, but you need then some splitting mechanism, which will not upload all files at once, but by chunks. In this case, if some thing fails, you will need to reload only this chunk. In addition, you will have better accuracy and you'll be able to localize possible fail place if something happens.

Regarding, how you can delete them. Well, same technique as for upload. Divide data on chunks and delete them by chunks. Or, you can try to remove whole project, if it suitable for your situation.

Update 1

So, I checked gsutil interface and it is supports glob syntax. You can match with glob syntax, for example 200 folders, and launch this command 150 time (this will upload 200 x 500 = 30 000 folders).

You can use such approach and combine it with -m option, so this is partially that your script did, but might work faster. This will work for folders names and files as well.
If you provide examples of the folders names and files names it would be easier to propose appropriate glob pattern.


问:
Getting value from listview control
Need help selecting the value from custID column in the ListView so that I can retrieve the value from the database and display it in the TextBoxes.The SelectedIndex not working in c#

Thanks

http://img713.imageshack.us/img713/133/listview.jpg

My Code

```<code>private void yourListView_SelectedIndexChanged(object sender, EventArgs e)
{
    if (yourListView.SelectedIndex == -1)
        return;
    //get selected row
    ListViewItem item = yourListView.Items[yourListView.SelectedIndex];
    //fill the text boxes
    textBoxID.Text = item.Text;
    textBoxName.Text = item.SubItems[0].Text;
    textBoxPhone.Text = item.SubItems[1].Text;
    textBoxLevel.Text = item.SubItems[2].Text;
}
</code>```

答:
C# and WPF use this:</p>

```<code>private void lv_yourListView_SelectedIndexChanged(object sender, EventArgs
e)
{
    if (yourListView.SelectedItems.Count == 0)
        return;

     var item = lvb_listInvoices.SelectedItems[0];
     var myColumnData = item.someField; //use whatever you want
}
</code>```

Title: Getting value from listview control

Body:
Need help selecting the value from custID column in the ListView so that I can retrieve the value from the database and display it in the TextBoxes.The SelectedIndex not working in c#

Thanks

http://img713.imageshack.us/img713/133/listview.jpg

My Code

private void yourListView_SelectedIndexChanged(object sender, EventArgs e)
{
    if (yourListView.SelectedIndex == -1)
        return;
    //get selected row
    ListViewItem item = yourListView.Items[yourListView.SelectedIndex];
    //fill the text boxes
    textBoxID.Text = item.Text;
    textBoxName.Text = item.SubItems[0].Text;
    textBoxPhone.Text = item.SubItems[1].Text;
    textBoxLevel.Text = item.SubItems[2].Text;
}

Body:
C# and WPF use this:

private void lv_yourListView_SelectedIndexChanged(object sender, EventArgs
e)
{
    if (yourListView.SelectedItems.Count == 0)
        return;

     var item = lvb_listInvoices.SelectedItems[0];
     var myColumnData = item.someField; //use whatever you want
}


问:
Apache2 conf redirect
Looking for what is the best practice for this.

I have 2 domains, oldsite.com and mynewsite.com

Added these to my oldsite.com apache2 config file:

```<code>#homepage
Redirect 301 / https://www.mynewsite.org

#rest of pages
Redirect 301 /old/page/location1 https://www.mynewsite.org/some/new/page1
Redirect 301 /old/page/location2 https://www.mynewsite.org/another/new/page/here
</code>```

I have tons of redirects to do though (100+). Like to keep it as neat as possible. Looking for the best practice for this. Say mynewsite.com changes some day. I'd like to be able to update just one location in the conf file.

答:
Looks like you have control over Apache config on old domain.

It is better to use RewriteMap for your requirements for thousands of redirection. Here is how you can use it:

Add following line to your httpd.conf file to define a RewriteMap:

```<code>RewriteMap redirMap txt://full/path/to/redirects.txt
</code>```

Create a text file as /full/path/to/redirects.txt like this:

```<code>/old/page/location1 /new/pag1
/old/page/location2 /new/pag2
/ /
</code>```

Add these line in your apache config or vhost config or site root .htaccess:

```<code>Options +FollowSymLinks
RewriteEngine on

RewriteCond ${redirMap:$0} .
RewriteRule .* https://www.mynewsite.org${redirMap:$0} [L,R=301,NE]
</code>```

This is pretty handy for mynewsite.com changes some day requirement as you will need to change domain name in one rule only.

Title: Apache2 conf redirect

Body:
Looking for what is the best practice for this.

I have 2 domains, oldsite.com and mynewsite.com

Added these to my oldsite.com apache2 config file:

#homepage
Redirect 301 / https://www.mynewsite.org

#rest of pages
Redirect 301 /old/page/location1 https://www.mynewsite.org/some/new/page1
Redirect 301 /old/page/location2 https://www.mynewsite.org/another/new/page/here

I have tons of redirects to do though (100+). Like to keep it as neat as possible. Looking for the best practice for this. Say mynewsite.com changes some day. I'd like to be able to update just one location in the conf file.

Body:
Looks like you have control over Apache config on old domain.

It is better to use RewriteMap for your requirements for thousands of redirection. Here is how you can use it:

Add following line to your httpd.conf file to define a RewriteMap:

RewriteMap redirMap txt://full/path/to/redirects.txt

Create a text file as /full/path/to/redirects.txt like this:

/old/page/location1 /new/pag1
/old/page/location2 /new/pag2
/ /

Add these line in your apache config or vhost config or site root .htaccess:

Options +FollowSymLinks
RewriteEngine on

RewriteCond ${redirMap:$0} .
RewriteRule .* https://www.mynewsite.org${redirMap:$0} [L,R=301,NE]

This is pretty handy for mynewsite.com changes some day requirement as you will need to change domain name in one rule only.


问:
Accessing a File in UWP
everyone.
I want to access a .wav file from my Assets folder in a UWP app,
as follow:

```<code>StorageFile file = await Package.Current.InstalledLocation.GetFileAsync(@"ms-appx:///Assets/"+"sound.wav");
</code>```

but I get the following error:

```<code>UWP accessing file System.UnauthorizedAccessException: Access is denied.
</code>```

I though I did everything right as described in MSDN, but I get the error still.

答:
Use either

```<code>StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/"+"sound.wav"));
</code>```

or

```<code>StorageFile file = await Package.Current.InstalledLocation.GetFileAsync(@"Assets\"+"sound.wav");
</code>```

Title: Accessing a File in UWP

Body:
everyone.
I want to access a .wav file from my Assets folder in a UWP app,
as follow:

StorageFile file = await Package.Current.InstalledLocation.GetFileAsync(@"ms-appx:///Assets/"+"sound.wav");

but I get the following error:

UWP accessing file System.UnauthorizedAccessException: Access is denied.

I though I did everything right as described in MSDN, but I get the error still.

Body:
Use either

StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/"+"sound.wav"));

or

StorageFile file = await Package.Current.InstalledLocation.GetFileAsync(@"Assets\"+"sound.wav");


问:
Android Studio: Failed to load JVM DLL
I have thoroughly researched this problem and the posted solutions have not worked for me.

I'm running Windows 8, and the most recent JAVA JDK (64 bit) and Android Studio versions.

[System specs: new XPS 13, core i5, 8GB RAM, SSD]

The exact error is:

Failed to load JVM DLL C:\Program Files\Java\jdk1.8.0_45\jre\bin\client\jvm.dll

If you already have a 64-bit JDK installed, define a JAVA_HOME variable in ... Environment Variables

-- Verification --

java -version

java version "1.8.0_45"

Java(TM) SE Runtime Environment (build 1.8.0_45-b15)..

-- Things I've tried --

Uninstall java and AS, reboot, install 64 bit java jdk, verify installation, reboot, install AS, set JAVA_HOME variable

YES, the viable is an Environment variable and not a User variable

I have added the /bin/ directory to the "path" environment variable

I have reversed the slashes in the environment variable paths as per one solution stated

Followed the uninstall/reinstall process stated above, but with a 32bit jdk instead (with the correct environment variable paths)

Done the whole process over (uninstalling, rebooting after installs, etc.) but with older JDKs

I have tried running studio.exe with 32 bit JDK installed, and studio64.exe with the 64 bit JDK installed

I feel like I've tried everything. I HAD to have screwed up somewhere along the line. Any idea?

答: Try running android studio as Administrator. That worked for me. Try installing a different version of Android Studio.</p>

Title: Android Studio: Failed to load JVM DLL


问:
Django Caching on front-end
I was working with 2 applications that are within a DJango project: "customer" and "vendors". Each application has a HTML file named "testindex.html".

Whenever I typed:

http://myhost/customer/basic_info

the correct page would show up

If I typed:

http://myhost/vendors/basic_info

the page from http://myhost/customer/basic_info would show up

I found out that it was due to caching (since both applications use "testindex.html"). So again, "testindex.html" is caching.

How can one get around this problem?

TIA

Details are listed below. I have the following views defined:

urls.py for the project

```<code>urlpatterns = [

... snip ...

url(r'^customer/', include('libmstr.customer.urls')),
url(r'^vendors/', include('libmstr.vendors.urls')),
]
</code>```

views.py for customer

```<code>from django.shortcuts import render

def basic_info(request):
    return render(request, 'testindex.html', {})
</code>```

views.py for vendors

```<code>from django.shortcuts import render

def basic_info(request):
    return render(request, 'testindex.html', {})
</code>```

urls.py for customers

```<code>from django.conf.urls import url
from . import views

# list of templates
app_name = 'customer'

urlpatterns = [
url(r'^basic_info/$', views.basic_info, name='basic_info'),
]
</code>```

urls.py for vendors

```<code>from django.conf.urls import url
from . import views

# list of templates
app_name = 'vendors'

urlpatterns = [
url(r'^basic_info/$', views.basic_info, name='basic_info'),
]
</code>```

答:
It sounds like you have two templates, customers/templates/testindex.html and vendors/templates/testindex.html.

When you call render(request, 'testindex.html', {}), the app directories template loader searches the templates directory for each app in INSTALLED_APPS, and stops the first time it finds a match. If customers is above vendors in INSTALLED_APPS, then it will always use the customers template.

For this reason, Django recommends that you name your templates customers/templates/customers/testindex.html and vendors/templates/vendors/testindex.html, and change your views to use customers/testindex.html and vendors/testindex.html. This way you avoid clashes.

Title: Django Caching on front-end

Body:
I was working with 2 applications that are within a DJango project: "customer" and "vendors". Each application has a HTML file named "testindex.html".

Whenever I typed:

http://myhost/customer/basic_info

the correct page would show up

If I typed:

http://myhost/vendors/basic_info

the page from http://myhost/customer/basic_info would show up

I found out that it was due to caching (since both applications use "testindex.html"). So again, "testindex.html" is caching.

How can one get around this problem?

TIA

Details are listed below. I have the following views defined:

urls.py for the project

urlpatterns = [

... snip ...

url(r'^customer/', include('libmstr.customer.urls')),
url(r'^vendors/', include('libmstr.vendors.urls')),
]

views.py for customer

from django.shortcuts import render

def basic_info(request):
    return render(request, 'testindex.html', {})

views.py for vendors

from django.shortcuts import render

def basic_info(request):
    return render(request, 'testindex.html', {})

urls.py for customers

from django.conf.urls import url
from . import views

# list of templates
app_name = 'customer'

urlpatterns = [
url(r'^basic_info/$', views.basic_info, name='basic_info'),
]

urls.py for vendors

from django.conf.urls import url
from . import views

# list of templates
app_name = 'vendors'

urlpatterns = [
url(r'^basic_info/$', views.basic_info, name='basic_info'),
]


问:
Loop cells in VBA.
I am trying to make my code better, as every beginner I have problem to make it more "systematic", I would like your advice on how to do it.

I open few workbook, so now my macro looks like this.

```<code> Sub OpenWorkbooks()
 workbooks.Open Filename :="C/.../file1.xlsx"
 workbooks.Open Filename :="C/.../file2.xlsx"
 workbooks.Open Filename :="C/.../file3.xlsx"
 .
 .
 End sub
</code>```

Its quite ugly, I would like to have each path in a cell. Let say from A1 to A3 and to loop this cell to open the workbooks. Any idea how I could do this?

In an other part of my code, nicely found on the web, I have the same problem. I would like to be able to enter my paths somewhere in my spreadsheet and then to loop it from there instead of entering manually one by one...

This is the second part of the code, quite clueless how I should do this...

```<code>Sub GetNumber()
Dim wWbPath As String, WbName As String
Dim WsName As String, CellRef As String
Dim Ret As String

Workbooks("file1").Close SaveChanges:=True

wbPath = "C:/etc...."

WbName = "file1.xlsx"
WsName = "Sheet1"
CellRef = "AD30"

arg = "'" & wbPath & "[" & wbName & "]" & _
wsName & "'!" & Range(cellRef).Address(True, True, xlR1C1)

Worksheets("Sheet1").Range("A1") = ExecuteExcel4Macro(arg)

'Then I need to do all again for the second workbook etc....

End sub
</code>```

Any idea is welcome,
Thank you!

答:
I had to figure out how do something similar recently. Try this ...</p>

```<code> Dim i As Long
 Dim SelectedFiles As Variant

SelectedFiles = Application.GetOpenFilename("Excel Files (*.xlsx), *.xlsx", _
Title:="Select files", MultiSelect:=True)

 If IsArray(SelectedFiles) Then

    For i = LBound(SelectedFiles) To UBound(SelectedFiles)
        Set wbkToOpen = Workbooks.Open(Filename:=SelectedFiles(i), corruptload:=xlRepairFile)

        Debug.Print wbkToOpen.Name
        Debug.Print SelectedFiles(i)

        wbkToOpen.Close savechanges:=False

    Next

End If
</code>```

Title: Loop cells in VBA.

Body:
I am trying to make my code better, as every beginner I have problem to make it more "systematic", I would like your advice on how to do it.

I open few workbook, so now my macro looks like this.

 Sub OpenWorkbooks()
 workbooks.Open Filename :="C/.../file1.xlsx"
 workbooks.Open Filename :="C/.../file2.xlsx"
 workbooks.Open Filename :="C/.../file3.xlsx"
 .
 .
 End sub

Its quite ugly, I would like to have each path in a cell. Let say from A1 to A3 and to loop this cell to open the workbooks. Any idea how I could do this?

In an other part of my code, nicely found on the web, I have the same problem. I would like to be able to enter my paths somewhere in my spreadsheet and then to loop it from there instead of entering manually one by one...

This is the second part of the code, quite clueless how I should do this...

Sub GetNumber()
Dim wWbPath As String, WbName As String
Dim WsName As String, CellRef As String
Dim Ret As String

Workbooks("file1").Close SaveChanges:=True

wbPath = "C:/etc...."

WbName = "file1.xlsx"
WsName = "Sheet1"
CellRef = "AD30"

arg = "'" & wbPath & "[" & wbName & "]" & _
wsName & "'!" & Range(cellRef).Address(True, True, xlR1C1)

Worksheets("Sheet1").Range("A1") = ExecuteExcel4Macro(arg)

'Then I need to do all again for the second workbook etc....

End sub

Any idea is welcome,
Thank you!

Body:
I had to figure out how do something similar recently. Try this ...

 Dim i As Long
 Dim SelectedFiles As Variant

SelectedFiles = Application.GetOpenFilename("Excel Files (*.xlsx), *.xlsx", _
Title:="Select files", MultiSelect:=True)

 If IsArray(SelectedFiles) Then

    For i = LBound(SelectedFiles) To UBound(SelectedFiles)
        Set wbkToOpen = Workbooks.Open(Filename:=SelectedFiles(i), corruptload:=xlRepairFile)

        Debug.Print wbkToOpen.Name
        Debug.Print SelectedFiles(i)

        wbkToOpen.Close savechanges:=False

    Next

End If


问:
ObservableCollection needs three more methods/properties. Does some other collection have them?
I have looked around a bit for this--can't find the proper collection

Here is the signature of my desired ViewModel. There are some interesting
alternatives out there David Hill's CollectionViewModel or ObservableDictionary(Of TKey, TValue) on codeplex. But for now, I would like a built-in collection (for SL4) that handles this. Thanks

```<code>public class myViewModel: INotifyPropertyChanged
{
    public ObservableCollection<MyDataType> MyCollection;
    private ObservableCollection<MyDataType> _myCollection;

    public CurrentItem<MyDataType>() { return _myCollection.CurrentItem;}

    public int GetCurrentIndex()  { return _myCollection.CurrentIndex;}
    public SetCurrentIndex(int Index)   { _myCollection.CurrentIndex = Index;}
</code>```

答: There isn't a built-in collection that provides this.  However, you could just store the currentIndex value as a private int inside your ViewModel, and refer to it for the current index methods, as well as use it for CurrentItem<T>().

Body:
I have looked around a bit for this--can't find the proper collection

Here is the signature of my desired ViewModel. There are some interesting
alternatives out there David Hill's CollectionViewModel or ObservableDictionary(Of TKey, TValue) on codeplex. But for now, I would like a built-in collection (for SL4) that handles this. Thanks

public class myViewModel: INotifyPropertyChanged
{
    public ObservableCollection<MyDataType> MyCollection;
    private ObservableCollection<MyDataType> _myCollection;

    public CurrentItem<MyDataType>() { return _myCollection.CurrentItem;}

    public int GetCurrentIndex()  { return _myCollection.CurrentIndex;}
    public SetCurrentIndex(int Index)   { _myCollection.CurrentIndex = Index;}


问:
Sorting to find maximum values
Here is a sample data table:

```<code>ID Number   Test Type   Score
001            A         81
001            A         75
001            A         93
001            B         62
001            B         87
001            B         82
002            A         91
002            A         83
002            B         94
002            B         97
</code>```

What I want, in excel, is a return of the maximum score of each test type for each id number so it would look like this...

```<code>ID Number   Test Type   Score
001            A         93
001            B         87
002            A         91
002            B         97
</code>```

Is that possible?

答:
You can use MAXIFS().  On your second table, if you have the ID number and Test Types, in the C column you can do:

```<code>=MAXIFS(Sheet1!$C$2:$C$1000,Sheet1!$A$2:$A$1000,$A2,Sheet1!$B$2:$B$1000,$B2)
</code>```

Where Sheet1 is your main table.

Title: Sorting to find maximum values

Body:
Here is a sample data table:

ID Number   Test Type   Score
001            A         81
001            A         75
001            A         93
001            B         62
001            B         87
001            B         82
002            A         91
002            A         83
002            B         94
002            B         97

What I want, in excel, is a return of the maximum score of each test type for each id number so it would look like this...

ID Number   Test Type   Score
001            A         93
001            B         87
002            A         91
002            B         97

Is that possible?

Body:
You can use MAXIFS().  On your second table, if you have the ID number and Test Types, in the C column you can do:

=MAXIFS(Sheet1!$C$2:$C$1000,Sheet1!$A$2:$A$1000,$A2,Sheet1!$B$2:$B$1000,$B2)

Where Sheet1 is your main table.


问:
Downcasting Objective-C object to Swift type fails (silently)
This was discussed here; similar but not identical.

MyView is a Swift subclass of UIImageView. It compiles and its interface appears in the DerivedData/.../*-Swift.h file. But downcasting to it in Obj-C fails. The code:

```<code>MyView* myView = (MyView*)viewThatCameFromIB;
// The Custom Class declared in IB inspector as MyView.
</code>```

results in this line in the Xcode Variable Viewer:

```<code>myView  UIImageView *  0x7fc8e9417e00
</code>```

This line of code executes with no failure. But sure enough, trying to use the MyView features on the myView variable crashes with unknown selector. Since the cast succeeded in Obj-C, before MyClass was ported, it should also after the port, n'est-ce pas?

I tried:

deleting and resetting the Custom Class in IB just in case.

breaking this line of code into multiple steps.

Now this worked:

instantiate a MyView directly with its init() method

That is, I got a MyView instance:

```<code>myView  _TtC12YadaYada11MyView *  0x7f8bc05487d0
</code>```

(Consequently, I can think of a workaround: write a Swift MyView constructor that takes a UIImageView and uses it to construct itself. But I shouldn't have to. Isn't that what the downcast would do behind the scenes?)

答: The problem seems to be caused (fixed) by clearing (setting) the Inherit Module From Target boolean for the MyView view, in the Custom Class section of the Identity Inspector. At least in the from-scratch test case. In my particular porting challenge, with 3,000+ files (and 50+ MyViews), there may be confounding factors. But for now, this is the answer.

Body:
This was discussed here; similar but not identical.

MyView is a Swift subclass of UIImageView. It compiles and its interface appears in the DerivedData/.../*-Swift.h file. But downcasting to it in Obj-C fails. The code:

MyView* myView = (MyView*)viewThatCameFromIB;
// The Custom Class declared in IB inspector as MyView.

results in this line in the Xcode Variable Viewer:

myView  UIImageView *  0x7fc8e9417e00

This line of code executes with no failure. But sure enough, trying to use the MyView features on the myView variable crashes with unknown selector. Since the cast succeeded in Obj-C, before MyClass was ported, it should also after the port, n'est-ce pas?

I tried:

deleting and resetting the Custom Class in IB just in case.

breaking this line of code into multiple steps.

Now this worked:

instantiate a MyView directly with its init() method

That is, I got a MyView instance:

myView  _TtC12YadaYada11MyView *  0x7f8bc05487d0

(Consequently, I can think of a workaround: write a Swift MyView constructor that takes a UIImageView and uses it to construct itself. But I shouldn't have to. Isn't that what the downcast would do behind the scenes?)