问:
How to handle interface for onActivityResult Override Method
I want to use onActivityResult method in Adapter but after searching on Stack Overflow I found I have to make interface for onActivityResult but I donot know how to make this and handle onActivityResult Methode to work as per my need.

Here is my Adapter Class.

```<code>    public class PosterAdapter extends RecyclerView.Adapter<PosterAdapter.PosterViewHolder> {

    private static final String TAG = "resPoster";
    private ArrayList<Poster> posterArrayList;
    private Context context;

    public PosterAdapter(ArrayList<Poster> posterArrayList, Context context) {
        this.posterArrayList = posterArrayList;
        this.context = context;
    }

    @NonNull
    @Override
    public PosterViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View itemView = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.sending_image_layout, viewGroup, false);

        return new PosterViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull PosterViewHolder posterViewHolder, int i) {

        posterViewHolder.imageViewDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                posterViewHolder.relativeLayoutImage.setDrawingCacheEnabled(true);

                Bitmap bitmap = Bitmap.createBitmap(posterViewHolder.relativeLayoutImage.getDrawingCache());
                posterViewHolder.relativeLayoutImage.setDrawingCacheEnabled(false);

                FileOutputStream outStream = null;
                File sdCard = Environment.getExternalStorageDirectory();
                File dir = new File(sdCard.getAbsolutePath() + "/providers");
                dir.mkdirs();
                String fileName = String.format("%d.jpg", System.currentTimeMillis());
                Log.d(TAG,"filename: " +  fileName);
                File outFile = new File(dir, fileName);
                Log.d(TAG,"outFile: " +  outFile);
                try {
                    outStream = new FileOutputStream(outFile);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
                    outStream.flush();
                    outStream.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });

        posterViewHolder.imageViewEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent();
                i.setType("image/*");
                i.setAction(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
//                startActivityForResult(i, 0);
                ((Activity) context).startActivityForResult(Intent.createChooser(i, "CHOOSING INTENT"), 0);
            }
        });

    }

    @Override
    public int getItemCount() {
        return posterArrayList.size();
    }

    public class PosterViewHolder extends RecyclerView.ViewHolder {

        RelativeLayout relativeLayoutImage;
        ImageView imageViewBg, imageViewEdit, imageViewDownload, imageViewShare;
        CircleImageView imageViewProfie;

        public PosterViewHolder(@NonNull View posterView) {
            super(posterView);

            relativeLayoutImage = posterView.findViewById(R.id.image_relative);
            imageViewBg = posterView.findViewById(R.id.image_bg);
            imageViewProfie = posterView.findViewById(R.id.image_profile_moving);
            imageViewEdit = posterView.findViewById(R.id.edit_image);
            imageViewDownload = posterView.findViewById(R.id.download_image);
            imageViewShare = posterView.findViewById(R.id.share_image);

        }
    }

}
</code>```

and I want to use this class

```<code> @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode == RESULT_OK) {
        if (requestCode == 0) {
            final Uri selectedUri = data.getData();
            if (selectedUri != null) {
                startCrop(selectedUri);
            } else {
                Toast.makeText(context, "Cannot retrieve selected Image", Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == UCrop.REQUEST_CROP) {
            handleCropResult(data);
        }
    }
    if (resultCode == UCrop.RESULT_ERROR) {
        handleCropError(data);
    }
}
</code>```

Please Help me handle this method in interface.
Thank you.

**UPDATE: **

Here is my activity code to understand more my question.

```<code>     RequestQueue requestQueue;
    private ArrayList<Poster> posterArrayList = new ArrayList<>();
    private RecyclerView recyclerView;
    private PosterAdapter posterAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sending_image);

        requestQueue = Volley.newRequestQueue(this);

        recyclerView = findViewById(R.id.recycler_poster);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        getAllPoster();
    }

    private void getAllPoster() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("poster_id", "1");

        Log.d(TAG + "pp", String.valueOf(params));

        String Url = Constants.Base_URL + "poster/";

        JsonObjectRequest request = new JsonObjectRequest(Url,  new JSONObject(params),
                response -> {
                    Log.d("responsePending", String.valueOf(response));

                    try {
                        String statusResponseObject = response.getString("status");
                        String msgObject = response.getString("msg");

                        if (statusResponseObject.equals("200")){

                            JSONArray jsonArray = response.getJSONArray("response");

                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject pendingFragResponse = jsonArray.getJSONObject(i);

                                String posterObject = pendingFragResponse.getString("poster");
                                String positionObject = pendingFragResponse.getString("position");
                                String sizeObject = pendingFragResponse.getString("size");
                                String txt_positionObject = pendingFragResponse.getString("txt_position");
                                String titleObject = pendingFragResponse.getString("title");
                                String descriptionObject = pendingFragResponse.getString("description");

                                //

                                posterArrayList.add(new Poster(posterObject, positionObject,
                                        sizeObject, txt_positionObject,
                                        titleObject, descriptionObject));
                                posterAdapter = new PosterAdapter( posterArrayList, SendingImageActivity.this);
                                recyclerView.setAdapter(posterAdapter);
//                                wp10ProgressBar.hideProgressBar();
//                                wp10ProgressBar.setVisibility(View.GONE);

                            }
                            posterAdapter.notifyDataSetChanged();
//                            wp10ProgressBar.hideProgressBar();
                        }else {
//                            wp10ProgressBar.hideProgressBar();
//                            wp10ProgressBar.setVisibility(View.GONE);
                            Toast.makeText(SendingImageActivity.this, msgObject, Toast.LENGTH_SHORT).show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();
                    }

                }, error -> {
            error.printStackTrace();
            Log.d(TAG + "error", String.valueOf(error.getMessage()));
            Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();

        });

        requestQueue.add(request);
    }

}

                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();
                    }

                }, error -> {
            error.printStackTrace();
            Log.d(TAG + "error", String.valueOf(error.getMessage()));
            Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();

        });

        requestQueue.add(request);
    }

}
</code>```

答:
Create a method in adapter

In your adapter class

```<code>    public void waterverYouWantMethod(){

}
</code>```

And call that method from Activity when onActivityResult mehtod called.

```<code>    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK) {
   // call that method here
adapter.wateverYouWantMethod();

    }

    }
</code>```

Body:
I want to use onActivityResult method in Adapter but after searching on Stack Overflow I found I have to make interface for onActivityResult but I donot know how to make this and handle onActivityResult Methode to work as per my need.

Here is my Adapter Class.

    public class PosterAdapter extends RecyclerView.Adapter<PosterAdapter.PosterViewHolder> {

    private static final String TAG = "resPoster";
    private ArrayList<Poster> posterArrayList;
    private Context context;

    public PosterAdapter(ArrayList<Poster> posterArrayList, Context context) {
        this.posterArrayList = posterArrayList;
        this.context = context;
    }

    @NonNull
    @Override
    public PosterViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View itemView = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.sending_image_layout, viewGroup, false);

        return new PosterViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull PosterViewHolder posterViewHolder, int i) {

        posterViewHolder.imageViewDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                posterViewHolder.relativeLayoutImage.setDrawingCacheEnabled(true);

                Bitmap bitmap = Bitmap.createBitmap(posterViewHolder.relativeLayoutImage.getDrawingCache());
                posterViewHolder.relativeLayoutImage.setDrawingCacheEnabled(false);

                FileOutputStream outStream = null;
                File sdCard = Environment.getExternalStorageDirectory();
                File dir = new File(sdCard.getAbsolutePath() + "/providers");
                dir.mkdirs();
                String fileName = String.format("%d.jpg", System.currentTimeMillis());
                Log.d(TAG,"filename: " +  fileName);
                File outFile = new File(dir, fileName);
                Log.d(TAG,"outFile: " +  outFile);
                try {
                    outStream = new FileOutputStream(outFile);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
                    outStream.flush();
                    outStream.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });

        posterViewHolder.imageViewEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent();
                i.setType("image/*");
                i.setAction(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
//                startActivityForResult(i, 0);
                ((Activity) context).startActivityForResult(Intent.createChooser(i, "CHOOSING INTENT"), 0);
            }
        });

    }

    @Override
    public int getItemCount() {
        return posterArrayList.size();
    }

    public class PosterViewHolder extends RecyclerView.ViewHolder {

        RelativeLayout relativeLayoutImage;
        ImageView imageViewBg, imageViewEdit, imageViewDownload, imageViewShare;
        CircleImageView imageViewProfie;

        public PosterViewHolder(@NonNull View posterView) {
            super(posterView);

            relativeLayoutImage = posterView.findViewById(R.id.image_relative);
            imageViewBg = posterView.findViewById(R.id.image_bg);
            imageViewProfie = posterView.findViewById(R.id.image_profile_moving);
            imageViewEdit = posterView.findViewById(R.id.edit_image);
            imageViewDownload = posterView.findViewById(R.id.download_image);
            imageViewShare = posterView.findViewById(R.id.share_image);

        }
    }

}

and I want to use this class

 @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode == RESULT_OK) {
        if (requestCode == 0) {
            final Uri selectedUri = data.getData();
            if (selectedUri != null) {
                startCrop(selectedUri);
            } else {
                Toast.makeText(context, "Cannot retrieve selected Image", Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == UCrop.REQUEST_CROP) {
            handleCropResult(data);
        }
    }
    if (resultCode == UCrop.RESULT_ERROR) {
        handleCropError(data);
    }
}

Please Help me handle this method in interface.
Thank you.

**UPDATE: **

Here is my activity code to understand more my question.

     RequestQueue requestQueue;
    private ArrayList<Poster> posterArrayList = new ArrayList<>();
    private RecyclerView recyclerView;
    private PosterAdapter posterAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sending_image);

        requestQueue = Volley.newRequestQueue(this);

        recyclerView = findViewById(R.id.recycler_poster);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        getAllPoster();
    }

    private void getAllPoster() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("poster_id", "1");

        Log.d(TAG + "pp", String.valueOf(params));

        String Url = Constants.Base_URL + "poster/";

        JsonObjectRequest request = new JsonObjectRequest(Url,  new JSONObject(params),
                response -> {
                    Log.d("responsePending", String.valueOf(response));

                    try {
                        String statusResponseObject = response.getString("status");
                        String msgObject = response.getString("msg");

                        if (statusResponseObject.equals("200")){

                            JSONArray jsonArray = response.getJSONArray("response");

                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject pendingFragResponse = jsonArray.getJSONObject(i);

                                String posterObject = pendingFragResponse.getString("poster");
                                String positionObject = pendingFragResponse.getString("position");
                                String sizeObject = pendingFragResponse.getString("size");
                                String txt_positionObject = pendingFragResponse.getString("txt_position");
                                String titleObject = pendingFragResponse.getString("title");
                                String descriptionObject = pendingFragResponse.getString("description");

                                //

                                posterArrayList.add(new Poster(posterObject, positionObject,
                                        sizeObject, txt_positionObject,
                                        titleObject, descriptionObject));
                                posterAdapter = new PosterAdapter( posterArrayList, SendingImageActivity.this);
                                recyclerView.setAdapter(posterAdapter);
//                                wp10ProgressBar.hideProgressBar();
//                                wp10ProgressBar.setVisibility(View.GONE);

                            }
                            posterAdapter.notifyDataSetChanged();
//                            wp10ProgressBar.hideProgressBar();
                        }else {
//                            wp10ProgressBar.hideProgressBar();
//                            wp10ProgressBar.setVisibility(View.GONE);
                            Toast.makeText(SendingImageActivity.this, msgObject, Toast.LENGTH_SHORT).show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();
                    }

                }, error -> {
            error.printStackTrace();
            Log.d(TAG + "error", String.valueOf(error.getMessage()));
            Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();

        });

        requestQueue.add(request);
    }

}

                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();
                    }

                }, error -> {
            error.printStackTrace();
            Log.d(TAG + "error", String.valueOf(error.getMessage()));
            Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();

        });

        requestQueue.add(request);
    }

}

Body:
Create a method in adapter

In your adapter class

    public void waterverYouWantMethod(){

}

And call that method from Activity when onActivityResult mehtod called.

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK) {
   // call that method here
adapter.wateverYouWantMethod();

    }

    }


来源: stackexchange

问:
Memory Leak when using DirectorySearcher.FindAll()
I have a long running process that needs to do a lot of queries on Active Directory quite often. For this purpose I have been using the System.DirectoryServices namespace, using the DirectorySearcher and DirectoryEntry classes. I have noticed a memory leak in the application.

It can be reproduced with this code:

```<code>while (true)
{
    using (var de = new DirectoryEntry("LDAP://hostname", "user", "pass"))
    {
        using (var mySearcher = new DirectorySearcher(de))
        {
            mySearcher.Filter = "(objectClass=domain)";
            using (SearchResultCollection src = mySearcher.FindAll())
            {
            }
         }
    }
}
</code>```

The documentation for these classes say that they will leak memory if Dispose() is not called. I have tried without dispose as well, it just leaks more memory in that case. I have tested this with both framework versions 2.0 and 4.0 Has anyone run into this before? Are there any workarounds?

Update: I tried running the code in another AppDomain, and it didn't seem to help either.

答:
Have you tried using and Dispose()?
Info from here

Update

Try calling de.Close(); before the end of the using.

I don't actually have an Active Domain Service to test this on, sorry.

ContentLicense: CC BY-SA 3.0

Body:
I have a long running process that needs to do a lot of queries on Active Directory quite often. For this purpose I have been using the System.DirectoryServices namespace, using the DirectorySearcher and DirectoryEntry classes. I have noticed a memory leak in the application.

It can be reproduced with this code:

while (true)
{
    using (var de = new DirectoryEntry("LDAP://hostname", "user", "pass"))
    {
        using (var mySearcher = new DirectorySearcher(de))
        {
            mySearcher.Filter = "(objectClass=domain)";
            using (SearchResultCollection src = mySearcher.FindAll())
            {
            }
         }
    }
}

The documentation for these classes say that they will leak memory if Dispose() is not called. I have tried without dispose as well, it just leaks more memory in that case. I have tested this with both framework versions 2.0 and 4.0 Has anyone run into this before? Are there any workarounds?

Update: I tried running the code in another AppDomain, and it didn't seem to help either.


问:
custom category tree in wordpress
Hi i want to create a tree of categories in wordpress like this :

```<code><ul>
    <a href=""> PARENT1 </a>
    <li><a href=""> CHILD 1-1</a></li>
    <li><a href=""> CHILD 1-2</a></li>
     .
     .
     .
</ul>
<ul>
    <a href=""> PARENT2 </a>
    <li><a href=""> CHILD 2-1</a></li>
    <li><a href=""> CHILD 2-2</a></li>
     .
     .
     .
</ul>
</code>```

i want something that creates categories list in above format and show only categories which have children and hide those who don't

I Tried Something like this but it didn't give me what i wanted

```<code><?php $args = array(
'type'                     => 'post',
'child_of'                 => 0,
'parent'                   => '',
'orderby'                  => 'name',
'order'                    => 'ASC',
'hide_empty'               => 0,
'hierarchical'             => 1,
'exclude'                  => '',
'include'                  => '',
'number'                   => '',
'taxonomy'                 => 'category',
'pad_counts'               => false
);
$cats = get_categories( $args );
foreach( $cats as $cat) {
    if($cat->parent == 0) {
        $head = $cat->name;
        $cat_id = $cat->term_id;
    }
    echo "<a href=''>" . $head . "</a>";
    wp_list_cats("sort_column=NAME&optioncount=0&hierarchical=1&hide_empty=0&child_of={$cat_id}");
}
</code>```

?>

答:
It's a very old post, but maybe some more clean code. For all the options of get_terms please see the docs. Feel free to make it more generic:

function build_custom_category_tree ($activeCatId, $activeParentId, $parentId = 0) {

    $output = '';
    $terms = get_terms( array(
        'taxonomy' => 'custom_categories',
        'hide_empty' => true,
        'hierarchical' => true,
        'parent' => $parentId
    ) );

    if (count($terms)) {

        $output .= '
';

        foreach ($terms as $term) {
            $output .= '
term_id === $activeParentId || $term->term_id === $activeCatId ? ' active' : '') . '">';
            $output .=  $term->name;
            $output .=  build_custom_category_tree($activeCatId, $activeParentId, $term->term_id);
            $output .= '
';
        }

        $output .= '
';
    }

    return $output;
}
```

<p>And then in your template:</p>

<pre class="lang-html prettyprint-override"><code><div>
   <?= build_custom_category_tree($catIdOfPost, $rootIdOfCat) ?>
</div>
</code>```

Title: custom category tree in wordpress

Body:
Hi i want to create a tree of categories in wordpress like this :

     PARENT1

 CHILD 1-1

 CHILD 1-2

     .
     .
     .

     PARENT2

 CHILD 2-1

 CHILD 2-2

     .
     .
     .

i want something that creates categories list in above format and show only categories which have children and hide those who don't

I Tried Something like this but it didn't give me what i wanted

<?php $args = array(
'type'                     => 'post',
'child_of'                 => 0,
'parent'                   => '',
'orderby'                  => 'name',
'order'                    => 'ASC',
'hide_empty'               => 0,
'hierarchical'             => 1,
'exclude'                  => '',
'include'                  => '',
'number'                   => '',
'taxonomy'                 => 'category',
'pad_counts'               => false
);
$cats = get_categories( $args );
foreach( $cats as $cat) {
    if($cat->parent == 0) {
        $head = $cat->name;
        $cat_id = $cat->term_id;
    }
    echo "" . $head . "";
    wp_list_cats("sort_column=NAME&optioncount=0&hierarchical=1&hide_empty=0&child_of={$cat_id}");
}

?>

Body:
It's a very old post, but maybe some more clean code. For all the options of get_terms please see the docs. Feel free to make it more generic:

function build_custom_category_tree ($activeCatId, $activeParentId, $parentId = 0) {

    $output = '';
    $terms = get_terms( array(
        'taxonomy' => 'custom_categories',
        'hide_empty' => true,
        'hierarchical' => true,
        'parent' => $parentId
    ) );

    if (count($terms)) {

        $output .= '<ul>';

        foreach ($terms as $term) {
            $output .= '<li class="custom-cat' . ($term->term_id === $activeParentId || $term->term_id === $activeCatId ? ' active' : '') . '">';
            $output .=  $term->name;
            $output .=  build_custom_category_tree($activeCatId, $activeParentId, $term->term_id);
            $output .= '</li>';
        }

        $output .= '</ul>';
    }

    return $output;
}

And then in your template:

<div>
   <?= build_custom_category_tree($catIdOfPost, $rootIdOfCat) ?>
</div>

ContentLicense: CC BY-SA 4.0


问:
How can i know which link I clicked?
I'm deploying a table where you can edit the columns. For that, in each cell there's an  to show a modal to change que value in the database and refresh the page. For now it does well the modal appearing but for the moment the modal appears, the code doesn't know which link was clicked. I need to know it to get the id of the row. The JQuery method that calls the last button of the modal ('Guardar') needs to call a php script by AJAX and send the id of the row (to make the UPDATE statement) and the new value of the column.

I tried to use the methods closest() and find() from JQuery and to set a the id of the row in a data-id attribute.

This is where I deploy the table vía PHP(code is simplified to one column to read and understand it better)

```<code>if($resHitos->num_rows>0){
    while ($columna = mysqli_fetch_assoc($resHitos)) {
        $id=$columna['id'];
        echo "<tr data-id='$id'>";
        echo "<td style='text-align:center'><p><a data-toggle='modal' data-target='#modalEditHito'>".$columna['descripcion']."</a></p></td>";
        echo "</tr>";
    }
}
</code>```

This is the modal

```<code><div class="modal fade" id="modalEditarHito" role="dialog">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Editar objetivo</h4>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label for="newObjetivo">Objetivo</label>
                        <textarea class="form-control" rows="5" id="editObjetivo"></textarea><br>
                 </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal" onclick="editDescripcionHito()">Guardar</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
            </div>
        </div>
    </div>
</div>
</code>```

The expected result is to see the new value inputed in the exact row that was clicked.

答:
Add listener event on your modal when it is displayed.</p>

```<code>$(document).on('show.bs.modal','#modalEditHito', function (e) {
  var $invoker = $(e.relatedTarget);
  //this may help
  //var tr = $invoker.closest('tr');
  //var tr_id = tr.attr("data-id");
});
</code>```

Title: How can i know which link I clicked?

Body:
I'm deploying a table where you can edit the columns. For that, in each cell there's an  to show a modal to change que value in the database and refresh the page. For now it does well the modal appearing but for the moment the modal appears, the code doesn't know which link was clicked. I need to know it to get the id of the row. The JQuery method that calls the last button of the modal ('Guardar') needs to call a php script by AJAX and send the id of the row (to make the UPDATE statement) and the new value of the column.

I tried to use the methods closest() and find() from JQuery and to set a the id of the row in a data-id attribute.

This is where I deploy the table vía PHP(code is simplified to one column to read and understand it better)

if($resHitos->num_rows>0){
    while ($columna = mysqli_fetch_assoc($resHitos)) {
        $id=$columna['id'];
        echo "
";
        echo "
".$columna['descripcion']."
	";
        echo "
";
    }
}

This is the modal

Editar objetivo

                    Objetivo
                        <textarea class="form-control" rows="5" id="editObjetivo"></textarea>

                <button type="button" class="btn btn-default" data-dismiss="modal" onclick="editDescripcionHito()">Guardar</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>

The expected result is to see the new value inputed in the exact row that was clicked.

Body:
Add listener event on your modal when it is displayed.

$(document).on('show.bs.modal','#modalEditHito', function (e) {
  var $invoker = $(e.relatedTarget);
  //this may help
  //var tr = $invoker.closest('tr');
  //var tr_id = tr.attr("data-id");
});


问:
Embed HTTP Web Site into SharePoint Online
Just wondering is there a way of embedding a HTTP web site into SharePoint Online. I see you can embed some HTTPS web sites into SharePoint Online. I am not interested in HTTPS web sites as such. I have a web page which runs under XAMPP, and I wanted to embed it into SharePoint Online.

Perhaps on the other hand there might be an app that allows such functionality?

Please advise

Any help much appreciated.

答:
The problem you will have is a browser security issue.  If you are connecting to SharePoint online you will be using HTTPS. If you try to iFrame in an HTTP site, the browser will likely block it with a mixed content error.  Nothing to do with SharePoint, this is browser security.

You will need to support HTTPS on your external web site, then use a Page Viewer Web Part to iFrame in your external site and use the HTTPS url.


问:
Eloquent condition not detecting accented letters in where condition
In my web application I have locations and every location has company_id and I don't want to have same names of location in same company. So I made this:

```<code>$name = $request->get('name');
$location = Location::find($id);
if ($location->name != $name) {
    $old_location = Location::where('company_id', $location->company_id)
        ->where('name', $name)
        ->first();
    if ($old_location) {
        $errors = ['name' => trans('asset.location').' '.$name.'
        '.trans('message.already_exists')];
            return back()->withErrors($errors)->withInput();
    }
}
</code>```

The problem is that if I have Service location and want to change it's name to Šervice it will not let me to do it. I have no location that is named like that. If condition goes through but in eloquent search it fails. How is this possible?

答:
Make sure you have correctly specfied the charset in config file. like

```<code>'charset'   => 'utf8',
'collation' => 'utf8_unicode_ci',
</code>```

src: Laravel 5.1 utf-8 saving to database

AND

I think, you must use the laravel validation here. So it could validate the request before processing.

```<code>Validator::extend('uniqueLocationInCompany', function ($attribute, $value, $parameters, $validator) {
    $count = DB::table('locations')->where('name', $value)
                                ->where('company_id', $parameters[0])
                                ->count();

    return $count === 0;
});
</code>```

You could then access this new rule in validator function:

```<code>'name' => "uniqueLocationInCompany:{$request->company_id}"
</code>```

For more awareness on how should we implement validation in laravel you should follow the documentation here.

https://laravel.com/docs/5.8/validation

Body:
In my web application I have locations and every location has company_id and I don't want to have same names of location in same company. So I made this:

$name = $request->get('name');
$location = Location::find($id);
if ($location->name != $name) {
    $old_location = Location::where('company_id', $location->company_id)
        ->where('name', $name)
        ->first();
    if ($old_location) {
        $errors = ['name' => trans('asset.location').' '.$name.'
        '.trans('message.already_exists')];
            return back()->withErrors($errors)->withInput();
    }
}

The problem is that if I have Service location and want to change it's name to Šervice it will not let me to do it. I have no location that is named like that. If condition goes through but in eloquent search it fails. How is this possible?

Body:
Make sure you have correctly specfied the charset in config file. like

'charset'   => 'utf8',
'collation' => 'utf8_unicode_ci',

src: Laravel 5.1 utf-8 saving to database

AND

I think, you must use the laravel validation here. So it could validate the request before processing.

Validator::extend('uniqueLocationInCompany', function ($attribute, $value, $parameters, $validator) {
    $count = DB::table('locations')->where('name', $value)
                                ->where('company_id', $parameters[0])
                                ->count();

    return $count === 0;
});

You could then access this new rule in validator function:

'name' => "uniqueLocationInCompany:{$request->company_id}"

For more awareness on how should we implement validation in laravel you should follow the documentation here.

https://laravel.com/docs/5.8/validation


问:
Top 10 records with sum of remaining records in others in SQL server
I have one table which consists of 4 Columns - (id int, location varchar (max), [date] datetime, Total_Sales Money) which consist of 20 records in output I want 11 rows in which top 10 rows as it is and 11th row should be sum of remaining rows i.e. from 11 to 20 in Other_Location. Please help me to get the query.

I want 11 rows in which top 10 rows as it is and 11th row should be sum of remaining rows

答:
You can select top 10 rows and 1 row sum with union

May be code:

```<code>SELECT id, location, date, total_sales FROM table limit 10 // where etc..
UNION
SELECT 0 as id, '' as location, 0 as date, sum(total_sales) as total_sales FROM table;
</code>```

Body:
You can select top 10 rows and 1 row sum with union

May be code:

SELECT id, location, date, total_sales FROM table limit 10 // where etc..
UNION
SELECT 0 as id, '' as location, 0 as date, sum(total_sales) as total_sales FROM table;


答:
In SQL Server 2012, using ROW_NUMBER() window function, you can achive this. Create ROW_NUMBER() to set RowNum for each row and based on the result, using UNION ALL it will return the result:

```<code>;WITH CTE AS (
    SELECT id, location, [date], Total_Sales,
           ROW_NUMBER() OVER (ORDER BY Id) AS RowNum
    FROM TableName
)

SELECT CAST(id AS VARCHAR(30)) AS Id,
       location,
       CAST([date] AS VARCHAR(30)) AS [date],
       CAST(Total_Sales AS VARCHAR(30)) AS Total_Sales
FROM CTE
WHERE RowNum BETWEEN 1 AND 10
UNION
SELECT '11-20 ids' AS id,
       '11-20 AS locations' as location,
       '11-20 dates' AS [date],
       SUM(Total_Sales) AS Total_Sales
FROM CTE
WHERE RowNum BETWEEN 11 AND 20
</code>```

Demo on db<>fiddle

Title: Top 10 records with sum of remaining records in others in SQL server

Body:
I have one table which consists of 4 Columns - (id int, location varchar (max), [date] datetime, Total_Sales Money) which consist of 20 records in output I want 11 rows in which top 10 rows as it is and 11th row should be sum of remaining rows i.e. from 11 to 20 in Other_Location. Please help me to get the query.

I want 11 rows in which top 10 rows as it is and 11th row should be sum of remaining rows

Body:
In SQL Server 2012, using ROW_NUMBER() window function, you can achive this. Create ROW_NUMBER() to set RowNum for each row and based on the result, using UNION ALL it will return the result:

;WITH CTE AS (
    SELECT id, location, [date], Total_Sales,
           ROW_NUMBER() OVER (ORDER BY Id) AS RowNum
    FROM TableName
)

SELECT CAST(id AS VARCHAR(30)) AS Id,
       location,
       CAST([date] AS VARCHAR(30)) AS [date],
       CAST(Total_Sales AS VARCHAR(30)) AS Total_Sales
FROM CTE
WHERE RowNum BETWEEN 1 AND 10
UNION
SELECT '11-20 ids' AS id,
       '11-20 AS locations' as location,
       '11-20 dates' AS [date],
       SUM(Total_Sales) AS Total_Sales
FROM CTE
WHERE RowNum BETWEEN 11 AND 20

Demo on db<>fiddle


问:
list index out of range when listing all projects using python-gitlab
I'm trying to use python-gitlab to list all my gitlab projects. But when I use the following code to list part of my projects in gitlab, I got list index out of range error.

# file name: poc.py
import gitlab

gl = gitlab.Gitlab(
    'http://my-gitlab.com:10080',
    private_token='<my_private_token>'
    )
projects = gl.projects.list(all=True)
for project in projects:
    print(project.attributes['name'])
```

<p>My gitlab server has more than 300 projects.</p>

<p>The following is the complete error message:</p>

```Traceback (most recent call last):
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/gitlab/__init__.py", line 783, in next
    item = self._data[self._current]
IndexError: list index out of range

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/urllib3/connection.py", line 159, in _new_conn
    (self._dns_host, self.port), self.timeout, **extra_kw)
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/urllib3/util/connection.py", line 80, in create_connection
    raise err
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/urllib3/util/connection.py", line 70, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [Errno 61] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/urllib3/connectionpool.py", line 600, in urlopen
    chunked=chunked)
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/urllib3/connectionpool.py", line 354, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/http/client.py", line 1239, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/http/client.py", line 1285, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/http/client.py", line 1234, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/http/client.py", line 1026, in _send_output
    self.send(msg)
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/http/client.py", line 964, in send
    self.connect()
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/urllib3/connection.py", line 181, in connect
    conn = self._new_conn()
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/urllib3/connection.py", line 168, in _new_conn
    self, "Failed to establish a new connection: %s" % e)
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x107784be0>: Failed to establish a new connection: [Errno 61] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/MyUserName/.local/lib/python3.6/site-packages/requests/adapters.py", line 449, in send
    timeout=timeout
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/urllib3/connectionpool.py", line 638, in urlopen
    _stacktrace=sys.exc_info()[2])
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/urllib3/util/retry.py", line 398, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='my-gitlab.com', port=80): Max retries exceeded with url: /api/v4/projects?membership=false&order_by=created_at&owned=false&page=2&per_page=20&simple=false&sort=desc&starred=false&statistics=false&with_custom_attributes=false&with_issues_enabled=false&with_merge_requests_enabled=false (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x107784be0>: Failed to establish a new connection: [Errno 61] Connection refused',))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "poc.py", line 15, in <module>
    projects = gl.projects.list(as_list=False, all=True)
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/gitlab/exceptions.py", line 255, in wrapped_f
    return f(*args, **kwargs)
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/gitlab/mixins.py", line 133, in list
    obj = self.gitlab.http_list(path, **data)
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/gitlab/__init__.py", line 597, in http_list
    return list(GitlabList(self, url, query_data, **kwargs))
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/gitlab/__init__.py", line 779, in __next__
    return self.next()
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/gitlab/__init__.py", line 788, in next
    self._query(self._next_url)
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/gitlab/__init__.py", line 716, in _query
    **kwargs)
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/gitlab/__init__.py", line 498, in http_request
    result = self.session.send(prepped, timeout=timeout, **settings)
  File "/Users/MyUserName/.local/lib/python3.6/site-packages/requests/sessions.py", line 646, in send
    r = adapter.send(request, **kwargs)
  File "/Users/MyUserName/.local/lib/python3.6/site-packages/requests/adapters.py", line 516, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='my-gitlab.com', port=80): Max retries exceeded with url: /api/v4/projects?membership=false&order_by=created_at&owned=false&page=2&per_page=20&simple=false&sort=desc&starred=false&statistics=false&with_custom_attributes=false&with_issues_enabled=false&with_merge_requests_enabled=false (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x107784be0>: Failed to establish a new connection: [Errno 61] Connection refused',))
```

<p>The error message <code>requests.exceptions.ConnectionError: HTTPConnectionPool(host='my-gitlab.com', port=80): Max retries exceeded</code> says that it uses port 80 instead of 10080 to communicate with gitlab server. This is because there was an <code>IndexError</code> triggered at line 825 of gitlab/<strong>init</strong>.py. So <code>python-gitlab</code> tried to use port 80 to see if this port works.</p>

<p>I've checked that the length of <code>self._data</code> is 20. And I don't know why <code>self._current</code> was added to <code>20</code>. <code>self._data[20]</code> triggers <code>IndexError</code> because the index's maximum value is 19.</p>

<p>For now, I use the following workaround to list all the projects:</p>

<pre class="lang-py prettyprint-override"><code>import gitlab

gl = gitlab.Gitlab(
    'http://my-gitlab.com:10080',
    private_token='<my_private_token>'
    )

current_page = 1
projects = dest_gitlab.projects.list(as_list=False)
total_pages = projects.total_pages
while (current_page <= total_pages):
    projects = gl.projects.list(as_list=False, per_page=100, page=current_page)
    for project in projects:
        print(project.attributes['name'])
    current_page += 1
</code>```

But this is inconvenient to list all projects.

The document here doesn't mention anything about this error.

Anyone know how to list all projects using python-gitlab?

Is this a bug of python-gitlab?

Is len(self._data) == 20 an expected behavior when calling gl.projects.list(all=True)?

答:
The reason for python-gitlab using port 80 to communicate with gitlab server is because this gitlab bug.

For now, I can only use the workaround or wait for gitlab to fix this bug.

import gitlab

gl = gitlab.Gitlab(
    'http://my-gitlab.com:10080',
    private_token='<my_private_token>'
    )

current_page = 1
projects = dest_gitlab.projects.list(as_list=False)
total_pages = projects.total_pages
while (current_page <= total_pages):
    projects = gl.projects.list(as_list=False, per_page=100, page=current_page)
    for project in projects:
        print(project.attributes['name'])
    current_page += 1
```

Body:
I'm trying to use python-gitlab to list all my gitlab projects. But when I use the following code to list part of my projects in gitlab, I got list index out of range error.

# file name: poc.py
import gitlab

gl = gitlab.Gitlab(
    'http://my-gitlab.com:10080',
    private_token='<my_private_token>'
    )
projects = gl.projects.list(all=True)
for project in projects:
    print(project.attributes['name'])

My gitlab server has more than 300 projects.

The following is the complete error message:

Traceback (most recent call last):
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/gitlab/__init__.py", line 783, in next
    item = self._data[self._current]
IndexError: list index out of range

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/urllib3/connection.py", line 159, in _new_conn
    (self._dns_host, self.port), self.timeout, **extra_kw)
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/urllib3/util/connection.py", line 80, in create_connection
    raise err
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/urllib3/util/connection.py", line 70, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [Errno 61] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/urllib3/connectionpool.py", line 600, in urlopen
    chunked=chunked)
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/urllib3/connectionpool.py", line 354, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/http/client.py", line 1239, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/http/client.py", line 1285, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/http/client.py", line 1234, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/http/client.py", line 1026, in _send_output
    self.send(msg)
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/http/client.py", line 964, in send
    self.connect()
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/urllib3/connection.py", line 181, in connect
    conn = self._new_conn()
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/urllib3/connection.py", line 168, in _new_conn
    self, "Failed to establish a new connection: %s" % e)
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x107784be0>: Failed to establish a new connection: [Errno 61] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/MyUserName/.local/lib/python3.6/site-packages/requests/adapters.py", line 449, in send
    timeout=timeout
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/urllib3/connectionpool.py", line 638, in urlopen
    _stacktrace=sys.exc_info()[2])
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/urllib3/util/retry.py", line 398, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='my-gitlab.com', port=80): Max retries exceeded with url: /api/v4/projects?membership=false&order_by=created_at&owned=false&page=2&per_page=20&simple=false&sort=desc&starred=false&statistics=false&with_custom_attributes=false&with_issues_enabled=false&with_merge_requests_enabled=false (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x107784be0>: Failed to establish a new connection: [Errno 61] Connection refused',))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "poc.py", line 15, in <module>
    projects = gl.projects.list(as_list=False, all=True)
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/gitlab/exceptions.py", line 255, in wrapped_f
    return f(*args, **kwargs)
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/gitlab/mixins.py", line 133, in list
    obj = self.gitlab.http_list(path, **data)
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/gitlab/__init__.py", line 597, in http_list
    return list(GitlabList(self, url, query_data, **kwargs))
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/gitlab/__init__.py", line 779, in __next__
    return self.next()
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/gitlab/__init__.py", line 788, in next
    self._query(self._next_url)
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/gitlab/__init__.py", line 716, in _query
    **kwargs)
  File "/Users/MyUserName/.pyenv/versions/3.6.5/lib/python3.6/site-packages/gitlab/__init__.py", line 498, in http_request
    result = self.session.send(prepped, timeout=timeout, **settings)
  File "/Users/MyUserName/.local/lib/python3.6/site-packages/requests/sessions.py", line 646, in send
    r = adapter.send(request, **kwargs)
  File "/Users/MyUserName/.local/lib/python3.6/site-packages/requests/adapters.py", line 516, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='my-gitlab.com', port=80): Max retries exceeded with url: /api/v4/projects?membership=false&order_by=created_at&owned=false&page=2&per_page=20&simple=false&sort=desc&starred=false&statistics=false&with_custom_attributes=false&with_issues_enabled=false&with_merge_requests_enabled=false (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x107784be0>: Failed to establish a new connection: [Errno 61] Connection refused',))

The error message requests.exceptions.ConnectionError: HTTPConnectionPool(host='my-gitlab.com', port=80): Max retries exceeded says that it uses port 80 instead of 10080 to communicate with gitlab server. This is because there was an IndexError triggered at line 825 of gitlab/init.py. So python-gitlab tried to use port 80 to see if this port works.

I've checked that the length of self._data is 20. And I don't know why self._current was added to 20. self._data[20] triggers IndexError because the index's maximum value is 19.

For now, I use the following workaround to list all the projects:

import gitlab

gl = gitlab.Gitlab(
    'http://my-gitlab.com:10080',
    private_token='<my_private_token>'
    )

current_page = 1
projects = dest_gitlab.projects.list(as_list=False)
total_pages = projects.total_pages
while (current_page <= total_pages):
    projects = gl.projects.list(as_list=False, per_page=100, page=current_page)
    for project in projects:
        print(project.attributes['name'])
    current_page += 1

But this is inconvenient to list all projects.

The document here doesn't mention anything about this error.

Anyone know how to list all projects using python-gitlab?

Is this a bug of python-gitlab?

Is len(self._data) == 20 an expected behavior when calling gl.projects.list(all=True)?


问:
How to add 2 Mat pixel values while iterating through pixels using OpenCV?
I have 2 Mat, both have same size. Then I split those 2 Mat to process the BGR value of each Mat (in my case, it's actually BGRA). Then I want to add each of BGR values from those 2 Mat and store it in blue, green, red variable.

I successfully adding 2 Mat without using pixel iteration, like this :

```<code>//below operation works
blue = img1_split1[0] + img2_split[0];
green = img1_split[1] + img2_split[1];
red = img1_split[2] + img2_split[2];
</code>```

But I'm facing Exception Unhandled if I use pixel iteration and add 2 pixel values from each Mat, like this :

Unhandled exception at 0x00007FF89AA69129 in VideoStitcher.exe:
  Microsoft C++ exception: cv::Exception at memory location
  0x000000ADA5CFD020.

Here's my code :

```<code>Mat img1, img2;
img1 = imread("some_image.jpg");  //this is just for example
img2 = imread("some_image.jpg");

vector<Mat> img1_split, img2_split;

split(img1, img1_split);
split(img2, img2_split);

Mat blue, green, red;

    for (int i = 0; i < img1.rows; i++)
    {
        for (int j = 0; j < img1.cols; j++)
        { //below operation doesn't work
            blue.at<uchar>(i, j) = img1_split1[0].at<uchar>(i, j) + img2_split[0].at<uchar>(i, j);
            green.at<uchar>(i, j) = img1_split[1].at<uchar>(i, j) + img2_split[1].at<uchar>(i, j);
            red.at<uchar>(i, j) = img1_split[2].at<uchar>(i, j) + img2_split[2].at<uchar>(i, j);
        }
    }
</code>```

Can somebody point out the mistake that I made? Thanks

答:
cv::Mat works like a shared smart pointer, so when one creates it  with the default constructor (i.e. cv::Mat x;), it does not have any data or type and its .data member points nowhere.

You need to pass at least rows and cols and type for it to be able to allocate the image data, for example, in your case it will be like:

```<code>Mat blue(img1.rows, img1.cols, CV_8UC1), green(img1.rows, img1.cols, CV_8UC1), red(img1.rows, img1.cols, CV_8UC1);
</code>```

I used CV_8UC1, since they are one channel images once you split them.

When you set pixels like this, you have to be careful with underflow and overflow... there is a nice function for that, it is call saturate_cast.

Body:
I have 2 Mat, both have same size. Then I split those 2 Mat to process the BGR value of each Mat (in my case, it's actually BGRA). Then I want to add each of BGR values from those 2 Mat and store it in blue, green, red variable.

I successfully adding 2 Mat without using pixel iteration, like this :

//below operation works
blue = img1_split1[0] + img2_split[0];
green = img1_split[1] + img2_split[1];
red = img1_split[2] + img2_split[2];

But I'm facing Exception Unhandled if I use pixel iteration and add 2 pixel values from each Mat, like this :

Unhandled exception at 0x00007FF89AA69129 in VideoStitcher.exe:
  Microsoft C++ exception: cv::Exception at memory location
  0x000000ADA5CFD020.

Here's my code :

Mat img1, img2;
img1 = imread("some_image.jpg");  //this is just for example
img2 = imread("some_image.jpg");

vector<Mat> img1_split, img2_split;

split(img1, img1_split);
split(img2, img2_split);

Mat blue, green, red;

    for (int i = 0; i < img1.rows; i++)
    {
        for (int j = 0; j < img1.cols; j++)
        { //below operation doesn't work
            blue.at<uchar>(i, j) = img1_split1[0].at<uchar>(i, j) + img2_split[0].at<uchar>(i, j);
            green.at<uchar>(i, j) = img1_split[1].at<uchar>(i, j) + img2_split[1].at<uchar>(i, j);
            red.at<uchar>(i, j) = img1_split[2].at<uchar>(i, j) + img2_split[2].at<uchar>(i, j);
        }
    }

Can somebody point out the mistake that I made? Thanks

Body:
cv::Mat works like a shared smart pointer, so when one creates it  with the default constructor (i.e. cv::Mat x;), it does not have any data or type and its .data member points nowhere.

You need to pass at least rows and cols and type for it to be able to allocate the image data, for example, in your case it will be like:

Mat blue(img1.rows, img1.cols, CV_8UC1), green(img1.rows, img1.cols, CV_8UC1), red(img1.rows, img1.cols, CV_8UC1);

I used CV_8UC1, since they are one channel images once you split them.

When you set pixels like this, you have to be careful with underflow and overflow... there is a nice function for that, it is call saturate_cast.


问:
How can I create a random array between a range of two other arrays?
I need to generate an array of random 20 bytes between a given range of arrays. Since arrays are comparable in Rust, this works:

```<code>let low = [0u8; 20];
let high = [2u8; 20];
assert_eq!(true, low < high);
assert_eq!(false, low > high);
assert_eq!(true, low == [0u8; 20]);
</code>```

For these bounds:

```<code>let low: [u8; 20] = [98, 0, 1, 0, 2, 6, 99, 3, 0, 5, 23, 3, 5, 6, 11, 8, 0, 2, 0, 17];
let high: [u8; 20] = [99, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1];
</code>```

These would be a valid result:

[98, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[99, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
```

<p>These are not:</p>

```[98, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[99, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]
```

<p>I want to do something like:</p>

```use rand::prelude::*;

fn main() {
    let low = [0u8; 20];
    let high = [2u8; 20];
    let value = rand::thread_rng().gen_range(low, high);
    println!("{:?}", value);
}
```

<p>but I get following error:</p>

<pre class="lang-none prettyprint-override"><code>error[E0277]: the trait bound `[u8; 20]: rand::distributions::uniform::SampleUniform` is not satisfied
 --> src\main.rs:6:36
  |
6 |     let value = rand::thread_rng().gen_range(low, high);
  |                                    ^^^^^^^^^ the trait `rand::distributions::uniform::SampleUniform` is not implemented for `[u8; 20]`
</code>```

I tried implementing SampleUniform and UniformSampler without much success. Is there a simple way to implement this?

答:
If you want to treat the byte arrays as big integers, use the
num-bigint crate with the rand feature enabled:

use bigint::{ToBigInt, RandBigInt};

let low = -10000.to_bigint().unwrap();
let high = 10000.to_bigint().unwrap();
let b = rng.gen_bigint_range(&low, &high);
```

You could also use unsigned integers instead of signed. There are methods to convert to and from big endian byte arrays:

from_bytes_be

to_bytes_be

See also:

How do I generate a random num::BigUint?

Body:
I need to generate an array of random 20 bytes between a given range of arrays. Since arrays are comparable in Rust, this works:

let low = [0u8; 20];
let high = [2u8; 20];
assert_eq!(true, low < high);
assert_eq!(false, low > high);
assert_eq!(true, low == [0u8; 20]);

For these bounds:

let low: [u8; 20] = [98, 0, 1, 0, 2, 6, 99, 3, 0, 5, 23, 3, 5, 6, 11, 8, 0, 2, 0, 17];
let high: [u8; 20] = [99, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1];

These would be a valid result:

[98, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[99, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

These are not:

[98, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[99, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]

I want to do something like:

use rand::prelude::*;

fn main() {
    let low = [0u8; 20];
    let high = [2u8; 20];
    let value = rand::thread_rng().gen_range(low, high);
    println!("{:?}", value);
}

but I get following error:

error[E0277]: the trait bound `[u8; 20]: rand::distributions::uniform::SampleUniform` is not satisfied
 --> src\main.rs:6:36
  |
6 |     let value = rand::thread_rng().gen_range(low, high);
  |                                    ^^^^^^^^^ the trait `rand::distributions::uniform::SampleUniform` is not implemented for `[u8; 20]`

I tried implementing SampleUniform and UniformSampler without much success. Is there a simple way to implement this?

Body:
If you want to treat the byte arrays as big integers, use the
num-bigint crate with the rand feature enabled:

use bigint::{ToBigInt, RandBigInt};

let low = -10000.to_bigint().unwrap();
let high = 10000.to_bigint().unwrap();
let b = rng.gen_bigint_range(&low, &high);

You could also use unsigned integers instead of signed. There are methods to convert to and from big endian byte arrays:

from_bytes_be

to_bytes_be

See also:

How do I generate a random num::BigUint?


问:
I am unable to resolve the below problem. This is the initial start page for the WebDriver server
This is the initial start page for the WebDriver server observed on IE with different localhost and port number shown on my screen.

I have put my code sample below. Please help me out.

IE version: 11 (32 bit)

Selenium IE Webdriver : 3.141.5.0 (32 bit)

C# language

I tried solutions given in stack overflow by Enabling all protected zones.

```<code>public static void Main(string[] args)
{
    IWebDriver driver = new InternetExplorerDriver();
    string url = @"http://www.google.com";

    driver.Navigate().GoToUrl(url);
    Thread.Sleep(10000);
    Console.WriteLine("Ending");
    driver.Quit();
}
</code>```

It is expected to open google.com. But shows me This is the initial start page for the WebDriver server.

答: The selenium webdriver was not compatible with the browser. It needed re-installation of the webdriver to match browser. It works fine now. </p>

Body:
This is the initial start page for the WebDriver server observed on IE with different localhost and port number shown on my screen.

I have put my code sample below. Please help me out.

IE version: 11 (32 bit)

Selenium IE Webdriver : 3.141.5.0 (32 bit)

C# language

I tried solutions given in stack overflow by Enabling all protected zones.

public static void Main(string[] args)
{
    IWebDriver driver = new InternetExplorerDriver();
    string url = @"http://www.google.com";

    driver.Navigate().GoToUrl(url);
    Thread.Sleep(10000);
    Console.WriteLine("Ending");
    driver.Quit();
}

It is expected to open google.com. But shows me This is the initial start page for the WebDriver server.


问:
Can I have a random block and a sorted page?
I keep running into the same problem, and I feel like I'm solving it the clunky way.  Do you have a better solution?

I have a site that with the content type "Staff Bios".  I've created a view page that lists all the bios in alphabetical order.  I want to have a block that shows just one bio (like a sidebar teaser), and I want the choice of which bio is displayed to be random.

I have been creating 2 separate views, one page with sort = node>title, and one block with sort = random.  But that seems lame.

Thoughts?  Thanks!

答:
No, this is not possible[*] with Drupal 5 / Views 1.

With Drupal 6 / Views 2, you get the option to create multiple View "Displays", each of which can have customized sorting (among other things).

[*] Well, technically, you /could/ do it, by creating a module that implements a new "View Type" that randomizes the rows before displaying them (and select that for the Block, and the normal View Type for the page), but I encourage you to instead put the effort into upgrading your site to Drupal 6.

OwnerDisplayName: Eileen

OwnerDisplayName: smokris

ContentLicense: CC BY-SA 2.5


问:
Use TextOut() in WM_COMMAND
I'm trying to print a text in the WM_COMMAND case, because I need a text to be printed after a button was pushed.

Here's the code I have:

```<code>switch(msg)
{
default:
    return DefWindowProc(hwnd, msg, wParam, lParam);
case WM_COMMAND:
    switch (LOWORD(wParam))
    {
    case 1:
        PAINTSTRUCT ps;
        HDC         hDC;
        hDC = BeginPaint(hwnd, &ps);
        {
            TextOut(hDC, 10, 50, "hello", 5);
        }
        EndPaint(hwnd, &ps);
        UpdateWindow(hwnd);
        break;
    }
    break;
}
</code>```

Sadly it doesn't print anything.

edit:

I can use TextOut() during WM_COMMAND that way:

```<code>HDC         hDC;
hDC = GetDC(hwnd);
TextOut(hDC, 10, ypos, "Warnings: ", 10);
UpdateWindow(hwnd);
</code>```

答:
For painting inside of WM_PAINT: BeginPaint/EndPaint.

For painting outside of WM_PAINT: GetDC/ReleaseDC.

Title: Use TextOut() in WM_COMMAND

Body:
I'm trying to print a text in the WM_COMMAND case, because I need a text to be printed after a button was pushed.

Here's the code I have:

switch(msg)
{
default:
    return DefWindowProc(hwnd, msg, wParam, lParam);
case WM_COMMAND:
    switch (LOWORD(wParam))
    {
    case 1:
        PAINTSTRUCT ps;
        HDC         hDC;
        hDC = BeginPaint(hwnd, &ps);
        {
            TextOut(hDC, 10, 50, "hello", 5);
        }
        EndPaint(hwnd, &ps);
        UpdateWindow(hwnd);
        break;
    }
    break;
}

Sadly it doesn't print anything.

edit:

I can use TextOut() during WM_COMMAND that way:

HDC         hDC;
hDC = GetDC(hwnd);
TextOut(hDC, 10, ypos, "Warnings: ", 10);
UpdateWindow(hwnd);


问:
Ranking data with views
I have two tables that I'm working with.  FILMS and STUDIO.  I'm trying to make a view that sums the profit of films by studio.

Here are my tables:

```<code>**FILMS**
FILM_ID       NUMBER
FILM_NAME     VARCHAR2
FILM_DIRECTOR VARCHAR2

**STUDIO**
STUDIO_ID    NUMBER
STUDIO_NAME  VARCHAR2
PROFIT       NUMBER
</code>```

I have been trying to make a view with the following columns, STUDIO_ID,    STUDIO_NAME, TOTAL_PROFIT.
Where TOTAL_PROFIT holds the sum.

Here is what I have tried:

```<code>SELECT
        STUDIO.STUDIO_ID,
        FILMS.PROFIT
    FROM
        STUDIO,
        FILMS
    WHERE
        STUDIO.STUDIO_ID IS NOT NULL
</code>```

I'm not sure how to store the sum of profit by studio in another new column.

Any help would be appreciated.

答:
what you are trying to do is to join the two columns with cross join,but instead you need to do something like this.

```<code>SELECT
STUDIO.STUDIO_ID,STUDIO_NAME
sum(PROFIT) as TOTAL_PROFIT
FROM
STUDIO
WHERE
STUDIO.STUDIO_ID IS NOT NULL
group by STUDIO.STUDIO_ID,STUDIO_NAME
</code>```

Hope this helps.

Title: Ranking data with views

Body:
I have two tables that I'm working with.  FILMS and STUDIO.  I'm trying to make a view that sums the profit of films by studio.

Here are my tables:

**FILMS**
FILM_ID       NUMBER
FILM_NAME     VARCHAR2
FILM_DIRECTOR VARCHAR2

**STUDIO**
STUDIO_ID    NUMBER
STUDIO_NAME  VARCHAR2
PROFIT       NUMBER

I have been trying to make a view with the following columns, STUDIO_ID,    STUDIO_NAME, TOTAL_PROFIT.
Where TOTAL_PROFIT holds the sum.

Here is what I have tried:

SELECT
        STUDIO.STUDIO_ID,
        FILMS.PROFIT
    FROM
        STUDIO,
        FILMS
    WHERE
        STUDIO.STUDIO_ID IS NOT NULL

I'm not sure how to store the sum of profit by studio in another new column.

Any help would be appreciated.

Body:
what you are trying to do is to join the two columns with cross join,but instead you need to do something like this.

SELECT
STUDIO.STUDIO_ID,STUDIO_NAME
sum(PROFIT) as TOTAL_PROFIT
FROM
STUDIO
WHERE
STUDIO.STUDIO_ID IS NOT NULL
group by STUDIO.STUDIO_ID,STUDIO_NAME

Hope this helps.


问:
pre post condition on javascript?
I have a single timer button which showing start and stop. When I click it, the text changed to stop, and when I click it again then the text changed to start. To maintain the state, then I wrote a code like this:

```<code>start.onclick = function() {
    if (state == 0) {
        state = 1;
        timer();
    }
    if (state == 1) {
        state = 0;
        clearTimeout(t);
    }
}
</code>```

Pre-condition of state is 0. On normal case, it should work if state equals 0, then state will changed to 1 and timer() will be executed. If state equals 1, state will changed to 0 and clearTimeout() will be executed. But I don't know why it won't work like this in javascript. Then I change the code like this:

```<code>start.onclick = function() {
    if (state == 0) {
        timer();
    }
    if (state == 1) {
        state = 0;
        clearTimeout(t);
    }
    state = 1;
}
</code>```

Then it worked, timer() is executed and state changed to 1, but when I tried again to start the button, then nothing worked. I check the state, then the state is in 1. because the second condition is not executed. is anyone know what wrong with this code? what am I missing?

答:
Your code sets the state to 1, if it was 0.

This makes the condition in second if true, hence its code is also executed. Hence both ifs are executed when state is 0.

Use else if like

```<code>start.onclick = function () {
    if (state == 0) {
        state = 1;
        timer();
    } else if (state == 1) { <=== see the difference in this line
        state = 0;
        clearTimeout(t);
    }
}
</code>```

Title: pre post condition on javascript?

Body:
I have a single timer button which showing start and stop. When I click it, the text changed to stop, and when I click it again then the text changed to start. To maintain the state, then I wrote a code like this:

start.onclick = function() {
    if (state == 0) {
        state = 1;
        timer();
    }
    if (state == 1) {
        state = 0;
        clearTimeout(t);
    }
}

Pre-condition of state is 0. On normal case, it should work if state equals 0, then state will changed to 1 and timer() will be executed. If state equals 1, state will changed to 0 and clearTimeout() will be executed. But I don't know why it won't work like this in javascript. Then I change the code like this:

start.onclick = function() {
    if (state == 0) {
        timer();
    }
    if (state == 1) {
        state = 0;
        clearTimeout(t);
    }
    state = 1;
}

Then it worked, timer() is executed and state changed to 1, but when I tried again to start the button, then nothing worked. I check the state, then the state is in 1. because the second condition is not executed. is anyone know what wrong with this code? what am I missing?

Body:
Your code sets the state to 1, if it was 0.

This makes the condition in second if true, hence its code is also executed. Hence both ifs are executed when state is 0.

Use else if like

start.onclick = function () {
    if (state == 0) {
        state = 1;
        timer();
    } else if (state == 1) { <=== see the difference in this line
        state = 0;
        clearTimeout(t);
    }
}


问:
Is it possible to solve this situation with JavaScript/jQuery?
I have a code that checks if radio buttons are checked and if they are it set background color.  It's all working fine, my problem is when I want to select another radio button, result is that all my radio buttons are selected on click but it needs to be just one.

$("input[type='radio']").each(function () {
  if ($(this).is(":checked")) {
  $(this).css("background", "yellow");
   }
 });
 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio">
<input type="radio" checked></code>```

You can test this out. Just try to select another radio button, you will see that radio buttons are selected (2 radio buttons).

What I want to achieve is that when you click on another radio button  it needs to remove this checked class or any other idea. I can't switch between radio buttons.

答:
Give them the same name:

$("input[type='radio']").each(function() {
  if ($(this).is(":checked")) {
    $(this).css("background", "yellow");
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<input type="radio" name="radio">
<input type="radio" name="radio" checked></code>```

Body:
I have a code that checks if radio buttons are checked and if they are it set background color.  It's all working fine, my problem is when I want to select another radio button, result is that all my radio buttons are selected on click but it needs to be just one.

$("input[type='radio']").each(function () {
  if ($(this).is(":checked")) {
  $(this).css("background", "yellow");
   }
 });

<input type="radio">
<input type="radio" checked>

You can test this out. Just try to select another radio button, you will see that radio buttons are selected (2 radio buttons).

What I want to achieve is that when you click on another radio button  it needs to remove this checked class or any other idea. I can't switch between radio buttons.

Body:
Give them the same name:

$("input[type='radio']").each(function() {
  if ($(this).is(":checked")) {
    $(this).css("background", "yellow");
  }
});

<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<input type="radio" name="radio">
<input type="radio" name="radio" checked>


答:
```<code><input type="radio" name="sameName">
<input type="radio" name="sameName">
</code>```

set their name like this way

Title: Is it possible to solve this situation with JavaScript/jQuery?

Body:
<input type="radio" name="sameName">
<input type="radio" name="sameName">

set their name like this way


问:
How do I pass the Post Item ID into getInitialProps?
I'm new to Next.js and having trouble getting a post ID to pass from the index page to the post page getInitialProps() function. The pages are being requested with the Link component.

The end goal is to get the post ID into the post.js getInitialProps function so that the correct json file will be requested like:

https://www.example.com/menu/100.json   <- id = 100

The JSON API endpoints are all working correctly from the browser and the index page is working in nextjs.

So far, I've tried several print statements to look for where this Link href property is being passed, but I've not yet been able to access the "itemid" in the href.

There are 3 main files to reproduce this:

index.js

```<code>
import Layout from '../components/MyLayout.js'
import Link from 'next/link'
import fetch from 'isomorphic-unfetch'

const Index = (props) => (
  <Layout>
    <h1>Pages</h1>
    <ul>
{props.results.map(result => (
        <li key={result.id}>
          <Link as={`/${result.slug}`} href={`/post?itemid=${result.id}`}>
            <a>{result.title}</a>
          </Link>
        </li>
      ))}
    </ul>
  </Layout>
)

Index.getInitialProps = async function() {
  const res = await fetch('https://www.example.com/menu.json')
  const data = await res.json()

  return {
    results: data['data'].map(data => data)
  }
}

export default Index

</code>```

server.js

```<code>
const express = require('express')
const next = require('next')

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app
  .prepare()
  .then(() => {
    const server = express()

    server.get('/:id*', (req, res) => {
      const actualPage = '/post'
      const queryParams = { slug: req.params.id + req.params[0]}
      app.render(req, res, actualPage, queryParams)
    })

    server.get('*', (req, res) => {
      return handle(req, res)
    })

    server.listen(3000, err => {
      if (err) throw err
      console.log('> Ready on http://localhost:3000')
    })
  })
  .catch(ex => {
    console.error(ex.stack)
    process.exit(1)
  })

</code>```

post.js

```<code>
import { withRouter } from 'next/router'
import Layout from '../components/MyLayout.js'
import fetch from 'isomorphic-unfetch'

const Post = props => (
  <Layout>
    <h1>{props.result.title}</h1>
    <p>{props.result.bodyCopy.replace(/<[/]?p>/g, '')}</p>
    <img src={props.result.image} />
  </Layout>
)

Post.getInitialProps = async function(context) {
  const { itemid } = context.query

  const res = await fetch(`https://www.example.com/menu/${itemid}.json`)
  const result = await res.json()

  return { result }
}

export default withRouter(Post)

</code>```

Here's what I'd like to happen:

User requests:  https://www.example.com/some-page
"some-page" has a Post ID of 100

The server gets both "some-page" and "100" on the page being requested/refreshed.

The server makes an API call to: https://www.example.com/menu/100.json

So far, the best result I've got was to get the API url to be:

https://www.example.com/menu/some-page.json

This endpoint is invalid since it is not being requested by the ID.

答:
Please try if this is working as what you have expected?

Index.js

import Layout from '../components/MyLayout.js'
import Link from 'next/link'
import fetch from 'isomorphic-unfetch'

const Index = (props) => (
  <Layout>

Pages

{props.results.map(result => (

          <Link as={`/${result.slug}/${result.id}`} href={`/post?itemid=${result.id}`}>
            {result.title}
          </Link>

      ))}

  </Layout>
)

Index.getInitialProps = async function() {
  const res = await fetch('https://www.example.com/menu.json')
  const data = await res.json()

  return {
    results: data['data'].map(data => data)
  }
}

export default Index```
</div>
</div>
</p>

<p>Server.js
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const express = require('express')
const next = require('next')

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app
  .prepare()
  .then(() => {
    const server = express()

    server.get('/:slug/:id*', (req, res) => {
      const actualPage = '/post'
      const queryParams = { slug: req.params.slug, itemid: req.params.id }
      app.render(req, res, actualPage, queryParams)
    })

    server.get('*', (req, res) => {
      return handle(req, res)
    })

    server.listen(3000, err => {
      if (err) throw err
      console.log('> Ready on http://localhost:3000')
    })
  })
  .catch(ex => {
    console.error(ex.stack)
    process.exit(1)
  })</code>```

Post.js

import { withRouter } from 'next/router'
import Layout from '../components/MyLayout.js'
import fetch from 'isomorphic-unfetch'

const Post = props => (
  <Layout>

{props.result.title}

{props.result.bodyCopy.replace(/<[/]?p>/g, '')}

  </Layout>
)

Post.getInitialProps = async function(context) {
  const { itemid } = context.query

  const res = await fetch(`https://www.example.com/menu/${itemid}.json`)
  const result = await res.json()

  return { result }
}

export default withRouter(Post)```

Body:
I'm new to Next.js and having trouble getting a post ID to pass from the index page to the post page getInitialProps() function. The pages are being requested with the Link component.

The end goal is to get the post ID into the post.js getInitialProps function so that the correct json file will be requested like:

https://www.example.com/menu/100.json   <- id = 100

The JSON API endpoints are all working correctly from the browser and the index page is working in nextjs.

So far, I've tried several print statements to look for where this Link href property is being passed, but I've not yet been able to access the "itemid" in the href.

There are 3 main files to reproduce this:

index.js

import Layout from '../components/MyLayout.js'
import Link from 'next/link'
import fetch from 'isomorphic-unfetch'

const Index = (props) => (
  <Layout>

Pages

{props.results.map(result => (

          <Link as={`/${result.slug}`} href={`/post?itemid=${result.id}`}>
            {result.title}
          </Link>

      ))}

  </Layout>
)

Index.getInitialProps = async function() {
  const res = await fetch('https://www.example.com/menu.json')
  const data = await res.json()

  return {
    results: data['data'].map(data => data)
  }
}

export default Index

server.js

const express = require('express')
const next = require('next')

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app
  .prepare()
  .then(() => {
    const server = express()

    server.get('/:id*', (req, res) => {
      const actualPage = '/post'
      const queryParams = { slug: req.params.id + req.params[0]}
      app.render(req, res, actualPage, queryParams)
    })

    server.get('*', (req, res) => {
      return handle(req, res)
    })

    server.listen(3000, err => {
      if (err) throw err
      console.log('> Ready on http://localhost:3000')
    })
  })
  .catch(ex => {
    console.error(ex.stack)
    process.exit(1)
  })

post.js

import { withRouter } from 'next/router'
import Layout from '../components/MyLayout.js'
import fetch from 'isomorphic-unfetch'

const Post = props => (
  <Layout>

{props.result.title}

{props.result.bodyCopy.replace(/<[/]?p>/g, '')}

  </Layout>
)

Post.getInitialProps = async function(context) {
  const { itemid } = context.query

  const res = await fetch(`https://www.example.com/menu/${itemid}.json`)
  const result = await res.json()

  return { result }
}

export default withRouter(Post)

Here's what I'd like to happen:

User requests:  https://www.example.com/some-page
"some-page" has a Post ID of 100

The server gets both "some-page" and "100" on the page being requested/refreshed.

The server makes an API call to: https://www.example.com/menu/100.json

So far, the best result I've got was to get the API url to be:

https://www.example.com/menu/some-page.json

This endpoint is invalid since it is not being requested by the ID.

Body:
Please try if this is working as what you have expected?

Index.js

import Layout from '../components/MyLayout.js'
import Link from 'next/link'
import fetch from 'isomorphic-unfetch'

const Index = (props) => (
  <Layout>
    <h1>Pages</h1>
    <ul>
{props.results.map(result => (
        <li key={result.id}>
          <Link as={`/${result.slug}/${result.id}`} href={`/post?itemid=${result.id}`}>
            <a>{result.title}</a>
          </Link>
        </li>
      ))}
    </ul>
  </Layout>
)

Index.getInitialProps = async function() {
  const res = await fetch('https://www.example.com/menu.json')
  const data = await res.json()

  return {
    results: data['data'].map(data => data)
  }
}

export default Index

Server.js

const express = require('express')
const next = require('next')

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app
  .prepare()
  .then(() => {
    const server = express()

    server.get('/:slug/:id*', (req, res) => {
      const actualPage = '/post'
      const queryParams = { slug: req.params.slug, itemid: req.params.id }
      app.render(req, res, actualPage, queryParams)
    })

    server.get('*', (req, res) => {
      return handle(req, res)
    })

    server.listen(3000, err => {
      if (err) throw err
      console.log('> Ready on http://localhost:3000')
    })
  })
  .catch(ex => {
    console.error(ex.stack)
    process.exit(1)
  })

Post.js

import { withRouter } from 'next/router'
import Layout from '../components/MyLayout.js'
import fetch from 'isomorphic-unfetch'

const Post = props => (
  <Layout>
    <h1>{props.result.title}</h1>
    <p>{props.result.bodyCopy.replace(/<[/]?p>/g, '')}</p>
    <img src={props.result.image} />
  </Layout>
)

Post.getInitialProps = async function(context) {
  const { itemid } = context.query

  const res = await fetch(`https://www.example.com/menu/${itemid}.json`)
  const result = await res.json()

  return { result }
}

export default withRouter(Post)


问:
C# Winforms handle unhandled exceptions
I want to catch all unhandled exceptions in my application. so I used this code to catch all the unhandled exceptions:

```<code>static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

    static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
    {
        SaveEx(e.Exception);
        Application.Exit();
    }

    static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        SaveEx((Exception)e.ExceptionObject);
        Application.Exit();
    }

    static void SaveEx(Exception ex)
    {
        bool exists = System.IO.Directory.Exists(Path.GetDirectoryName(@"C:\AppLogs\"));

        if (!exists)
            System.IO.Directory.CreateDirectory(Path.GetDirectoryName(@"C:\AppLogs\"));

        String filePath = @"C:\AppLogs\" + DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss") + ".txt";

        String log = "===========Start=============\r\n";

        log += "Error Message: " + ex.Message + "\r\n";
        log += "Stack Trace: " + ex.StackTrace + "\r\n";

        log += "===========End=============";

        System.IO.File.WriteAllText(filePath, log);
    }
}
</code>```

I tried to raise these exceptions with a divide in 0:

on main thread it's work perfect:

```<code>int t = 0;
int r = 5 / t;
</code>```

But when i try to do it inside a Thread:

```<code> Thread thread = new Thread(delegate()
 {
      int t = 0;
      int r = 5 / t;
 });
 thread.Start();
</code>```

The CurrentDomain_UnhandledException function got called but it keeps calling the int r = 5 / t; row in my code so I have a loop of exceptions. Any idea what can be the problem? the thread is called only once.

答:
You need to change Application UnhandledExceptionMode
 to UnhandledExceptionMode.CatchException to make things works correctly. Microsoft already wrote a very good article about it here.

I tried to simulate your work. Everything worked well, take a look on my example.

```<code>    [STAThread]
    static void Main()
    {
        // Set the unhandled exception mode to force all Windows Forms errors to go through
        // our handler.
        Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

        // Add the event handler for handling UI thread exceptions to the event.
        Application.ThreadException += Application_ThreadException;

        // Add the event handler for handling non-UI thread exceptions to the event.
        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

    private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
    {
        MessageBox.Show(e.Exception.Message, "Application_ThreadException");
        Application.Exit();
    }

    private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        var exception = e.ExceptionObject as Exception;
        MessageBox.Show(exception.Message, "CurrentDomain_UnhandledException");
        Application.Exit();
    }
</code>```

So, if we raise an exception inside a thread like below:

```<code>    private void button1_Click(object sender, EventArgs e)
    {
        var thread = new Thread(delegate () {
            throw new DivideByZeroException();
        });

        thread.Start();
    }
</code>```

button1_Click is fired.

thread get started and raises a DividedByZeroException.

CurrentDomain_UnhandledException catches the exception, shows the message and closes the app

Title: C# Winforms handle unhandled exceptions

Body:
I want to catch all unhandled exceptions in my application. so I used this code to catch all the unhandled exceptions:

static class Program
{
    ///
    /// The main entry point for the application.
    ///
    [STAThread]
    static void Main()
    {
        Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

    static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
    {
        SaveEx(e.Exception);
        Application.Exit();
    }

    static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        SaveEx((Exception)e.ExceptionObject);
        Application.Exit();
    }

    static void SaveEx(Exception ex)
    {
        bool exists = System.IO.Directory.Exists(Path.GetDirectoryName(@"C:\AppLogs\"));

        if (!exists)
            System.IO.Directory.CreateDirectory(Path.GetDirectoryName(@"C:\AppLogs\"));

        String filePath = @"C:\AppLogs\" + DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss") + ".txt";

        String log = "===========Start=============\r\n";

        log += "Error Message: " + ex.Message + "\r\n";
        log += "Stack Trace: " + ex.StackTrace + "\r\n";

        log += "===========End=============";

        System.IO.File.WriteAllText(filePath, log);
    }
}

I tried to raise these exceptions with a divide in 0:

on main thread it's work perfect:

int t = 0;
int r = 5 / t;

But when i try to do it inside a Thread:

 Thread thread = new Thread(delegate()
 {
      int t = 0;
      int r = 5 / t;
 });
 thread.Start();

The CurrentDomain_UnhandledException function got called but it keeps calling the int r = 5 / t; row in my code so I have a loop of exceptions. Any idea what can be the problem? the thread is called only once.

Body:
You need to change Application UnhandledExceptionMode
 to UnhandledExceptionMode.CatchException to make things works correctly. Microsoft already wrote a very good article about it here.

I tried to simulate your work. Everything worked well, take a look on my example.

    [STAThread]
    static void Main()
    {
        // Set the unhandled exception mode to force all Windows Forms errors to go through
        // our handler.
        Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

        // Add the event handler for handling UI thread exceptions to the event.
        Application.ThreadException += Application_ThreadException;

        // Add the event handler for handling non-UI thread exceptions to the event.
        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

    private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
    {
        MessageBox.Show(e.Exception.Message, "Application_ThreadException");
        Application.Exit();
    }

    private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        var exception = e.ExceptionObject as Exception;
        MessageBox.Show(exception.Message, "CurrentDomain_UnhandledException");
        Application.Exit();
    }

So, if we raise an exception inside a thread like below:

    private void button1_Click(object sender, EventArgs e)
    {
        var thread = new Thread(delegate () {
            throw new DivideByZeroException();
        });

        thread.Start();
    }

button1_Click is fired.

thread get started and raises a DividedByZeroException.

CurrentDomain_UnhandledException catches the exception, shows the message and closes the app


问:
Load balancing application servers running in multiple docker containers
What i am doing : I am running jruby sinatra server in four different docker containers. And I did setup apache2 load balancer configuration in another docker container using ubuntu docker image.

Given below are the snapshots of docker containers, and httpd.conf configuration :

When i am hitting the url : 127.0.0.1:9292
It is showing home page of apache.

and on hitting url : 127.0.0.1:9292/load-manager . It's showing that requested url is not found.

Does anyone have any idea, what am i doing wrong or if i am missing something?

答:
I found solution for this.
I wasn't exposing the port which need to be accessed in other container(load balancer).

So, to communicate between the containers we need to expose ports. And Inside load balancer container we can either load balance nodes by their

IP_ADDRESS:PORT or CONTAINER_NAME:PORT


问:
Code with ?, Compile in Objective-C
So I'm jumping into iPhone development and I've begun looking into Objective-C and have noticed that... it sucks. Ultimately, there's all kinds of odd syntax requirements, ex:

```<code>NSString *city = @"Victoria";
</code>```

or

```<code>[MyClass myMethod]
</code>```

This is alien. The language should be smart enough to know what do do with a normal variable and string.

But, this is the language, and I can't do anything about it. So, my main question is: Is there any way to write my code in PHP/AS3/C# or some other normal language and then compile or convert it to legal Objective-C? I was going to use AS3 but necessary functionality like the Camera is not currently supported.

I know it's an odd question, but what about when I need to develop for Android or Windows 7? There are only so many languages one can learn before one loses his/her mind. I'd like to stop at 7.

答:
I'd better write a real answer instead of expressing my thoughts piecemeal in comments.

I think you should stick with it because for somebody coming from the world of Java or .Net or C++ things do look a bit strange at first.  However, once you understand the paradigm, you realise that, in  OO terms, Java, C++ and .Net are only half way there.  The Objective-C model turns out to be extraordinarily powerful for such a small language.

In real OO as per the Smalltalk model, you do not call methods on objects,you send messages to them and they decide what to do.  C++ style language only provide a limited form of this through inheritance.  Objective-C goes the whole way.  This is why, incidentally, the syntax for "calling" methods on Objective-C objects is different to normal function calls, it's because it is not a function call.

As for the syntax, well the example you gave is the way it is because a C style string is a completely different thing to a NSString.  The first is just a pointer and a sequence of bytes terminated with a null byte, the second is a proper string object.  The compiler has to have a way of differentiating the two without breaking C compatibility.

As for the message passing syntax, well it seems strange at first, but once you get used to the interleaved parameters, the advantages become plain.  Objective-C methods are much more self documenting than those of traditional C like languages.

There are only two major areas in which Objective-C falls short (in my opinion) and they are the lack of namespace support and (on iOS) the lack of proper garbage collection.

Title: Code with ?, Compile in Objective-C

Body:
So I'm jumping into iPhone development and I've begun looking into Objective-C and have noticed that... it sucks. Ultimately, there's all kinds of odd syntax requirements, ex:

NSString *city = @"Victoria";

or

[MyClass myMethod]

This is alien. The language should be smart enough to know what do do with a normal variable and string.

But, this is the language, and I can't do anything about it. So, my main question is: Is there any way to write my code in PHP/AS3/C# or some other normal language and then compile or convert it to legal Objective-C? I was going to use AS3 but necessary functionality like the Camera is not currently supported.

I know it's an odd question, but what about when I need to develop for Android or Windows 7? There are only so many languages one can learn before one loses his/her mind. I'd like to stop at 7.


问:
Is there a way to update set of rows in Postgres against a UUID array?
I am having a problem in sending my array of UUID in an update Query.

My UUID array looks like this:

```<code>[
    "c5cahude-8245-49ed-b2d2-niufu",
    "b272jiopeb-486c-495f-91a4-zokxp",
    "kodeidji-1487-4d02-a958-901i9"
]
</code>```

I have tried to use .join() and .toString() but it did not work. My last option was to create something by sending it through a map function. I am not satisfied with this piece of code.

My current code looks something like this right now.

```<code>const params: string = _.map(ids, (s, i) => `$${i + offset}`).join(',');
const query = `update some_table set deleted = NOW(), fk_updated_by = $${ids.length + 1} where id IN(${params})`;
</code>```

The output is correct but i want to implement something much more simpler.

Thanks in advance!

答:
Prepared statements work with arrays, so I'm assuming they will work with array of UUID just fine.

node-postgres supports mapping simple JavaScript arrays to PostgreSQL
  arrays, so in most cases you can just pass it like any other
  parameter.

```<code>client.query("SELECT * FROM stooges WHERE name = ANY ($1)", [ ['larry', 'curly', 'moe'] ], ...);
</code>```

https://github.com/brianc/node-postgres/wiki/FAQ#11-how-do-i-build-a-where-foo-in--query-to-find-rows-matching-an-array-of-values

https://node-postgres.com/features/queries#prepared-statements

Body:
I am having a problem in sending my array of UUID in an update Query.

My UUID array looks like this:

[
    "c5cahude-8245-49ed-b2d2-niufu",
    "b272jiopeb-486c-495f-91a4-zokxp",
    "kodeidji-1487-4d02-a958-901i9"
]

I have tried to use .join() and .toString() but it did not work. My last option was to create something by sending it through a map function. I am not satisfied with this piece of code.

My current code looks something like this right now.

const params: string = _.map(ids, (s, i) => `$${i + offset}`).join(',');
const query = `update some_table set deleted = NOW(), fk_updated_by = $${ids.length + 1} where id IN(${params})`;

The output is correct but i want to implement something much more simpler.

Thanks in advance!

Body:
Prepared statements work with arrays, so I'm assuming they will work with array of UUID just fine.

node-postgres supports mapping simple JavaScript arrays to PostgreSQL
  arrays, so in most cases you can just pass it like any other
  parameter.

client.query("SELECT * FROM stooges WHERE name = ANY ($1)", [ ['larry', 'curly', 'moe'] ], ...);

https://github.com/brianc/node-postgres/wiki/FAQ#11-how-do-i-build-a-where-foo-in--query-to-find-rows-matching-an-array-of-values

https://node-postgres.com/features/queries#prepared-statements