问:
IE7: background-img on multipleline text
On a anchor-tag with a url to a external site we have a little icon that indicates that this is a link to a external site. Now this Icon is included via a additional span-element around the link-text and displayed via CSS background-image with position 100% 50% to always be at the end of the text and a padding-right for the text-gap between link and the following text

now this works fine in every browser — as long as the link-text is not longer than 1 line … if it is on multiple lines, the whole thing works still fine everywhere, except IE7 (IE6 is not supported by the project)… IE7 displays the Icon at the end of the first line and a few pixels to the bottom, instead of at the end of the link-/span-text on the second or third line…

Sometimes a picture says more than 1000 words: http://img859.imageshack.us/i/spdexternalerror.jpg/

HTML-Code: Link-Text to multiple lines

CSS to the span-element: {background: url(/#/icon-new-window.png) no-repeat center right; padding-right: 14px;}

答:
Multi-line background is a problem for IE7. The correct way to do what you want, without adding extra markup, is to use CSS :after however :after is not supported natively in IE6 or 7 (support was added in IE8). If you don't mind using JavaScript to add :after support to IE7 then you could use the ie7-js library (also see this question :after and :before css pseudo elements hack for IE 7)

Using that library, the following is working for me in IE7.

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Title</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <style type="text/css">
        p {
            width:100px;
            border:1px dashed blue;
        }

        a.external:after {
          content:url(http://www.knowledgewand.com/images/icon_new_window.gif);
        }
    </style>
    <!--[if lt IE 9]>
        <script src="http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE9.js"></script>
    <![endif]-->
</head>
<body>
    <p>
        <a href="#" class="external">Link-Text to multiple lines</a>
    </p>
</body>
</html>
</code>```

Body:
Multi-line background is a problem for IE7. The correct way to do what you want, without adding extra markup, is to use CSS :after however :after is not supported natively in IE6 or 7 (support was added in IE8). If you don't mind using JavaScript to add :after support to IE7 then you could use the ie7-js library (also see this question :after and :before css pseudo elements hack for IE 7)

Using that library, the following is working for me in IE7.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Title</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <style type="text/css">
        p {
            width:100px;
            border:1px dashed blue;
        }

        a.external:after {
          content:url(http://www.knowledgewand.com/images/icon_new_window.gif);
        }
    </style>
    <!--[if lt IE 9]>
        <script src="http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE9.js"></script>
    <![endif]-->
</head>
<body>
    <p>
        <a href="#" class="external">Link-Text to multiple lines</a>
    </p>
</body>
</html>


来源: stackexchange

问:
How can i display a particular product?
I am trying to display a particular product by clicking on it from the list

```<code><ul>
    <% products.each do |product| %>
    <tr>

        <a href="<%= products_path(@product) %>"><%= product.title %> .   </a>
        <br/>

    </tr>
    <% end %>
</ul>
</code>```

Expected results should be products/1 but the result is products.1 and should displays a list of products

答: products_path(@product) should be products_path(product)

ContentLicense: CC BY-SA 4.0

Title: How can i display a particular product?

Body:
I am trying to display a particular product by clicking on it from the list

    <% products.each do |product| %>

        <a href="<%= products_path(@product) %>"><%= product.title %> .

    <% end %>

Expected results should be products/1 but the result is products.1 and should displays a list of products


问:
What is causing inefficiency when parsing this QuerySet into tuples?
In a django app, I am attempting to parse a Queryset, representing individual time-series values x from n sensors, into tuples (t, x1, x2 ... xn), and thence into a json object in the format specified by google charts here: https://developers.google.com/chart/interactive/docs/gallery/linechart

None values are used as placeholders if no value was logged for a given timestamp from a particular sensor

The page load time is significant for a QuerySet with ~6500 rows (~3 seconds, run locally)

It's significantly longer on the server

http://54.162.202.222/pulogger/simpleview/?device=test

Profiling indicates that 99.9% of the time is spent on _winapi.WaitForSingleObject, (which I can't interpret) and manual profiling with a timer indicates that the server-side culprit is the while loop that iterates over the QuerySet and groups the values into tuples (line 23 in my code example)

Results are as-follows:

basic gets (took 5ms)

queried data (took 0ms)

split data by sensor (took 981ms)

prepared column labels/types (took 0ms)

prepared json (took 27ms)

created context (took 0ms)

For the sake of completeness, the timing function is as follows:

```<code>def print_elapsed_time(ref_datetime, description):
    print('{} (took {}ms)'.format(description, floor((datetime.now()-ref_datetime).microseconds/1000)))
    return datetime.now()
</code>```

The code performing the processing and generating the view is as-follows:

```<code>def simpleview(request):
    time_marker = datetime.now()
    device_name = request.GET['device']
    device = Datalogger.objects.get(device_name=device_name)

    sensors = Sensor.objects.filter(datalogger=device).order_by('pk')
    sensor_count = len(sensors)  # should be no worse than count() since already-evaluated and cached.  todo: confirm

    #assign each sensor an index for the tuples (zero is used for time/x-axis)
    sensor_indices = {}
    for idx, sensor in enumerate(sensors, start=1):
        sensor_indices.update({sensor.sensor_name:idx})

    time_marker = print_elapsed_time(time_marker, 'basic gets')

    # process data into timestamp-grouped tuples accessible by sensor-index ([0] is timestamp)
    raw_data = SensorDatum.objects.filter(sensor__datalogger__device_name=device_name).order_by('timestamp', 'sensor')
    data = []
    data_idx = 0

    time_marker = print_elapsed_time(time_marker, 'queried data')

    while data_idx < len(raw_data):
        row_list = [raw_data[data_idx].timestamp]
        row_list.extend([None]*sensor_count)
        row_idx = 1

        while data_idx < len(raw_data) and raw_data[data_idx].timestamp == row_list[0]:
            row_idx = sensor_indices.get(raw_data[data_idx].sensor.sensor_name)
            row_list[row_idx] = raw_data[data_idx].value
            data_idx += 1
        data.append(tuple(row_list))

    time_marker = print_elapsed_time(time_marker, 'split data by sensor')

    column_labels = ['Time']
    column_types = ["datetime"]
    for sensor in sensors:
        column_labels.append(sensor.sensor_name)
        column_types.append("number")

    time_marker = print_elapsed_time(time_marker, 'prepared column labels/types')

    gchart_json = prepare_data_for_gchart(column_labels, column_types, data)

    time_marker = print_elapsed_time(time_marker, 'prepared json')

    context = {
        'device': device_name,
        'sensor_count': sensor_count,
        'sensor_indices': sensor_indices,
        'gchart_json': gchart_json,
    }

    time_marker = print_elapsed_time(time_marker, 'created context')

    return render(request, 'pulogger/simpleTimeSeriesView.html', context)
</code>```

I'm new to python, so I expect that there's a poor choice of operation/collection I've used somewhere.  Unless I'm blind, it should run in O(n).

Obviously this isn't the whole problem since it only accounts for a part of the apparent load-time, but I figure this is a good place to start.

答:
You have queries running under a loop. You can use select_related to cache related objects beforehand.

Example:

```<code>raw_data = SensorDatum.objects.filter(
    sensor__datalogger__device_name=device_name
).order_by(
    'timestamp',
    'sensor'
).select_related('sensor') # this will fetch and cache sensor objects and will prevent further db queries in the loop
</code>```

Ref: select_related Django 2.1 Docs

Body:
In a django app, I am attempting to parse a Queryset, representing individual time-series values x from n sensors, into tuples (t, x1, x2 ... xn), and thence into a json object in the format specified by google charts here: https://developers.google.com/chart/interactive/docs/gallery/linechart

None values are used as placeholders if no value was logged for a given timestamp from a particular sensor

The page load time is significant for a QuerySet with ~6500 rows (~3 seconds, run locally)

It's significantly longer on the server

http://54.162.202.222/pulogger/simpleview/?device=test

Profiling indicates that 99.9% of the time is spent on _winapi.WaitForSingleObject, (which I can't interpret) and manual profiling with a timer indicates that the server-side culprit is the while loop that iterates over the QuerySet and groups the values into tuples (line 23 in my code example)

Results are as-follows:

basic gets (took 5ms)

queried data (took 0ms)

split data by sensor (took 981ms)

prepared column labels/types (took 0ms)

prepared json (took 27ms)

created context (took 0ms)

For the sake of completeness, the timing function is as follows:

def print_elapsed_time(ref_datetime, description):
    print('{} (took {}ms)'.format(description, floor((datetime.now()-ref_datetime).microseconds/1000)))
    return datetime.now()

The code performing the processing and generating the view is as-follows:

def simpleview(request):
    time_marker = datetime.now()
    device_name = request.GET['device']
    device = Datalogger.objects.get(device_name=device_name)

    sensors = Sensor.objects.filter(datalogger=device).order_by('pk')
    sensor_count = len(sensors)  # should be no worse than count() since already-evaluated and cached.  todo: confirm

    #assign each sensor an index for the tuples (zero is used for time/x-axis)
    sensor_indices = {}
    for idx, sensor in enumerate(sensors, start=1):
        sensor_indices.update({sensor.sensor_name:idx})

    time_marker = print_elapsed_time(time_marker, 'basic gets')

    # process data into timestamp-grouped tuples accessible by sensor-index ([0] is timestamp)
    raw_data = SensorDatum.objects.filter(sensor__datalogger__device_name=device_name).order_by('timestamp', 'sensor')
    data = []
    data_idx = 0

    time_marker = print_elapsed_time(time_marker, 'queried data')

    while data_idx < len(raw_data):
        row_list = [raw_data[data_idx].timestamp]
        row_list.extend([None]*sensor_count)
        row_idx = 1

        while data_idx < len(raw_data) and raw_data[data_idx].timestamp == row_list[0]:
            row_idx = sensor_indices.get(raw_data[data_idx].sensor.sensor_name)
            row_list[row_idx] = raw_data[data_idx].value
            data_idx += 1
        data.append(tuple(row_list))

    time_marker = print_elapsed_time(time_marker, 'split data by sensor')

    column_labels = ['Time']
    column_types = ["datetime"]
    for sensor in sensors:
        column_labels.append(sensor.sensor_name)
        column_types.append("number")

    time_marker = print_elapsed_time(time_marker, 'prepared column labels/types')

    gchart_json = prepare_data_for_gchart(column_labels, column_types, data)

    time_marker = print_elapsed_time(time_marker, 'prepared json')

    context = {
        'device': device_name,
        'sensor_count': sensor_count,
        'sensor_indices': sensor_indices,
        'gchart_json': gchart_json,
    }

    time_marker = print_elapsed_time(time_marker, 'created context')

    return render(request, 'pulogger/simpleTimeSeriesView.html', context)

I'm new to python, so I expect that there's a poor choice of operation/collection I've used somewhere.  Unless I'm blind, it should run in O(n).

Obviously this isn't the whole problem since it only accounts for a part of the apparent load-time, but I figure this is a good place to start.

Body:
You have queries running under a loop. You can use select_related to cache related objects beforehand.

Example:

raw_data = SensorDatum.objects.filter(
    sensor__datalogger__device_name=device_name
).order_by(
    'timestamp',
    'sensor'
).select_related('sensor') # this will fetch and cache sensor objects and will prevent further db queries in the loop

Ref: select_related Django 2.1 Docs


问:
How to Highlight the `Selected row` in a `Listview` using Fragments
I created a listview that is acting as a menu. When the user chooses a specific menu, another fragment will show up on the right portion.

Please see this image:

The problem is, the icon and the title are only highlighted and not the whole selected row. How can I highlight the selected row instead of the icon and title only?

This is my code:

fragment_inventory_list.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".InventoryListFragment"
    android:layout_marginTop="@dimen/padding_50"
    android:orientation="vertical"
    android:background="?android:attr/activatedBackgroundIndicator">

   <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:orientation="vertical">

       <ListView
           android:id="@+id/inventorylist_listview"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:choiceMode="singleChoice"
           android:listSelector="@color/light_gray"/>

   </LinearLayout>

</LinearLayout>
</code>```

InventoryListFragment.java

```<code>package com.example.devcash;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.devcash.CustomAdapters.InventoryListAdapter;
import com.example.devcash.Fragments.CategoriesFragment;
import com.example.devcash.Fragments.DiscountsFragment;
import com.example.devcash.Fragments.ProductsFragment;
import com.example.devcash.Fragments.ServicesFragment;
import com.example.devcash.Lists.InventoryList;

import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 */
public class InventoryListFragment extends Fragment implements AdapterView.OnItemClickListener {

    ListView lvinventory;
    ArrayList<InventoryList> list = new ArrayList<InventoryList>();
    InventoryListAdapter adapter;

    public InventoryListFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_inventory_list, container, false);

        lvinventory = (ListView) view.findViewById(R.id.inventorylist_listview);
        adapter = new InventoryListAdapter(getActivity(),list);

        list.add(new InventoryList(R.drawable.ic_product,"Products"));
        list.add(new InventoryList(R.drawable.ic_services,"Services"));
        list.add(new InventoryList(R.drawable.ic_category, "Categories"));
        list.add(new InventoryList(R.drawable.ic_local_offer,"Discounts"));

        lvinventory.setAdapter(adapter);
        lvinventory.setOnItemClickListener(this);

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        InventoryList selectedList = this.list.get(position);

        int icon = selectedList.getIcon();
        String title = selectedList.getInventory_title();

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        switch (position){
            case 0:
                ProductsFragment productsFragment = new ProductsFragment();
                fragmentTransaction.add(R.id.inventorylist_fragmentcontainer, productsFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
            case 1:
                ServicesFragment servicesFragment = new ServicesFragment();
                fragmentTransaction.add(R.id.inventorylist_fragmentcontainer, servicesFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
            case  2:
                CategoriesFragment categoriesFragment = new CategoriesFragment();
                fragmentTransaction.add(R.id.inventorylist_fragmentcontainer, categoriesFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
            case 3:
                DiscountsFragment discountsFragment = new DiscountsFragment();
                fragmentTransaction.add(R.id.inventorylist_fragmentcontainer, discountsFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
        }
    }
}
</code>```

答:
Try this</p>

```<code>private class InventoryListAdapter extends ... {
    private int focusedPosition = -1; // -1 means nothing is selected
    ....
    ....

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);
        if (position == focusedPosition) {
            view.setBackgroundColor(/* your selected color */);
        } else {
            view.setBackgroundColor(/* your NOT selected color */);
        }

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               focusedPosition = position;
               notifyDataSetChanged();
            }
        });

        return view;
    }
</code>```

Body:
I created a listview that is acting as a menu. When the user chooses a specific menu, another fragment will show up on the right portion.

Please see this image:

The problem is, the icon and the title are only highlighted and not the whole selected row. How can I highlight the selected row instead of the icon and title only?

This is my code:

fragment_inventory_list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".InventoryListFragment"
    android:layout_marginTop="@dimen/padding_50"
    android:orientation="vertical"
    android:background="?android:attr/activatedBackgroundIndicator">

   <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:orientation="vertical">

       <ListView
           android:id="@+id/inventorylist_listview"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:choiceMode="singleChoice"
           android:listSelector="@color/light_gray"/>

   </LinearLayout>

</LinearLayout>

InventoryListFragment.java

package com.example.devcash;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.devcash.CustomAdapters.InventoryListAdapter;
import com.example.devcash.Fragments.CategoriesFragment;
import com.example.devcash.Fragments.DiscountsFragment;
import com.example.devcash.Fragments.ProductsFragment;
import com.example.devcash.Fragments.ServicesFragment;
import com.example.devcash.Lists.InventoryList;

import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 */
public class InventoryListFragment extends Fragment implements AdapterView.OnItemClickListener {

    ListView lvinventory;
    ArrayList<InventoryList> list = new ArrayList<InventoryList>();
    InventoryListAdapter adapter;

    public InventoryListFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_inventory_list, container, false);

        lvinventory = (ListView) view.findViewById(R.id.inventorylist_listview);
        adapter = new InventoryListAdapter(getActivity(),list);

        list.add(new InventoryList(R.drawable.ic_product,"Products"));
        list.add(new InventoryList(R.drawable.ic_services,"Services"));
        list.add(new InventoryList(R.drawable.ic_category, "Categories"));
        list.add(new InventoryList(R.drawable.ic_local_offer,"Discounts"));

        lvinventory.setAdapter(adapter);
        lvinventory.setOnItemClickListener(this);

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        InventoryList selectedList = this.list.get(position);

        int icon = selectedList.getIcon();
        String title = selectedList.getInventory_title();

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        switch (position){
            case 0:
                ProductsFragment productsFragment = new ProductsFragment();
                fragmentTransaction.add(R.id.inventorylist_fragmentcontainer, productsFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
            case 1:
                ServicesFragment servicesFragment = new ServicesFragment();
                fragmentTransaction.add(R.id.inventorylist_fragmentcontainer, servicesFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
            case  2:
                CategoriesFragment categoriesFragment = new CategoriesFragment();
                fragmentTransaction.add(R.id.inventorylist_fragmentcontainer, categoriesFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
            case 3:
                DiscountsFragment discountsFragment = new DiscountsFragment();
                fragmentTransaction.add(R.id.inventorylist_fragmentcontainer, discountsFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                break;
        }
    }
}

Body:
Try this

private class InventoryListAdapter extends ... {
    private int focusedPosition = -1; // -1 means nothing is selected
    ....
    ....

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);
        if (position == focusedPosition) {
            view.setBackgroundColor(/* your selected color */);
        } else {
            view.setBackgroundColor(/* your NOT selected color */);
        }

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               focusedPosition = position;
               notifyDataSetChanged();
            }
        });

        return view;
    }


问:
How to get the version of ionic framework?
I wonder how to check the version of ionic. If I do ionic -v I get back 1.4.3

Can that be? Wasn't 1.0.0 just released?

答:
```<code>$ ionic -v
</code>```

CLI 4.12.0

you will be able to know your framework version

```<code>$ ionic info
</code>```

all details

ContentLicense: CC BY-SA 3.0

Body:
$ ionic -v

CLI 4.12.0

you will be able to know your framework version

$ ionic info

all details


问:
How to change css styles using jQuery with values from <input> elements
I'm making a program where user can select an element to render and also select CSS styles to add to the element.

The program successfully renders un-altered elements. The difficulty is changing the styles. So far i'm only changning Width and Height.
! I won't use .width()/.height() methods because I want to include units and change others CSS properties.

I get this error: Uncaught TypeError: latestElement.css is not a function

This tells me that .css() doesn't seem to work with jQuery prototype.

```<code> HTML:
```

 Please select type of container to add
<select id= "container">
 <option value= "div" > &ltdiv&gt </option>
 <option value= "p"> &ltp&gt </option>
 <option value= "section"> &ltsection&gt </option>

</select>

<button id="btn" > Create Container </button>

```
</code>```

To avoid assigning a new id attribute to every knew element I select them using the list of each element (i.e $('element')[i]). I store that reference in a variable but it breaks .css().

```<code>      <script
      src="https://code.jquery.com/jquery-3.4.1.min.js"
      integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
      crossorigin="anonymous"></script>

    <script>
    $(document).ready( function(){

         // event-handler to create new element
        function createContainer() {

        // variables store values from <select> element
        var selector = $('select');
        var elementType = $('select').val();

        // string containing markup for use with .append()
        var elementTypeStr = "<" + elementType + "> This is a " + elementType +
                              "</" + elementType + ">" ;

            $('#layout_demo').append( elementTypeStr );
            // create jQuery prototype for prototype.css()
             i = $( elementType ).length;
               latestElement = $(elementType)[i - 1];
            latestElement.css( "width", function(){
                return width + widthUnit ;
            });

        } // end createContainer()

        // ---------------------------- event handlers ---------------------

        $('#btn').click( createContainer );
        // button to delete latest element or selected element

    }); // end ready

  </script>

</code>```

答:
No need to fetch last item, do like this :-</p>

```<code>$(document).ready( function(){

  function createContainer() {
    var selector = $('select');
    var el = $('select').val();
    var elementType = $(`<${el}> This is ${el} </${el}>`) ;
    $('#layout_demo').append( elementType );
    elementType.css( "border", '1px solid red');
  }
  $('#btn').click( createContainer );

});
</code>```

Body:
I'm making a program where user can select an element to render and also select CSS styles to add to the element.

The program successfully renders un-altered elements. The difficulty is changing the styles. So far i'm only changning Width and Height.
! I won't use .width()/.height() methods because I want to include units and change others CSS properties.

I get this error: Uncaught TypeError: latestElement.css is not a function

This tells me that .css() doesn't seem to work with jQuery prototype.

 HTML:
```
<section id="form">
<!-- select element --->
<label for="container"> Please select type of container to add</label>
<select id= "container">
 <option value= "div" > &ltdiv&gt </option>
 <option value= "p"> &ltp&gt </option>
 <option value= "section"> &ltsection&gt </option>

</select>

<button id="btn" > Create Container </button>
</section>

<!-- Seperate container to hold now elements -->

<div id="layout_demo">

</div>

```

To avoid assigning a new id attribute to every knew element I select them using the list of each element (i.e $('element')[i]). I store that reference in a variable but it breaks .css().

Body:
No need to fetch last item, do like this :-

$(document).ready( function(){

  function createContainer() {
    var selector = $('select');
    var el = $('select').val();
    var elementType = $(`<${el}> This is ${el} </${el}>`) ;
    $('#layout_demo').append( elementType );
    elementType.css( "border", '1px solid red');
  }
  $('#btn').click( createContainer );

});


问:
Hibernate One-to-Many not returning full result set
I have a hibernate entity (paygrade) with multiple children (paysteps) and am trying to query these children in the app.  Unfortunately, I'm only able to retrieve the first record of the query.  Here are the entities

```<code>public class Paygrade extends Persistent {

    @Id
    @Column(length = 80, updatable=false)
    private String code;

    @Column(length = 80, updatable=false)
    private String name;

    @OneToMany(mappedBy = "paygrade", fetch = FetchType.LAZY)
    @ForeignKey(name = "none")
    private Set<Paystep> paygradeSteps = new HashSet<Paystep>();

    // getters and setters
}

@IdClass(PaystepPK.class)
public class Paystep {

    @Id
    @Column(length = 80, updatable=false)
    protected String gradeCode;

    @Column(length = 80, updatable=false)
    protected String gradeName;

    @Id
    @Column(length = 80, updatable=false)
    protected String scaleCode;

    @Column(length = 80, updatable=false)
    protected String scaleName;

    @Column(length = 80, updatable=false)
    protected String scalePoint;

    @Column(updatable=false)
    protected Long scaleValue;

    @ManyToOne
    @ForeignKey(name = "none")
    @JoinColumn (name="grade_code", updatable = false, insertable = false)
    private Paygrade paygrade;

    // getters and setters

}
</code>```

The below query is called by hibernate when calling the getPaygradeSteps() method of a paygrade instance:

```<code>Hibernate:
/* load one-to-many ...Paygrade.paygradeSteps */ select
    paygradest0_.grade_code as grade1_38_1_,
    paygradest0_.grade_code as grade1_1_,
    paygradest0_.scale_code as scale2_1_,
    paygradest0_.grade_code as grade1_39_0_,
    paygradest0_.scale_code as scale2_39_0_,
    paygradest0_.grade_name as grade3_39_0_,
    paygradest0_.scale_name as scale4_39_0_,
    paygradest0_.scale_point as scale5_39_0_,
    paygradest0_.scale_value as scale6_39_0_
from
    tv_grade_point paygradest0_
where
    paygradest0_.grade_code= 'Grade 9'
</code>```

The query returns 9 results from the database, but hibernate only ever retrieves the first record.  I'm assuming it may have something to do with the composite key of paystep (perils of using hibernate with a legacy database).

Does anyone know why this behaviour has popped up?

答:
You need to specify the join column "grade_code" in the OneToMany reference and make it inverse.

By the way: the SQL query in your question is retrieving tv_grade_point, not Paystep.

Body:
I have a hibernate entity (paygrade) with multiple children (paysteps) and am trying to query these children in the app.  Unfortunately, I'm only able to retrieve the first record of the query.  Here are the entities

public class Paygrade extends Persistent {

    @Id
    @Column(length = 80, updatable=false)
    private String code;

    @Column(length = 80, updatable=false)
    private String name;

    @OneToMany(mappedBy = "paygrade", fetch = FetchType.LAZY)
    @ForeignKey(name = "none")
    private Set<Paystep> paygradeSteps = new HashSet<Paystep>();

    // getters and setters
}

@IdClass(PaystepPK.class)
public class Paystep {

    @Id
    @Column(length = 80, updatable=false)
    protected String gradeCode;

    @Column(length = 80, updatable=false)
    protected String gradeName;

    @Id
    @Column(length = 80, updatable=false)
    protected String scaleCode;

    @Column(length = 80, updatable=false)
    protected String scaleName;

    @Column(length = 80, updatable=false)
    protected String scalePoint;

    @Column(updatable=false)
    protected Long scaleValue;

    @ManyToOne
    @ForeignKey(name = "none")
    @JoinColumn (name="grade_code", updatable = false, insertable = false)
    private Paygrade paygrade;

    // getters and setters

}

The below query is called by hibernate when calling the getPaygradeSteps() method of a paygrade instance:

Hibernate:
/* load one-to-many ...Paygrade.paygradeSteps */ select
    paygradest0_.grade_code as grade1_38_1_,
    paygradest0_.grade_code as grade1_1_,
    paygradest0_.scale_code as scale2_1_,
    paygradest0_.grade_code as grade1_39_0_,
    paygradest0_.scale_code as scale2_39_0_,
    paygradest0_.grade_name as grade3_39_0_,
    paygradest0_.scale_name as scale4_39_0_,
    paygradest0_.scale_point as scale5_39_0_,
    paygradest0_.scale_value as scale6_39_0_
from
    tv_grade_point paygradest0_
where
    paygradest0_.grade_code= 'Grade 9'

The query returns 9 results from the database, but hibernate only ever retrieves the first record.  I'm assuming it may have something to do with the composite key of paystep (perils of using hibernate with a legacy database).

Does anyone know why this behaviour has popped up?


问:
JSP Page not rendering in SpringBoot Application
I have seen lot of same problem but My problem is not resolving with all those solutions. My JSP page is not rendering.

I have added all required jars like thymeleaf, tomcat, jstl to run the application but still getting error

Below is my controller

```<code>@RequestMapping("/rest/user")
public class BookResource {

@GetMapping("/recommend")
    public List<String> recommend() {
        return bookrepo.BookDetail(bookname);

    }
@RequestMapping(value = "/recommendation", method = RequestMethod.GET)
    public String recommend(Model model) {
        model.addAttribute("recommendations", bookrepo.BookDetail(bookname));
        model.addAttribute("name", "Harsh");
        return "recommendation";

    }
}
</code>```

After i Hit the URL I am getiing below error:

```<code>Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Tue May 28 09:50:33 IST 2019
There was an unexpected error (type=Internal Server Error, status=500).
Error resolving template "recommendation", template might not exist or might not be accessible by any of the configured Template Resolvers
</code>```

The JSP Page I have created not rendering, I put my jsp page inside resources/templates and also at WEB-INF/jsp/.
And properties file is also updated

```<code>spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
</code>```

Pom.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.springBootApp</groupId>
    <artifactId>FirstSpringBootApp</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.3.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.6</version>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap-datepicker</artifactId>
            <version>1.0.1</version>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>1.9.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- Redis Dependencies -->

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- GCP Dependencies -->

        <!-- <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-gcp-starter</artifactId>
            <version>1.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-gcp-starter-sql-mysql</artifactId>
            <version>1.0.0.RELEASE</version>
        </dependency> -->

    </dependencies>

    <build>
        <plugins>
             <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <!-- GCP plugin -->
            <!-- <plugin>
                <groupId>com.google.cloud.tools</groupId>
                <artifactId>appengine-maven-plugin</artifactId>
                <version>1.3.2</version>
            </plugin> -->
        </plugins>
    </build>

</project>
</code>```

Structure .

答:
From your stacktrace it can be seen that springboot fails to resolve your template "recommendation", so it must have something to do with where you have kept your jsp files.

Keep your jsp templates under /WEB-INF/jsp/ since that's what you have provided in the application.properties. Also , ensure that the extension for your template is .jsp itself since you have specified that in property file as well.

Ensure that , in your pom you have the following dependencies added :

```<code><!-- JSTL -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
</dependency>
<!-- To compile JSP files -->
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <scope>provided</scope>
</dependency>
</code>```

You can remove the thymeleaf dependency since you are using jsp as the templating engine here.

If that did not work, then you can try manually configuring your jsp view resolver like :

```<code>@Configuration
public class MvcConfiguration implements WebMvcConfigurer
{
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/view/");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(JstlView.class);
        registry.viewResolver(resolver);
    }
}
</code>```

Body:
I have seen lot of same problem but My problem is not resolving with all those solutions. My JSP page is not rendering.

I have added all required jars like thymeleaf, tomcat, jstl to run the application but still getting error

Below is my controller

@RequestMapping("/rest/user")
public class BookResource {

@GetMapping("/recommend")
    public List<String> recommend() {
        return bookrepo.BookDetail(bookname);

    }
@RequestMapping(value = "/recommendation", method = RequestMethod.GET)
    public String recommend(Model model) {
        model.addAttribute("recommendations", bookrepo.BookDetail(bookname));
        model.addAttribute("name", "Harsh");
        return "recommendation";

    }
}

After i Hit the URL I am getiing below error:

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Tue May 28 09:50:33 IST 2019
There was an unexpected error (type=Internal Server Error, status=500).
Error resolving template "recommendation", template might not exist or might not be accessible by any of the configured Template Resolvers

The JSP Page I have created not rendering, I put my jsp page inside resources/templates and also at WEB-INF/jsp/.
And properties file is also updated

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

Pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.springBootApp</groupId>
    <artifactId>FirstSpringBootApp</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.3.RELEASE</version>
        <relativePath />
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.6</version>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap-datepicker</artifactId>
            <version>1.0.1</version>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>1.9.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
             <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

        </plugins>
    </build>

</project>

Structure .

Body:
From your stacktrace it can be seen that springboot fails to resolve your template "recommendation", so it must have something to do with where you have kept your jsp files.

Keep your jsp templates under /WEB-INF/jsp/ since that's what you have provided in the application.properties. Also , ensure that the extension for your template is .jsp itself since you have specified that in property file as well.

Ensure that , in your pom you have the following dependencies added :

<!-- JSTL -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
</dependency>
<!-- To compile JSP files -->
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <scope>provided</scope>
</dependency>

You can remove the thymeleaf dependency since you are using jsp as the templating engine here.

If that did not work, then you can try manually configuring your jsp view resolver like :

@Configuration
public class MvcConfiguration implements WebMvcConfigurer
{
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/view/");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(JstlView.class);
        registry.viewResolver(resolver);
    }
}


问:
Which services are identified in conn.log by Bro?
I am looking for the list of services that bro/zeek identifies in conn.log. But I am unable to find out exactly how many services Bro identifies. Where can I get the correct script le, source code or documentation where I can get the list of services that Bro detects?

E.g. this documentation section just mentions that

```<code>application-layer services ( - the service field is filled in as Bro determines a specific protocol to be in use, independent of the connection’s ports),
</code>```

But where are these services defined?

答:
The answer to this question is a bit complex, because it depends on the set of protocol analyzers present on your system and how they are configured (i.e., how/whether Zeek may select them for individual connections).

That said, this list defines the set of supported analyzers. There may be more if you install additional ones on your system via the package manager.

The nitty-gritty details are spelled out in the original paper.

Body:
I am looking for the list of services that bro/zeek identifies in conn.log. But I am unable to find out exactly how many services Bro identifies. Where can I get the correct script le, source code or documentation where I can get the list of services that Bro detects?

E.g. this documentation section just mentions that

application-layer services ( - the service field is filled in as Bro determines a specific protocol to be in use, independent of the connection’s ports),

But where are these services defined?


问:
run external application in linux using qprocess
I am creating an GUI application using QT creater in Raspbian. When I click a button I want to open an external application like terminal, or browser, etc.

I have tried many attempts

attempt 1

std::system("/usr/share/raspi-ui-overrides/applications/scratch.desktop&");
```

<p>it says me permission denied</p>

<ul>
<li>attempt 2</li>
</ul>

<pre class="lang-cpp prettyprint-override"><code>QDesktopServices::openUrl(QUrl("/usr/share/raspi-ui-overrides/applications/scratch.desktop"));
</code>```

this one is working but its not opening the application but its opening in terminal:

QDesktopServices::openUrl(QUrl("/usr/share/raspi-ui-overrides/applications/scratch.desktop"));
```

答:
The .desktop files are not executable, but serve as shortcuts for the desktop system. Assuming that the scratch.desktop has the following:

scratch.desktop

```<code>[Desktop Entry]
Name=Scratch
Comment= Programming system and content development tool
Exec=scratch
Terminal=false
Type=Application
Icon=scratch
Categories=Development;
MimeType=application/x-scratch-project
</code>```

Then the executable is /usr/bin/scratch, And you can run it with Qt:

QProcess::startDetached("/usr/bin/scratch");
```

<p>Or:</p>

<pre class="lang-cpp prettyprint-override"><code>QProcess::execute("/usr/bin/scratch");
</code>```

Body:
I am creating an GUI application using QT creater in Raspbian. When I click a button I want to open an external application like terminal, or browser, etc.

I have tried many attempts

attempt 1

std::system("/usr/share/raspi-ui-overrides/applications/scratch.desktop&");

it says me permission denied

attempt 2

QDesktopServices::openUrl(QUrl("/usr/share/raspi-ui-overrides/applications/scratch.desktop"));

this one is working but its not opening the application but its opening in terminal:

QDesktopServices::openUrl(QUrl("/usr/share/raspi-ui-overrides/applications/scratch.desktop"));

Body:
The .desktop files are not executable, but serve as shortcuts for the desktop system. Assuming that the scratch.desktop has the following:

scratch.desktop

[Desktop Entry]
Name=Scratch
Comment= Programming system and content development tool
Exec=scratch
Terminal=false
Type=Application
Icon=scratch
Categories=Development;
MimeType=application/x-scratch-project

Then the executable is /usr/bin/scratch, And you can run it with Qt:

QProcess::startDetached("/usr/bin/scratch");

Or:

QProcess::execute("/usr/bin/scratch");


问:
Call search API after UITextField changed, Moya
I am doing search feature, I want to call api after my search textField changed. I am using Moya, how can I do that?
Is there anyone have idea?</p>

答:
If you use Moya, it will return an Object Cancellable when you call a request.
You just need to save that object, and then when you make another request, you cancel the previous request.

Example:

```<code>var previousRequest: Cancellable?

func search(text: String) {
    previousRequest?.cancel()
    //make new request...
}
</code>```

Body:
If you use Moya, it will return an Object Cancellable when you call a request.
You just need to save that object, and then when you make another request, you cancel the previous request.

Example:

var previousRequest: Cancellable?

func search(text: String) {
    previousRequest?.cancel()
    //make new request...
}


问:
How to save grayscale image in Python?
I am trying to save a grayscale image using matplotlib savefig(). I find that the png file which is saved after the use of matplotlib savefig() is a bit different from the output image which is showed when the code runs. The output image which is generated when the code is running contains more details than the saved figure.

How can I save the output plot in such a manner that all details are stored in the output image?

My my code is given below:

```<code>import cv2
import matplotlib.pyplot as plt

plt.figure(1)
img_DR = cv2.imread(‘image.tif',0)
edges_DR = cv2.Canny(img_DR,20,40)
plt.imshow(edges_DR,cmap = 'gray')
plt.savefig('DR.png')
plt.show()
</code>```

The input file (‘image.tif’) can be found from here.

Following is the output image which is generated when the code is running:

Below is the saved image:

Although the two aforementioned images denote the same picture, one can notice that they are slightly different. A keen look at the circular periphery of the two images shows that they are different.

答:
Save the actual image to file, not the figure.  The DPI between the figure and the actual created image from your processing will be different.   Since you're using OpenCV, use cv2.imwrite.  In your case:

```<code>cv2.imwrite('DR.png', edges_DR)
</code>```

Use the PNG format as JPEG is lossy and would thus give you a reduction in quality to promote small file sizes.  If accuracy is the key here, use a lossless compression standard and PNG is one example.

If you are somehow opposed to using OpenCV, Matplotlib has an equivalent image writing method called imsave which has the same syntax as cv2.imwrite:

```<code>plt.imsave('DR.png', edges_DR, cmap='gray')
</code>```

Note that I am enforcing the colour map to be grayscale for imsave as it is not automatically inferred like how OpenCV writes images to file.

Title: How to save grayscale image in Python?

Body:
I am trying to save a grayscale image using matplotlib savefig(). I find that the png file which is saved after the use of matplotlib savefig() is a bit different from the output image which is showed when the code runs. The output image which is generated when the code is running contains more details than the saved figure.

How can I save the output plot in such a manner that all details are stored in the output image?

My my code is given below:

import cv2
import matplotlib.pyplot as plt

plt.figure(1)
img_DR = cv2.imread(‘image.tif',0)
edges_DR = cv2.Canny(img_DR,20,40)
plt.imshow(edges_DR,cmap = 'gray')
plt.savefig('DR.png')
plt.show()

The input file (‘image.tif’) can be found from here.

Following is the output image which is generated when the code is running:

Below is the saved image:

Although the two aforementioned images denote the same picture, one can notice that they are slightly different. A keen look at the circular periphery of the two images shows that they are different.

Body:
Save the actual image to file, not the figure.  The DPI between the figure and the actual created image from your processing will be different.   Since you're using OpenCV, use cv2.imwrite.  In your case:

cv2.imwrite('DR.png', edges_DR)

Use the PNG format as JPEG is lossy and would thus give you a reduction in quality to promote small file sizes.  If accuracy is the key here, use a lossless compression standard and PNG is one example.

If you are somehow opposed to using OpenCV, Matplotlib has an equivalent image writing method called imsave which has the same syntax as cv2.imwrite:

plt.imsave('DR.png', edges_DR, cmap='gray')

Note that I am enforcing the colour map to be grayscale for imsave as it is not automatically inferred like how OpenCV writes images to file.


问:
PHPSpec - fail to run, anyone using it for php development?
Searched stackoverflow for this and found no answer

Coming from Ruby On Rails and Rspec, I need a tool like rspec (easier transition). Installed it through PEAR and tried to run it but it's not working (yet)

Just wanna ask around if anyone's using it have the same problem, since it's not running at all

tried running it with an example from the manual - http://dev.phpspec.org/manual/en/before.writing.code.specify.its.required.behaviour.html

```<code>phpspec NewFileSystemLoggerSpec
</code>```

returns nothing

even running

```<code>phpspec some_dummy_value
</code>```

returns nothing

答:
Note that PHPSpec is discontinued:

http://blog.astrumfutura.com/2010/05/the-mockery-php-mock-objects-made-simple/#comment-88628508

OwnerDisplayName: Ed

ContentLicense: CC BY-SA 2.5

Body:
Searched stackoverflow for this and found no answer

Coming from Ruby On Rails and Rspec, I need a tool like rspec (easier transition). Installed it through PEAR and tried to run it but it's not working (yet)

Just wanna ask around if anyone's using it have the same problem, since it's not running at all

tried running it with an example from the manual - http://dev.phpspec.org/manual/en/before.writing.code.specify.its.required.behaviour.html

phpspec NewFileSystemLoggerSpec

returns nothing

even running

phpspec some_dummy_value

returns nothing


问:
How to Call and Compare Previous Guesses to One Another in a Guessing Game
I apologize if there is a answer to this question on a previous post. I seen a few posts about guessing games but couldn't seem to find how to recall a guess and see if it was closer then the previous one. I'm a complete beginner in python, I want the game to indicate if the first guess is within 10 or not, then say warmer or colder base on the next guesses. Thank you in advance.</p>

```<code>from random import randint

win = randint(1,101)

count = 0

while True:
    try:
        result = int(input('Guess a number between 1 and 100 \n'))
        if result > 100 or result < 1:
            print('oops, pick between 1 and 100!')
            continue
    except:
        print("oops, that's not a number!")
        continue

    if result == win:
        print(f"YOU WON, it took you {count} guesses")
        count += 1
        break

    else:
        if abs(result - win) <= 10:
                print("HOT WITHIN 10")
                count += 1
                continue
        elif abs(result - win) > 10:
            print("COLD ")
            count += 1
            continue

                # call previous guess
                # if abs(win - new_guess) < (previous_guess - win)
                # print warmer
                # else print colder
</code>```

答:
Here is some modification on your code to print warmer or colder based on previous guess:</p>

```<code>from random import randint

win = randint(1,101)
count = 1
prev_guess = guess = None

while True:
    try:
        prev_guess = guess
        guess = int(input('Guess a number between 1 and 100 \n'))
        if guess > 100 or guess < 1:
            print('oops, pick between 1 and 100!')
            continue
    except:
        print("oops, that's not a number!")
        continue

    if guess == win:
        print(f"YOU WON, it took you {count} guesses")
        count += 1
        break

    else:
        guess_dist = abs(guess - win)  # _dist for distance to the win number
        print(guess, prev_guess)

        if guess_dist <= 10:
            if not prev_guess or abs(prev_guess - win) > 10:
                print("HOT WITHIN 10")
            elif guess_dist < abs(prev_guess - win):
                print('warmer')
            else:
                print('colder')

        elif guess_dist > 10:
            print("COLD ")

        count += 1
        continue
</code>```

Body:
I apologize if there is a answer to this question on a previous post. I seen a few posts about guessing games but couldn't seem to find how to recall a guess and see if it was closer then the previous one. I'm a complete beginner in python, I want the game to indicate if the first guess is within 10 or not, then say warmer or colder base on the next guesses. Thank you in advance.

from random import randint

win = randint(1,101)

count = 0

while True:
    try:
        result = int(input('Guess a number between 1 and 100 \n'))
        if result > 100 or result < 1:
            print('oops, pick between 1 and 100!')
            continue
    except:
        print("oops, that's not a number!")
        continue

    if result == win:
        print(f"YOU WON, it took you {count} guesses")
        count += 1
        break

    else:
        if abs(result - win) <= 10:
                print("HOT WITHIN 10")
                count += 1
                continue
        elif abs(result - win) > 10:
            print("COLD ")
            count += 1
            continue

                # call previous guess
                # if abs(win - new_guess) < (previous_guess - win)
                # print warmer
                # else print colder

Body:
Here is some modification on your code to print warmer or colder based on previous guess:

from random import randint

win = randint(1,101)
count = 1
prev_guess = guess = None

while True:
    try:
        prev_guess = guess
        guess = int(input('Guess a number between 1 and 100 \n'))
        if guess > 100 or guess < 1:
            print('oops, pick between 1 and 100!')
            continue
    except:
        print("oops, that's not a number!")
        continue

    if guess == win:
        print(f"YOU WON, it took you {count} guesses")
        count += 1
        break

    else:
        guess_dist = abs(guess - win)  # _dist for distance to the win number
        print(guess, prev_guess)

        if guess_dist <= 10:
            if not prev_guess or abs(prev_guess - win) > 10:
                print("HOT WITHIN 10")
            elif guess_dist < abs(prev_guess - win):
                print('warmer')
            else:
                print('colder')

        elif guess_dist > 10:
            print("COLD ")

        count += 1
        continue


问:
Get all data from DIV JQUERY
I try to get all data from a DIV tag. Or I need only text from a div, but the problem is that it has a strong html tag in div. My div block.

var myVar;
myVar = $('.myclass').text();

alert(myVar);```
<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>
<div class="myclass">100 -
  <strong>265</strong>
</div></code>```

and

```<code> alert(myVar.value);
</code>```

and

```<code> myVar = $('.myclass').html();
</code>```

By first i get nothing, if I try to get value of myVar, I get message "undefined". If i try to get html, i get nothing i my alert.
The easy way I think are to get all data from div and replace strong html tag with nothing.

答:
End Result is without strong tag

var myVar;
myVar = $('.myclass').text();
$('.result').text(myVar);```
<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>
<div class="myclass">100 -
  <strong>265</strong>
</div>

<div class="result">

</div></code>```

Title: Get all data from DIV JQUERY

Body:
I try to get all data from a DIV tag. Or I need only text from a div, but the problem is that it has a strong html tag in div. My div block.

var myVar;
myVar = $('.myclass').text();

alert(myVar);

100 -
  265

and

 alert(myVar.value);

and

 myVar = $('.myclass').html();

By first i get nothing, if I try to get value of myVar, I get message "undefined". If i try to get html, i get nothing i my alert.
The easy way I think are to get all data from div and replace strong html tag with nothing.

Body:
End Result is without strong tag

var myVar;
myVar = $('.myclass').text();
$('.result').text(myVar);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="myclass">100 -
  <strong>265</strong>
</div>

<div class="result">

</div>


问:
Conditional date filter
I am trying to split a series of timestamps into groups:

Define variables:

```<code>Very old = Date < '20190101'
Current = Today's date as %Y-%m (Year-Month)
</code>```

Conditions

```<code>1. timestamp < very old
2. Very old < timestamp < current
3. timestamp = current
4. timestamp > current
</code>```

Series that had been split from original DataFrame:

```<code>timestamp_dict = \
{0: Timestamp('2019-05-01 00:00:00'),
 1: Timestamp('2019-05-01 00:00:00'),
 2: Timestamp('2018-12-01 00:00:00'),
 3: Timestamp('2019-05-01 00:00:00'),
 4: Timestamp('2019-05-01 00:00:00'),
 5: Timestamp('2019-05-01 00:00:00'),
 6: Timestamp('2019-04-01 00:00:00'),
 7: Timestamp('2019-08-01 00:00:00')}
</code>```

The datetimes are stored as datetime64[ns].
I have a feeling converting current timestamp to str is wrong, however, I am not sure how to extract the current timestamp as format %Y-%m.

I have an idea on accessing current date as month, year integers and then concatenating but then I would probably run into zero padding issues:

```<code>_month = dt.datetime.today().month
_year = dt.datetime.today().year

# Would run into zero padding for months 1-9:
current = str(_year) + str(_month)
</code>```

Here, I try to generate a new DataFrame column using np.select and specifying my required conditions.

```<code>import datetime as dt

current = dt.datetime.today().strftime('%Y-%m')
veryold = '20190101'

conditions = [
    df.Delivery < veryold,
    (df.Delivery >= veryold | (df.Delivery < current),
    df.Delivery == current,
    df.Delivery > current
]

outcome = [
    'Very old',
    'Old',
    'Current',
    'Future'
]

df['New'] = np.select(conditions, outcome)

df.New
</code>```

My expected output is to have an additional column of labeled outcomes in my DataFrame.

答:
Idea is create month periods by Series.dt.to_period for possible compare by YYYY-MM:

```<code>current = pd.Timestamp(pd.datetime.today()).to_period('M')
veryold = pd.Timestamp('20190101')

conditions = [
    df.Delivery < veryold,
    (df.Delivery >= veryold) | (df.Delivery.dt.to_period('M') < current),
    df.Delivery.dt.to_period('M') == current,
    df.Delivery.dt.to_period('M') > current]

outcome = [
    'Very old',
    'Old',
    'Current',
    'Future'
]

df = pd.Series(pd.Timestamp_dict).to_frame('Delivery')
df['New'] = np.select(conditions, outcome)
print(df)
    Delivery       New
0 2019-05-01       Old
1 2019-05-01       Old
2 2018-12-01  Very old
3 2019-05-01       Old
4 2019-05-01       Old
5 2019-05-01       Old
6 2019-04-01       Old
7 2019-08-01       Old
</code>```

Title: Conditional date filter

Body:
I am trying to split a series of timestamps into groups:

Define variables:

Very old = Date < '20190101'
Current = Today's date as %Y-%m (Year-Month)

Conditions

1. timestamp < very old
2. Very old < timestamp < current
3. timestamp = current
4. timestamp > current

Series that had been split from original DataFrame:

timestamp_dict = \
{0: Timestamp('2019-05-01 00:00:00'),
 1: Timestamp('2019-05-01 00:00:00'),
 2: Timestamp('2018-12-01 00:00:00'),
 3: Timestamp('2019-05-01 00:00:00'),
 4: Timestamp('2019-05-01 00:00:00'),
 5: Timestamp('2019-05-01 00:00:00'),
 6: Timestamp('2019-04-01 00:00:00'),
 7: Timestamp('2019-08-01 00:00:00')}

The datetimes are stored as datetime64[ns].
I have a feeling converting current timestamp to str is wrong, however, I am not sure how to extract the current timestamp as format %Y-%m.

I have an idea on accessing current date as month, year integers and then concatenating but then I would probably run into zero padding issues:

_month = dt.datetime.today().month
_year = dt.datetime.today().year

# Would run into zero padding for months 1-9:
current = str(_year) + str(_month)

Here, I try to generate a new DataFrame column using np.select and specifying my required conditions.

import datetime as dt

current = dt.datetime.today().strftime('%Y-%m')
veryold = '20190101'

conditions = [
    df.Delivery < veryold,
    (df.Delivery >= veryold | (df.Delivery < current),
    df.Delivery == current,
    df.Delivery > current
]

outcome = [
    'Very old',
    'Old',
    'Current',
    'Future'
]

df['New'] = np.select(conditions, outcome)

df.New

My expected output is to have an additional column of labeled outcomes in my DataFrame.

Body:
Idea is create month periods by Series.dt.to_period for possible compare by YYYY-MM:

current = pd.Timestamp(pd.datetime.today()).to_period('M')
veryold = pd.Timestamp('20190101')

conditions = [
    df.Delivery < veryold,
    (df.Delivery >= veryold) | (df.Delivery.dt.to_period('M') < current),
    df.Delivery.dt.to_period('M') == current,
    df.Delivery.dt.to_period('M') > current]

outcome = [
    'Very old',
    'Old',
    'Current',
    'Future'
]

df = pd.Series(pd.Timestamp_dict).to_frame('Delivery')
df['New'] = np.select(conditions, outcome)
print(df)
    Delivery       New
0 2019-05-01       Old
1 2019-05-01       Old
2 2018-12-01  Very old
3 2019-05-01       Old
4 2019-05-01       Old
5 2019-05-01       Old
6 2019-04-01       Old
7 2019-08-01       Old


问:
How to uninstall Go?
I tried the answer here Removed golang but go command still works?, but it didn't work (I can still run go)

Currently, when I run which go I see this output

```<code>/usr/local/go/bin/go
</code>```

I think I had two installations of go as my GOPATH was pointing to another folder named gocode. I've now removed that folder, and the usr/local/go/bin/go folder.

I've also removed my GOPATH. However, I can still run go.

How do I uninstall go?

答:
Use this command to uninstall Golang for Ubuntu.

This will remove just the golang-go package itself.

```<code>sudo apt-get remove golang-go
</code>```

Uninstall golang-go and its dependencies:

```<code>sudo apt-get remove --auto-remove golang-go
</code>```

Title: How to uninstall Go?

Body:
I tried the answer here Removed golang but go command still works?, but it didn't work (I can still run go)

Currently, when I run which go I see this output

/usr/local/go/bin/go

I think I had two installations of go as my GOPATH was pointing to another folder named gocode. I've now removed that folder, and the usr/local/go/bin/go folder.

I've also removed my GOPATH. However, I can still run go.

How do I uninstall go?

Body:
Use this command to uninstall Golang for Ubuntu.

This will remove just the golang-go package itself.

sudo apt-get remove golang-go

Uninstall golang-go and its dependencies:

sudo apt-get remove --auto-remove golang-go


问:
Error(57,5): PL/SQL: ORA-00984: column not allowed here for creating stored procedures
I have created a stored procedure but while compiling it, I am getting error as

Error(57,5): PL/SQL: ORA-00984: column not allowed here

Below is my query

create or replace PROCEDURE NEIQC_DATA_DUMP_MST AS
BEGIN

execute immediate 'truncate table TBL_NEIQC_WF_SITE_MST';

INSERT INTO TBL_NEIQC_WF_SITE_MST

(
    OBJECTID,
    SAP_ID,
    NETWORK_ENTITY_ID    ,
    SITE_NAME            ,
    SITE_ADDRESS         ,
    MAINTENANCEZONE_CODE ,
    INVENTORY_TYPE       ,
    TYPE_NAME            ,
    SITE_STATUS_CODE     ,
    NE_MODIFIED_DATE     ,
    NE_MODIFIED_BY       ,
    CREATED_DATE         ,
    CREATED_BY           ,
    STRUCTURE_NAME       ,
    RJ_CITY_CODE         ,
    RJ_R4G_STATE_CODE    ,
    RJ_DISTRICT_CODE     ,
    RJ_TALUK_CODE        ,
    RJ_JC_CODE           ,
    RJ_JIOPOINT_SAPCODE  ,
    RJ_COMPANY_CODE_1    ,
    RJ_COMPANY_CODE_2
)

VALUES

(
    OBJECTID                      ,
    RJ_SAPID,
    RJ_NETWORK_ENTITY_ID          ,
    RJ_SITE_NAME                  ,
    RJ_SITE_ADDRESS               ,
    RJ_MAINTENANCE_ZONE_CODE      ,
    '',
    TYPE_NAME                     ,
    'ACTIVE',
    RJ_LAST_MODIFIED_DATE,
    RJ_LAST_MODIFIED_BY ,
    SYSDATE,
    'SCHEDULER',
    STRUCTURE_NAME                ,
    RJ_CITY_CODE                  ,
    RJ_R4G_STATE_CODE             ,
    RJ_DISTRICT_CODE              ,
    RJ_TALUK_CODE                 ,
    RJ_JC_CODE                    ,
    RJ_JIOPOINT_SAPCODE           ,
    RJ_COMPANY_CODE_1             ,
    RJ_COMPANY_CODE_2
);

COMMIT;

END NEIQC_DATA_DUMP_MST;```

please suggest what is wrong

答:
your insert Statement should look like </p>

```<code>INSERT INTO TBL_NEIQC_WF_SITE_MST

(
    OBJECTID,
    SAP_ID,
    NETWORK_ENTITY_ID    ,
    SITE_NAME            ,
    SITE_ADDRESS         ,
    MAINTENANCEZONE_CODE ,
    INVENTORY_TYPE       ,
    TYPE_NAME            ,
    SITE_STATUS_CODE     ,
    NE_MODIFIED_DATE     ,
    NE_MODIFIED_BY       ,
    CREATED_DATE         ,
    CREATED_BY           ,
    STRUCTURE_NAME       ,
    RJ_CITY_CODE         ,
    RJ_R4G_STATE_CODE    ,
    RJ_DISTRICT_CODE     ,
    RJ_TALUK_CODE        ,
    RJ_JC_CODE           ,
    RJ_JIOPOINT_SAPCODE  ,
    RJ_COMPANY_CODE_1    ,
    RJ_COMPANY_CODE_2
)

select
    OBJECTID                      ,
    RJ_SAPID,
    RJ_NETWORK_ENTITY_ID          ,
    RJ_SITE_NAME                  ,
    RJ_SITE_ADDRESS               ,
    RJ_MAINTENANCE_ZONE_CODE      ,
    '',
    TYPE_NAME                     ,
    'ACTIVE',
    RJ_LAST_MODIFIED_DATE,
    RJ_LAST_MODIFIED_BY ,
    SYSDATE,
    'SCHEDULER',
    STRUCTURE_NAME                ,
    RJ_CITY_CODE                  ,
    RJ_R4G_STATE_CODE             ,
    RJ_DISTRICT_CODE              ,
    RJ_TALUK_CODE                 ,
    RJ_JC_CODE                    ,
    RJ_JIOPOINT_SAPCODE           ,
    RJ_COMPANY_CODE_1             ,
    RJ_COMPANY_CODE_2
  from ne_structures -- if this is your table
</code>```

<p>;</p>

Body:
I have created a stored procedure but while compiling it, I am getting error as

Error(57,5): PL/SQL: ORA-00984: column not allowed here

Below is my query

create or replace PROCEDURE NEIQC_DATA_DUMP_MST AS
BEGIN

execute immediate 'truncate table TBL_NEIQC_WF_SITE_MST';

INSERT INTO TBL_NEIQC_WF_SITE_MST

(
    OBJECTID,
    SAP_ID,
    NETWORK_ENTITY_ID    ,
    SITE_NAME            ,
    SITE_ADDRESS         ,
    MAINTENANCEZONE_CODE ,
    INVENTORY_TYPE       ,
    TYPE_NAME            ,
    SITE_STATUS_CODE     ,
    NE_MODIFIED_DATE     ,
    NE_MODIFIED_BY       ,
    CREATED_DATE         ,
    CREATED_BY           ,
    STRUCTURE_NAME       ,
    RJ_CITY_CODE         ,
    RJ_R4G_STATE_CODE    ,
    RJ_DISTRICT_CODE     ,
    RJ_TALUK_CODE        ,
    RJ_JC_CODE           ,
    RJ_JIOPOINT_SAPCODE  ,
    RJ_COMPANY_CODE_1    ,
    RJ_COMPANY_CODE_2
)

VALUES

(
    OBJECTID                      ,
    RJ_SAPID,
    RJ_NETWORK_ENTITY_ID          ,
    RJ_SITE_NAME                  ,
    RJ_SITE_ADDRESS               ,
    RJ_MAINTENANCE_ZONE_CODE      ,
    '',
    TYPE_NAME                     ,
    'ACTIVE',
    RJ_LAST_MODIFIED_DATE,
    RJ_LAST_MODIFIED_BY ,
    SYSDATE,
    'SCHEDULER',
    STRUCTURE_NAME                ,
    RJ_CITY_CODE                  ,
    RJ_R4G_STATE_CODE             ,
    RJ_DISTRICT_CODE              ,
    RJ_TALUK_CODE                 ,
    RJ_JC_CODE                    ,
    RJ_JIOPOINT_SAPCODE           ,
    RJ_COMPANY_CODE_1             ,
    RJ_COMPANY_CODE_2
);

COMMIT;

END NEIQC_DATA_DUMP_MST;

please suggest what is wrong

Body:
your insert Statement should look like

INSERT INTO TBL_NEIQC_WF_SITE_MST

(
    OBJECTID,
    SAP_ID,
    NETWORK_ENTITY_ID    ,
    SITE_NAME            ,
    SITE_ADDRESS         ,
    MAINTENANCEZONE_CODE ,
    INVENTORY_TYPE       ,
    TYPE_NAME            ,
    SITE_STATUS_CODE     ,
    NE_MODIFIED_DATE     ,
    NE_MODIFIED_BY       ,
    CREATED_DATE         ,
    CREATED_BY           ,
    STRUCTURE_NAME       ,
    RJ_CITY_CODE         ,
    RJ_R4G_STATE_CODE    ,
    RJ_DISTRICT_CODE     ,
    RJ_TALUK_CODE        ,
    RJ_JC_CODE           ,
    RJ_JIOPOINT_SAPCODE  ,
    RJ_COMPANY_CODE_1    ,
    RJ_COMPANY_CODE_2
)

select
    OBJECTID                      ,
    RJ_SAPID,
    RJ_NETWORK_ENTITY_ID          ,
    RJ_SITE_NAME                  ,
    RJ_SITE_ADDRESS               ,
    RJ_MAINTENANCE_ZONE_CODE      ,
    '',
    TYPE_NAME                     ,
    'ACTIVE',
    RJ_LAST_MODIFIED_DATE,
    RJ_LAST_MODIFIED_BY ,
    SYSDATE,
    'SCHEDULER',
    STRUCTURE_NAME                ,
    RJ_CITY_CODE                  ,
    RJ_R4G_STATE_CODE             ,
    RJ_DISTRICT_CODE              ,
    RJ_TALUK_CODE                 ,
    RJ_JC_CODE                    ,
    RJ_JIOPOINT_SAPCODE           ,
    RJ_COMPANY_CODE_1             ,
    RJ_COMPANY_CODE_2
  from ne_structures -- if this is your table

;


问:
How to manage icons in solution with several projects?
I have five projects in my solution. Each of them uses some icons (many of these icons are the same in the different projects) and I want to store them in one place.

I tried to use separate project for storing icons, but I got fiasco..

When I use icon from other project (project which contains all icons) Visual Studio automatically copied this icons to the form.resx file.

Explanation:
By the first I can't attach icon (from other project) to my button from designer. Therefore I must to go to the form.designer.cs and manually attach the icon to the button. After these operations VS rebuilt the auto-generated part in form.designer.cs replaced my code with own and copied the icon to the form.resx file.

```<code>//my code
this.btnCompile.Image = SharedProject.Properties.Resources.compile;

//code replaced with VS
this.btnCompile.Image = ( (System.Drawing.Image)( resources.GetObject( "compile.Image" ) ) );
</code>```

You can see that image was copied to local project to the resources. In this case to change button's image is insufficient to replace only my image (compilation.png) in shared project. I need to replace also it in each form where it used.

Question: How to manage icons in solution to avoid duplication and this big inconvenience?

答:
You can design a Service project witch will serve Icons or other resources for your other projects. you should just implement an interface like this in your application :

```<code>public interface IResourceProvider
{
   Image RetrieveIcon(string key);
   //you can add other resource types here.
}
</code>```

then implement this interface in a new class and return related Icon to each key passed to its methods. here you need to browse resx file of this project for requested Icon (Resource)

then in you application you should just call your ResourceProvider class to priovide required resource Items.

Body:
I have five projects in my solution. Each of them uses some icons (many of these icons are the same in the different projects) and I want to store them in one place.

I tried to use separate project for storing icons, but I got fiasco..

When I use icon from other project (project which contains all icons) Visual Studio automatically copied this icons to the form.resx file.

Explanation:
By the first I can't attach icon (from other project) to my button from designer. Therefore I must to go to the form.designer.cs and manually attach the icon to the button. After these operations VS rebuilt the auto-generated part in form.designer.cs replaced my code with own and copied the icon to the form.resx file.

//my code
this.btnCompile.Image = SharedProject.Properties.Resources.compile;

//code replaced with VS
this.btnCompile.Image = ( (System.Drawing.Image)( resources.GetObject( "compile.Image" ) ) );

You can see that image was copied to local project to the resources. In this case to change button's image is insufficient to replace only my image (compilation.png) in shared project. I need to replace also it in each form where it used.

Question: How to manage icons in solution to avoid duplication and this big inconvenience?

Body:
You can design a Service project witch will serve Icons or other resources for your other projects. you should just implement an interface like this in your application :

public interface IResourceProvider
{
   Image RetrieveIcon(string key);
   //you can add other resource types here.
}

then implement this interface in a new class and return related Icon to each key passed to its methods. here you need to browse resx file of this project for requested Icon (Resource)

then in you application you should just call your ResourceProvider class to priovide required resource Items.


问:
style.css not updating on Wordpress
I've been struggling with this problem for days and can't find a solution.

I've been updating my css and the changes are not reflected for a crazy reason.

When I check the source, the style.css is this one, that is never updating :

http://www.dogecoin.link/wp-content/themes/directory/directory/style.css?1404006283

That is different from this one that is the good one and where the changes are reflected:

http://www.dogecoin.link/wp-content/themes/directory/directory/style.css

I don't know where the "style.css?1404006283" is cached and even after emptying the cache (W3 Cache) and waiting for 2days, the changes are not reflected.

Thank you for the help!

答: Clear the browser cache and rrefresh! works will be null without version in styles sheet so changes will not effect. Changing the version number of stylesheet whenever you do a change to styles is a good practice and will have immediate effect on the production. Instead there will be no cache problem.</p>

Title: style.css not updating on Wordpress


问:
What's the best way to deal with version control system and xcode storyboards?
I am pretty new to iOS UI development using xcode and I am struggling on how to deal with storyboards and version control systems.

When dealing with git pull requests I am having a hard time understanding all the changes that are included in that file, even opening the storyboard and moving the "camera" around changes a lot of stuff in it.

So my question is... when drawing a UI with xcode, is storyboard the right tool to do it? i.e. changes made by me (let alone by other developers) are not really human-readable in commits; what is the most savvy way to deal with UI? doing it all in code is feasible?

答:
You can use Storyboards, but in many projects I've been working on, two people never modify a Storyboard at the same time because it creates many conflicts and it's the horrible.

If you use Storyboards and respect this rule It would be a good approach.


问:
How to find the unique list entries in a python dataframe?
I have a dataset which has the movie title along with the different genres that it falls under. Each movie has more than one genre. Hence, for the entire dataset I want to find the total number of unique genres that are present.

I am not able to use df.unique() as it is a list in each column of the DataFrame itself.

```<code>movieId title   genres
0   1   Toy Story (1995)    Adventure|Animation|Children|Comedy|Fantasy
1   2   Jumanji (1995)  Adventure|Children|Fantasy
2   3   Grumpier Old Men (1995) Comedy|Romance
3   4   Waiting to Exhale (1995)    Comedy|Drama|Romance
4   5   Father of the Bride Part II (1995)  Comedy
5   6   Heat (1995) Action|Crime|Thriller
6   7   Sabrina (1995)  Comedy|Romance
7   8   Tom and Huck (1995) Adventure|Children
8   9   Sudden Death (1995) Action
9   10  GoldenEye (1995)    Action|Adventure|Thriller
10  11  American President, The (1995)  Comedy|Drama|Romance
11  12  Dracula: Dead and Loving It (1995)  Comedy|Horror
12  13  Balto (1995)    Adventure|Animation|Children
13  14  Nixon (1995)    Drama
14  15  Cutthroat Island (1995) Action|Adventure|Romance
15  16  Casino (1995)   Crime|Drama
16  17  Sense and Sensibility (1995)    Drama|Romance
17  18  Four Rooms (1995)   Comedy
18  19  Ace Ventura: When Nature Calls (1995)   Comedy
19  20  Money Train (1995)  Action|Comedy|Crime|Drama|Thriller
20  21  Get Shorty (1995)   Comedy|Crime|Thriller
21  22  Copycat (1995)  Crime|Drama|Horror|Mystery|Thriller
22  23  Assassins (1995)    Action|Crime|Thriller
23  24  Powder (1995)   Drama|Sci-Fi
24  25  Leaving Las Vegas (1995)    Drama|Romance
25  26  Othello (1995)  Drama
26  27  Now and Then (1995) Children|Drama
27  28  Persuasion (1995)   Drama|Romance
28  29  City of Lost Children, The (Cité des enfants p...
</code>```

This is the dataset for movies.

Under the genres column I want to split Action|Comedy|Crime|Drama|Thriller into Action, Comedy, Crime, Drama, Thriller.

Also for the entire dataset which is as a DataFrame now, I want to find the unique genres.

答:
You can do it as follow:

```<code>df = pd.DataFrame({'title':['Toy Story (1995)','Jumanji (1995)','Grumpier Old Men (1995)'],
                            'genres':['Adventure|Animation|Children|Comedy|Fantasy','Adventure|Children|Fantasy','Comedy|Romance']})

a = list(set([y for x in df['genres'] for y in x.split('|')]))
print(a)
</code>```

Output:

```<code>['Animation', 'Comedy', 'Children', 'Fantasy', 'Adventure', 'Romance']
</code>```

Body:
I have a dataset which has the movie title along with the different genres that it falls under. Each movie has more than one genre. Hence, for the entire dataset I want to find the total number of unique genres that are present.

I am not able to use df.unique() as it is a list in each column of the DataFrame itself.

movieId title   genres
0   1   Toy Story (1995)    Adventure|Animation|Children|Comedy|Fantasy
1   2   Jumanji (1995)  Adventure|Children|Fantasy
2   3   Grumpier Old Men (1995) Comedy|Romance
3   4   Waiting to Exhale (1995)    Comedy|Drama|Romance
4   5   Father of the Bride Part II (1995)  Comedy
5   6   Heat (1995) Action|Crime|Thriller
6   7   Sabrina (1995)  Comedy|Romance
7   8   Tom and Huck (1995) Adventure|Children
8   9   Sudden Death (1995) Action
9   10  GoldenEye (1995)    Action|Adventure|Thriller
10  11  American President, The (1995)  Comedy|Drama|Romance
11  12  Dracula: Dead and Loving It (1995)  Comedy|Horror
12  13  Balto (1995)    Adventure|Animation|Children
13  14  Nixon (1995)    Drama
14  15  Cutthroat Island (1995) Action|Adventure|Romance
15  16  Casino (1995)   Crime|Drama
16  17  Sense and Sensibility (1995)    Drama|Romance
17  18  Four Rooms (1995)   Comedy
18  19  Ace Ventura: When Nature Calls (1995)   Comedy
19  20  Money Train (1995)  Action|Comedy|Crime|Drama|Thriller
20  21  Get Shorty (1995)   Comedy|Crime|Thriller
21  22  Copycat (1995)  Crime|Drama|Horror|Mystery|Thriller
22  23  Assassins (1995)    Action|Crime|Thriller
23  24  Powder (1995)   Drama|Sci-Fi
24  25  Leaving Las Vegas (1995)    Drama|Romance
25  26  Othello (1995)  Drama
26  27  Now and Then (1995) Children|Drama
27  28  Persuasion (1995)   Drama|Romance
28  29  City of Lost Children, The (Cité des enfants p...

This is the dataset for movies.

Under the genres column I want to split Action|Comedy|Crime|Drama|Thriller into Action, Comedy, Crime, Drama, Thriller.

Also for the entire dataset which is as a DataFrame now, I want to find the unique genres.

Body:
You can do it as follow:

df = pd.DataFrame({'title':['Toy Story (1995)','Jumanji (1995)','Grumpier Old Men (1995)'],
                            'genres':['Adventure|Animation|Children|Comedy|Fantasy','Adventure|Children|Fantasy','Comedy|Romance']})

a = list(set([y for x in df['genres'] for y in x.split('|')]))
print(a)

Output:

['Animation', 'Comedy', 'Children', 'Fantasy', 'Adventure', 'Romance']


问:
Regular Expression for matching parentheses
What is the regular expression for matching '(' in a string?

Following is the scenario :

I have a string

```<code>str = "abc(efg)";
</code>```

I want to split the string at '(' using regular expression.For that i am using

```<code>Arrays.asList(Pattern.compile("/(").split(str))
</code>```

But i am getting the following exception.

```<code>java.util.regex.PatternSyntaxException: Unclosed group near index 2
/(
</code>```

Escaping '(' doesn't seems to work.

答:
For any special characters you should use '\'.
So, for matching parentheses  - /\(/ </p>

Body:
What is the regular expression for matching '(' in a string?

Following is the scenario :

I have a string

str = "abc(efg)";

I want to split the string at '(' using regular expression.For that i am using

Arrays.asList(Pattern.compile("/(").split(str))

But i am getting the following exception.

java.util.regex.PatternSyntaxException: Unclosed group near index 2
/(

Escaping '(' doesn't seems to work.


问:
How to execute procedure in function SQL Server
I need this function:

```<code>create function test (@InVar int)
returns nvarchar(max) as
begin
  declare @OutVar nvarchar(max);
  exec someProcedure @InVar, @OutVar out;
  return @OutVar
end
</code>```

I want :

```<code>select *, dbo.test(ID)
from SomeTable
</code>```

答:
It seems you want to execute stored procedure someProcedure from within function test. That's also what you explicitly ask.

That is not allowed, so you cannot do that. Functions in SQL Server are never allowed to have side effects.

As stated in Microsoft's documentation regarding User-Defined Functions:

The statements in a BEGIN...END block cannot have any side effects. Function side effects are any permanent changes to the state of a resource that has a scope outside the function such as a modification to a database table. The only changes that can be made by the statements in the function are changes to objects local to the function, such as local cursors or variables. Modifications to database tables, operations on cursors that are not local to the function, sending e-mail, attempting a catalog modification, and generating a result set that is returned to the user are examples of actions that cannot be performed in a function.

Note

If a CREATE FUNCTION statement produces side effects against resources that do not exist when the CREATE FUNCTION statement is issued, SQL Server executes the statement. However, SQL Server does not execute the function when it is invoked.

So it seems you have to find another strategy to do what you want.

Body:
I need this function:

create function test (@InVar int)
returns nvarchar(max) as
begin
  declare @OutVar nvarchar(max);
  exec someProcedure @InVar, @OutVar out;
  return @OutVar
end

I want :

select *, dbo.test(ID)
from SomeTable


问:
How to skip initializing a Git Repository during creation of angular 6 project
Is there any command to skip initializing a Git Repository during angular 6 project creation

I am using ng new [name] command to create angular 6 project. by default it is adding git repository.

ng new [name]

答:
Updated answer:
Use --skip-git argument instead of deprecated --skipGit.

Old answer: You can use --skipGit argument.

From docs:

--skipGit=true|false

When true, does not initialize a git repository.

Default: false

Aliases: -g

Official docs - See Arguments section.


问:
I don't know why it occurs heap corruption(about memory allocation problem)
it's course's one of project and its goal is to make fully-worked MyString Class. Until made destructor method, it was worked well. but in main.cpp, when i tried to use these method i made, it occurs heap corruption. i thought the problem comes up from order of calling destructor but i couldn't figure out where it occurred.

try to check allocated memory(reverse called order)
processing without destructor method(it works)

main.cpp

```<code>    void main() {
        MyString a = MyString("HELLOMYNAMEIS");
        char ab[10] = "thisiskrw";
        MyString c = ab;
        a = a + c;
        cout << a;
}
</code>```

MyString.cpp

```<code>MyString::~MyString() {
    delete[] str_;
}

MyString operator+(const MyString& lhs, const MyString& rhs) {
    MyString a(lhs);
    MyString b(rhs);
    a += b;
    cout << a;
    return a;
}

MyString& MyString::operator+=(const MyString& str) {
    int i = 0;
    if (this->capacity() < (this->length_ + str.length_)) {
        char* temp = new char[this->length_ + str.length_+1];
        memset(temp, '\0', this->length_+str.length_+1);
        strcpy(temp, this->str_);
        for (int i = 0; i < str.length_; i++) {
            temp[(this->length_) + i] = str.str_[i];
        }
        temp[this->length_ + str.length_] = '\0';
        strcpy(this->str_,temp);
        this->length_ = this->length_ + str.length_;
        delete[] temp;
    }
    else {
        for (int i = 0; i < str.length_; i++) {
            this->str_[(this->length_) + i] = str.str_[i];
        }
        this->length_ = this->length_ + str.length_;
    }
    return *this;
}
</code>```

it will print string inside MyString object.

答:
You forgot to write this->str_ = temp; anywhere. You just try to write the longer string into the shorter space.

```<code>strcpy(this->str_,temp);
this->length_ = this->length_ + str.length_;
delete[] temp;
</code>```

Should be

```<code>delete [] this->str_;
this->str_ = temp;
</code>```

Body:
it's course's one of project and its goal is to make fully-worked MyString Class. Until made destructor method, it was worked well. but in main.cpp, when i tried to use these method i made, it occurs heap corruption. i thought the problem comes up from order of calling destructor but i couldn't figure out where it occurred.

try to check allocated memory(reverse called order)
processing without destructor method(it works)

main.cpp

    void main() {
        MyString a = MyString("HELLOMYNAMEIS");
        char ab[10] = "thisiskrw";
        MyString c = ab;
        a = a + c;
        cout << a;
}

MyString.cpp

MyString::~MyString() {
    delete[] str_;
}

MyString operator+(const MyString& lhs, const MyString& rhs) {
    MyString a(lhs);
    MyString b(rhs);
    a += b;
    cout <capacity() < (this->length_ + str.length_)) {
        char* temp = new char[this->length_ + str.length_+1];
        memset(temp, '\0', this->length_+str.length_+1);
        strcpy(temp, this->str_);
        for (int i = 0; i < str.length_; i++) {
            temp[(this->length_) + i] = str.str_[i];
        }
        temp[this->length_ + str.length_] = '\0';
        strcpy(this->str_,temp);
        this->length_ = this->length_ + str.length_;
        delete[] temp;
    }
    else {
        for (int i = 0; i < str.length_; i++) {
            this->str_[(this->length_) + i] = str.str_[i];
        }
        this->length_ = this->length_ + str.length_;
    }
    return *this;
}

it will print string inside MyString object.

Body:
You forgot to write this->str_ = temp; anywhere. You just try to write the longer string into the shorter space.

strcpy(this->str_,temp);
this->length_ = this->length_ + str.length_;
delete[] temp;

Should be

delete [] this->str_;
this->str_ = temp;


问:
How to check if a string is in a list of strings?
In Python, doing if a in b is really easy, and I'm wondering if there's an equivalent in C++.

Specifically, I want to make a list of strings and check if an input is in that list.

```<code>std::string myinput;
std::string mylist[] = {"a", "b", "c"};
std::cin >> myinput;
// if myinput is included in mylist
// do other stuff here
</code>```

How do I check using an if whether the input myinput is included in string mylist?

答:
You can also use std::count

```<code>#include <iostream>
#include <algorithm>  // std::count
#include <vector>

//using namespace std;

int main() {
    std::vector<std::string> ans = {"a", "b", "c", "a"};
    std::cout << count(ans.begin(), ans.end(), "a") << std::endl;
    return 0;
}
</code>```

if the number > 0, it means the string is in strings.

Body:
In Python, doing if a in b is really easy, and I'm wondering if there's an equivalent in C++.

Specifically, I want to make a list of strings and check if an input is in that list.

std::string myinput;
std::string mylist[] = {"a", "b", "c"};
std::cin >> myinput;
// if myinput is included in mylist
// do other stuff here

How do I check using an if whether the input myinput is included in string mylist?

Body:
You can also use std::count

#include <iostream>
#include <algorithm>  // std::count
#include <vector>

//using namespace std;

int main() {
    std::vector<std::string> ans = {"a", "b", "c", "a"};
    std::cout << count(ans.begin(), ans.end(), "a") << std::endl;
    return 0;
}

if the number > 0, it means the string is in strings.


问:
DbSet<xxx>' does not contain a definition for 'Update' and no accessible extension method 'Update'
here is my code block

```<code> foreach(var n in animalbirdAdoptionDetails)
 {
    int animalBirdsId = n.AnimalsAndBirdsId;
    int NoAnimal =  Convert.ToInt32(n.NoAnimalsAdopted);
    n.isActive = false;
    context.NameOfAnimalsAndBirds.Update(e2 => new entity
                     {
                         quantity = e2.quantity + moreQuantity
                     });
    context.SaveChanges();

  }

</code>```

DbSet' does not contain a definition for 'Update' and no accessible extension method 'Update' accepting a first argument of type 'DbSet' could be found (are you missing a using directive or an assembly reference?)

答:
```<code>foreach(var n in animalbirdAdoptionDetails)
{
   int animalBirdsId = n.AnimalsAndBirdsId;
   int NoAnimal =  Convert.ToInt32( n.NoAnimalsAdopted);
   n.isActive = false;

   // Retrieve existing record into your model class
   NameOfAnimalsAndBird model = context.NameOfAnimalsAndBirds.Find(n.Id);

    model.quantity = model.quantity + moreQuantity;
    context.SaveChanges();
}
</code>```

Body:
here is my code block

 foreach(var n in animalbirdAdoptionDetails)
 {
    int animalBirdsId = n.AnimalsAndBirdsId;
    int NoAnimal =  Convert.ToInt32(n.NoAnimalsAdopted);
    n.isActive = false;
    context.NameOfAnimalsAndBirds.Update(e2 => new entity
                     {
                         quantity = e2.quantity + moreQuantity
                     });
    context.SaveChanges();

  }

DbSet' does not contain a definition for 'Update' and no accessible extension method 'Update' accepting a first argument of type 'DbSet' could be found (are you missing a using directive or an assembly reference?)


问:
How create a single dropdrown and place it on every page?
I'mworking on a website and requirement is that to "create a single dropdown that contains the time zone info . and place it on everypage?
How could i do it?

This is for the development of a dropdown list in asp.net c# language.

I dont want to repeat code on everypage of dropdown list i just want to use my previous code of dropdown list like "include" in php .

答:
Use a Layout when creating another view or you can add & edit the _Layout.cshtml in the Shared Folder under Views and inherit it to every views that you create by ticking the "Use a Layout Page" upon adding the views.

See this link for reference:
https://www.c-sharpcorner.com/UploadFile/4b0136/getting-started-with-view-in-mvc-5/