问:
Changing imageview present in recently clicked listitem in android ListView
Here I am trying to make a music streaming app which works using an API, and I have utilized the MusicPlayer class available in Android. Here what I am trying to do is to get the response from the API in a listview and then click on any item in the listview to stream that particular song. The songs are present on a server and I am getting the correct responses from the server and music streaming is also implemented correctly according to me. The music progress is shown with the help of a SeekBar and I am 100% sure it is also working as I wanted it to be.

The new thing which I added to it recently is that, whenever I click on a particular song item from list, the headphone icon present on left of that item changes to play icon as shown in the screenshot attached below

Screenshot of the app from my phone

Here, play icon on left of songs show that they are recently played, but I want play icon only on those songs which is currently playing, not on recently played songs too.

But I cannot figure out way to do this, I have tried some things like

Storing the clicked item position somewhere in the class, to use it later.

Searching on internet, a way to modify only those list item which are not clicked in listview.

Modifying the image resource of the  recently clicked item when stop icon is clicked.

But 3rd one didn't work, and haven't found a way to achieve the 1st and 2nd one..

Code snippet of ListView implementation

```<code>        CustomSongList adapter = new CustomSongList(Songs.this, songdetails);
        list = (ListView) findViewById(R.id.list);

        list.setAdapter(adapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                url = songdetails.get(position).getUrl(); // your URl
                pos = position;
                ImageView listenImage = (ImageView) view.findViewById(R.id.musicicon);
                listenImage.setImageResource(R.drawable.play);   /* I am changing icon from headphone icon to play icon here*/

                if (mediaPlayer != null) {
                    mediaPlayer.stop();
                }

                mediaPlayer = new MediaPlayer();
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                try {
                    mediaPlayer.setDataSource(url);
                    mediaPlayer.prepare();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                mediaFileLengthInMilliseconds = mediaPlayer.getDuration();// gets the song length in milliseconds from URL
                mediaPlayer.start();
                imPlay.setVisibility(View.INVISIBLE);
                imPause.setVisibility(View.VISIBLE);
                primarySeekBarProgressUpdater();
            }
        });
</code>```

Here is a code snippet of ListView Adapter class.

```<code>public View getView(int position, View view, ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();

    View rowView = inflater.inflate(R.layout.songlist_item, null, true);

    TextView Title = (TextView) rowView.findViewById(R.id.title);
    TextView Singer = (TextView) rowView.findViewById(R.id.singer);
    TextView Duration = (TextView) rowView.findViewById(R.id.duration);

    Title.setText(songlist.get(position).getTitle());
    Singer.setText("Singer : " + songlist.get(position).getSinger());
    Duration.setText("Duration : " + songlist.get(position).getDuration()+" mins");
    return rowView;
}
</code>```

And this is the snippet of songs layout file

```<code><ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/seekBar"
    android:layout_below="@+id/songheading"
    android:layout_margin="10dp"
    android:background="@android:color/transparent"
    android:cacheColorHint="@android:color/transparent"
    android:divider="@drawable/transperent_color"
    android:dividerHeight="5dip" />

<SeekBar
    android:id="@+id/seekBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/buttonPlay" />

<ImageView
    android:id="@+id/buttonPlay"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:background="@drawable/play" />

<ImageView
    android:id="@+id/buttonPause"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:background="@drawable/pause" />

<ImageView
    android:id="@+id/buttonStop"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentEnd="true"
    android:background="@drawable/stop" />
</code>```

The headphone icon set for each item of listview is done by following code snippet

```<code> <ImageView
    android:id="@+id/musicicon"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:contentDescription="@string/app_name"
    android:gravity="center"
    android:layout_marginTop="10dp"
    android:src="@drawable/listen_icon" />
</code>```

Edit

Applied the solution given by @KalaBalik

thanks @KalaBalik for posting the steps to mark the song, but I have applied your steps step by step, and what I found is that my app now doesn't show the list itself, when loading is complete, here is the screenshot

And here are the edits performed by me on the code as you said

Code snippet of listview

```<code><ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/seekBar"
    android:layout_below="@+id/songheading"
    android:layout_margin="10dp"
    android:background="@android:color/transparent"
    android:cacheColorHint="@android:color/transparent"
    android:choiceMode="singleChoice"                       // -----here
    android:divider="@drawable/transperent_color"
    android:dividerHeight="5dip" />
</code>```

CheckedTextView implementation

```<code><CheckedTextView
        android:id="@+id/tvChecked"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:drawableStart="@drawable/playing" />
</code>```

Compound drawable for checkedTextview,

playing.xml

```<code><selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/play" android:state_checked="true" />
<item android:drawable="@drawable/listen_icon" />
</code>```

SpannableStringBuilder implementation

```<code>String finalString = title + "\n" + singer + "\n" + duration;
    SpannableStringBuilder sb = new SpannableStringBuilder();
    Typeface exoMedium = Typeface.createFromAsset(context.getAssets(), "fonts/Exo-Medium.ttf");
    TypefaceSpan exoMediumSpan = new CustomTypeFaceSpan("", exoMedium);
    sb.setSpan(exoMediumSpan, finalString.indexOf(title), title.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    sb.setSpan(new ForegroundColorSpan(Color.BLUE), finalString.indexOf(singer), singer.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    sb.setSpan(new ForegroundColorSpan(Color.CYAN), finalString.indexOf(duration), duration.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
</code>```

I have created a CustomTypeFaceSpan using this link

setting SpannableStringBuilder in checkedTextView  holder.checkedTextView.setText(sb);  here I Used ViewHolder pattern

and setting listview checked true when item clicked

```<code>list.setAdapter(adapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                list.setItemChecked(position, true);
</code>```

But result is in the screenshot above, tell me where I have done something wrong.

答:
What you need is to somehow mark or "check" the song currently playing. This can be done with a CheckedTextView, for example.

Put this in your ListView XML:                 android:choiceMode="singleChoice"

Inside your ListItem XML, I recommend having only one CheckedTextView. You can still do your formatting by (a) using a compound drawable for your image (for example: android:drawableStart="@drawable/playing") and (b) setting the text to a String from a SpannableStringBuilder programmatically. That way you can have different font sizes, styles and colors within one string which you put in the (one) CheckedTextView. In theory, you can have more complex listItem layouts, but it gets complicated quickly.

In your listener, you simply check the item at the current position, like so: list.setItemChecked(position, true);

Now that (after initialising) you always have one and just one checked list item, all you have to do is react to it. You can do so with a state list on the compound drawable. This state list would hold instructions about when (under which state: checked or not) one or the other drawable will be shown.

In order for the ListView to run efficient it is recommended (but not necessary) to implement the ViewHolder pattern, like so:

Inside the adapter:

```<code>@Override
public View getView(int position, View convertView, ViewGroup parent) {
    final ViewHolder viewHolder;
    if (convertView == null) {
        convertView = inflater.inflate(R.layout.list_item, parent, false);
        viewHolder = new ViewHolder(convertView);
        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }
    viewHolder.checkedTextView.setText(filteredList.get(position));
    return convertView;
}

static class ViewHolder {
    final CheckedTextView checkedTextView;

    private ViewHolder(View convertView) {
        checkedTextView = (CheckedTextView) convertView.findViewById(R.id.listentry);
    }
}
</code>```

Body:
Here I am trying to make a music streaming app which works using an API, and I have utilized the MusicPlayer class available in Android. Here what I am trying to do is to get the response from the API in a listview and then click on any item in the listview to stream that particular song. The songs are present on a server and I am getting the correct responses from the server and music streaming is also implemented correctly according to me. The music progress is shown with the help of a SeekBar and I am 100% sure it is also working as I wanted it to be.

The new thing which I added to it recently is that, whenever I click on a particular song item from list, the headphone icon present on left of that item changes to play icon as shown in the screenshot attached below

Screenshot of the app from my phone

Here, play icon on left of songs show that they are recently played, but I want play icon only on those songs which is currently playing, not on recently played songs too.

But I cannot figure out way to do this, I have tried some things like

Storing the clicked item position somewhere in the class, to use it later.

Searching on internet, a way to modify only those list item which are not clicked in listview.

Modifying the image resource of the  recently clicked item when stop icon is clicked.

But 3rd one didn't work, and haven't found a way to achieve the 1st and 2nd one..

Code snippet of ListView implementation

        CustomSongList adapter = new CustomSongList(Songs.this, songdetails);
        list = (ListView) findViewById(R.id.list);

        list.setAdapter(adapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                url = songdetails.get(position).getUrl(); // your URl
                pos = position;
                ImageView listenImage = (ImageView) view.findViewById(R.id.musicicon);
                listenImage.setImageResource(R.drawable.play);   /* I am changing icon from headphone icon to play icon here*/

                if (mediaPlayer != null) {
                    mediaPlayer.stop();
                }

                mediaPlayer = new MediaPlayer();
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                try {
                    mediaPlayer.setDataSource(url);
                    mediaPlayer.prepare();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                mediaFileLengthInMilliseconds = mediaPlayer.getDuration();// gets the song length in milliseconds from URL
                mediaPlayer.start();
                imPlay.setVisibility(View.INVISIBLE);
                imPause.setVisibility(View.VISIBLE);
                primarySeekBarProgressUpdater();
            }
        });

Here is a code snippet of ListView Adapter class.

public View getView(int position, View view, ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();

    View rowView = inflater.inflate(R.layout.songlist_item, null, true);

    TextView Title = (TextView) rowView.findViewById(R.id.title);
    TextView Singer = (TextView) rowView.findViewById(R.id.singer);
    TextView Duration = (TextView) rowView.findViewById(R.id.duration);

    Title.setText(songlist.get(position).getTitle());
    Singer.setText("Singer : " + songlist.get(position).getSinger());
    Duration.setText("Duration : " + songlist.get(position).getDuration()+" mins");
    return rowView;
}

And this is the snippet of songs layout file

<ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/seekBar"
    android:layout_below="@+id/songheading"
    android:layout_margin="10dp"
    android:background="@android:color/transparent"
    android:cacheColorHint="@android:color/transparent"
    android:divider="@drawable/transperent_color"
    android:dividerHeight="5dip" />

<SeekBar
    android:id="@+id/seekBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/buttonPlay" />

<ImageView
    android:id="@+id/buttonPlay"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:background="@drawable/play" />

<ImageView
    android:id="@+id/buttonPause"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:background="@drawable/pause" />

<ImageView
    android:id="@+id/buttonStop"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentEnd="true"
    android:background="@drawable/stop" />

The headphone icon set for each item of listview is done by following code snippet

 <ImageView
    android:id="@+id/musicicon"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:contentDescription="@string/app_name"
    android:gravity="center"
    android:layout_marginTop="10dp"
    android:src="@drawable/listen_icon" />

Edit

Applied the solution given by @KalaBalik

thanks @KalaBalik for posting the steps to mark the song, but I have applied your steps step by step, and what I found is that my app now doesn't show the list itself, when loading is complete, here is the screenshot

And here are the edits performed by me on the code as you said

Code snippet of listview

<ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/seekBar"
    android:layout_below="@+id/songheading"
    android:layout_margin="10dp"
    android:background="@android:color/transparent"
    android:cacheColorHint="@android:color/transparent"
    android:choiceMode="singleChoice"                       // -----here
    android:divider="@drawable/transperent_color"
    android:dividerHeight="5dip" />

CheckedTextView implementation

<CheckedTextView
        android:id="@+id/tvChecked"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:drawableStart="@drawable/playing" />

Compound drawable for checkedTextview,

playing.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/play" android:state_checked="true" />
<item android:drawable="@drawable/listen_icon" />

SpannableStringBuilder implementation

String finalString = title + "\n" + singer + "\n" + duration;
    SpannableStringBuilder sb = new SpannableStringBuilder();
    Typeface exoMedium = Typeface.createFromAsset(context.getAssets(), "fonts/Exo-Medium.ttf");
    TypefaceSpan exoMediumSpan = new CustomTypeFaceSpan("", exoMedium);
    sb.setSpan(exoMediumSpan, finalString.indexOf(title), title.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    sb.setSpan(new ForegroundColorSpan(Color.BLUE), finalString.indexOf(singer), singer.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    sb.setSpan(new ForegroundColorSpan(Color.CYAN), finalString.indexOf(duration), duration.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

I have created a CustomTypeFaceSpan using this link

setting SpannableStringBuilder in checkedTextView  holder.checkedTextView.setText(sb);  here I Used ViewHolder pattern

and setting listview checked true when item clicked

list.setAdapter(adapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                list.setItemChecked(position, true);

But result is in the screenshot above, tell me where I have done something wrong.

Body:
What you need is to somehow mark or "check" the song currently playing. This can be done with a CheckedTextView, for example.

Put this in your ListView XML:                 android:choiceMode="singleChoice"

Inside your ListItem XML, I recommend having only one CheckedTextView. You can still do your formatting by (a) using a compound drawable for your image (for example: android:drawableStart="@drawable/playing") and (b) setting the text to a String from a SpannableStringBuilder programmatically. That way you can have different font sizes, styles and colors within one string which you put in the (one) CheckedTextView. In theory, you can have more complex listItem layouts, but it gets complicated quickly.

In your listener, you simply check the item at the current position, like so: list.setItemChecked(position, true);

Now that (after initialising) you always have one and just one checked list item, all you have to do is react to it. You can do so with a state list on the compound drawable. This state list would hold instructions about when (under which state: checked or not) one or the other drawable will be shown.

In order for the ListView to run efficient it is recommended (but not necessary) to implement the ViewHolder pattern, like so:

Inside the adapter:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    final ViewHolder viewHolder;
    if (convertView == null) {
        convertView = inflater.inflate(R.layout.list_item, parent, false);
        viewHolder = new ViewHolder(convertView);
        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }
    viewHolder.checkedTextView.setText(filteredList.get(position));
    return convertView;
}

static class ViewHolder {
    final CheckedTextView checkedTextView;

    private ViewHolder(View convertView) {
        checkedTextView = (CheckedTextView) convertView.findViewById(R.id.listentry);
    }
}


来源: stackexchange

问:
Result of GAMMA underflows its kind
I would like to calculate gamma(-170.1) using the program below:

```<code>program arithmetic
! program to do a calculation
real(8) :: x
x = GAMMA(-170.1)
print *, x
end program
</code>```

but I get the error:

test.f95:4.10:

x = GAMMA(-170.1)
           1
  Error: Result of GAMMA underflows its kind at (1)

when I compile with gfortran. According to Maple gamma(-170.1) = 5.191963205*10^(-172) which I think should be within the range of the exponent of the variable x as I've defined it.

答: -170.0 may be treated as a float.  If so, changing it to a double should resolve the issue.</p>

ContentLicense: CC BY-SA 3.0

Title: Result of GAMMA underflows its kind

Body:
I would like to calculate gamma(-170.1) using the program below:

program arithmetic
! program to do a calculation
real(8) :: x
x = GAMMA(-170.1)
print *, x
end program

but I get the error:

test.f95:4.10:

x = GAMMA(-170.1)
           1
  Error: Result of GAMMA underflows its kind at (1)

when I compile with gfortran. According to Maple gamma(-170.1) = 5.191963205*10^(-172) which I think should be within the range of the exponent of the variable x as I've defined it.

ContentLicense: CC BY-SA 2.5


问:
firefox developer tools compare to firebug / missing preview for ajax response
i know this question might get voted down and be closed but i have to put it out there

im windows user and i got familiar with firefox in the bad old days of IE reign
i love firefox specially after i become a web developer and started to work with wonderful add-ons

but recent changes has made me to move to chrome more and more every day specifically i have to mention death of beloved firebug

i hate the firefox developer console , it feels awkward and clunky and primitive compare to firebug  and its not as user friendly as firebug

i have to ask , is it me or anyone else feels the same ?  cuz i've searched around and it doesn't seem to bother anyone else !

here is what bothers me the most .... modern web apps rely heavily on ajax calls , for some reason i cant find preview for ajax calls response in the firefox developer tools ... i can see server response as code but not rendered preview of server response

and i say i cant find it becuz i cant imagine possibility of not having preview .... just imagine your using a framework and it returns a stack error with lots of html/css style , its impossible to find the actual error among the heap of codes in developer tools response section

so aside from the rant  , basically  im hoping someone to say there is a preview  and this is how you can activated  it !

答:
Unfortunately, the preview for responses got removed in Firefox 55, obviously under the incorrect assumption that it duplicated some other UI.
Luckily it was added back for Firefox 59, now placed within the Response panel.

Here's a screenshot for how this looks like on this page:


问:
Multiple-target cross-browser drag& drop file upload
We're investigating if it's possible to have the following: A webpage with multiple 'folders' to which a user can drag & drop a files. It's meant to be used as an interface to upload scanned documents to an archive.

For example, we would have page that states: 'Quotes', 'Invoices' & 'Misc'. Depending on the sort of document the user would drag & drop the file from the local file system to one of these three folders. It should then upload the file to the correct folder on the web server.

Is this possible, and if it is, any existing solutions using ASP.NET?

答:
You can use modern browsers HTML5 functionalities to do so. A detailed explanation here:
http://www.useragentman.com/blog/2010/01/10/cross-browser-html5-drag-and-drop/
There is also the jQuery plugin: https://github.com/weixiyen/jquery-filedrop This one is a bit bogus (truncates files with accents like in french, doesn't handle correctly several drop areas in the same page, ...), but are easy to fix (I sent a fixed version to the author weeks ago, but didn't get any feedback...)
With some Ajax and the correct server-side solution, it works like a charm. I don't know any .NET solution, though.
Best,</p>


问:
Visual Studio 2015 crash when open any file in editor
I have some problem with VS2015: when I open any project and try to open a file for editing - VS2015 crashes. I try reinstall, all /commands and more.

ActivityLog.xml:

```<code>  <entry>
    <record>430</record>
    <time>2015/11/03 14:46:35.669</time>
    <type>Error</type>
    <source>Editor or Editor Extension</source>
    <description>System.IO.FileFormatException: Input file or data stream does not conform to the expected file format specification. ---> System.IO.FileFormatException: Input file or data stream does not conform to the expected file format specification.
   at MS.Internal.Text.TextInterface.Native.Util.ConvertHresultToException(Int32 hr)
   at MS.Internal.Text.TextInterface.Font.CreateFontFace()
   at MS.Internal.Text.TextInterface.Font.AddFontFaceToCache()
   at MS.Internal.Text.TextInterface.Font.GetFontFace()
   at System.Windows.Media.GlyphTypeface..ctor(Font font)
   at MS.Internal.FontFace.PhysicalFontFamily.GetGlyphTypeface(FontStyle style, FontWeight weight, FontStretch stretch)
   at MS.Internal.FontFace.PhysicalFontFamily.MS.Internal.FontFace.IFontFamily.GetTypefaceMetrics(FontStyle style, FontWeight weight, FontStretch stretch)
   at System.Windows.Media.Typeface.ConstructCachedTypeface()
   at System.Windows.Media.Typeface.get_CachedTypeface()
   at System.Windows.Media.Typeface.get_Symbol()
   at MS.Internal.TextFormatting.TextStore.FetchTextRun(Int32 cpFetch)
   at MS.Internal.TextFormatting.TextStore.FetchLSRun(Int32 lscpFetch, TextFormattingMode textFormattingMode, Boolean isSideways, Plsrun& plsrun, Int32& lsrunOffset, Int32& lsrunLength)
   at MS.Internal.TextFormatting.LineServicesCallbacks.FetchRunRedefined(IntPtr pols, Int32 lscpFetch, Int32 fIsStyle, IntPtr pstyle, Char* pwchTextBuffer, Int32 cchTextBuffer, Int32& fIsBufferUsed, Char*& pwchText, Int32& cchText, Int32& fIsHidden, LsChp& lschp, IntPtr& lsplsrun)
   --- End of inner exception stack trace ---
   at MS.Internal.TextFormatting.TextMetrics.FullTextLine.FormatLine(FullTextState fullText, Int32 cpFirst, Int32 lineLength, Int32 formatWidth, Int32 finiteFormatWidth, Int32 paragraphWidth, LineFlags lineFlags, FormattedTextSymbols collapsingSymbol)
   at MS.Internal.TextFormatting.TextFormatterImp.FormatLineInternal(TextSource textSource, Int32 firstCharIndex, Int32 lineLength, Double paragraphWidth, TextParagraphProperties paragraphProperties, TextLineBreak previousLineBreak, TextRunCache textRunCache)
   at MS.Internal.TextFormatting.TextFormatterImp.FormatLine(TextSource textSource, Int32 firstCharIndex, Double paragraphWidth, TextParagraphProperties paragraphProperties, TextLineBreak previousLineBreak)
   at System.Windows.Media.FormattedText.LineEnumerator.FormatLine(TextSource textSource, Int32 textSourcePosition, Double maxLineLength, TextParagraphProperties paraProps, TextLineBreak lineBreak)
   at System.Windows.Media.FormattedText.LineEnumerator.MoveNext()
   at System.Windows.Media.FormattedText.DrawAndCalculateMetrics(DrawingContext dc, Point drawingOffset, Boolean getBlackBoxMetrics)
   at System.Windows.Media.FormattedText.get_Metrics()
   at Microsoft.VisualStudio.Language.Intellisense.Implementation.CodeLensInterLineAdornmentTaggerProvider.TextFormatCache.UpdateTextHeight()
   at Microsoft.VisualStudio.Language.Intellisense.Implementation.CodeLensInterLineAdornmentTaggerProvider.TextFormatCache.EnsureInitialized()
   at Microsoft.VisualStudio.Language.Intellisense.Implementation.CodeLensInterLineAdornmentTaggerProvider.CodeLensInterLineAdornmentTagger.GetTags(NormalizedSnapshotSpanCollection spans)
   at Microsoft.VisualStudio.Text.Tagging.Implementation.TagAggregator`1.<GetTagsForBuffer>d__38.MoveNext()</description>
  </entry>
</code>```

I found a problem. CodeLens broken. If I turn it off, then it works. How i can fix CodeLens? a problem in the font (ActivityLog.txt show some methods with font)?

答:
I encountered a similar problem.Use wpf program, if you install an illegal font, use the font error, when we select font using the property box,every font will be used, so an error occurs.

I found the problem in the environment:

win7 32(x86)

.net4.5

wpf

Hope someone can completely solve.

Body:
I have some problem with VS2015: when I open any project and try to open a file for editing - VS2015 crashes. I try reinstall, all /commands and more.

ActivityLog.xml:

  <entry>
    <record>430</record>
    <time>2015/11/03 14:46:35.669</time>
    <type>Error</type>
    <source>Editor or Editor Extension</source>
    <description>System.IO.FileFormatException: Input file or data stream does not conform to the expected file format specification. ---> System.IO.FileFormatException: Input file or data stream does not conform to the expected file format specification.
   at MS.Internal.Text.TextInterface.Native.Util.ConvertHresultToException(Int32 hr)
   at MS.Internal.Text.TextInterface.Font.CreateFontFace()
   at MS.Internal.Text.TextInterface.Font.AddFontFaceToCache()
   at MS.Internal.Text.TextInterface.Font.GetFontFace()
   at System.Windows.Media.GlyphTypeface..ctor(Font font)
   at MS.Internal.FontFace.PhysicalFontFamily.GetGlyphTypeface(FontStyle style, FontWeight weight, FontStretch stretch)
   at MS.Internal.FontFace.PhysicalFontFamily.MS.Internal.FontFace.IFontFamily.GetTypefaceMetrics(FontStyle style, FontWeight weight, FontStretch stretch)
   at System.Windows.Media.Typeface.ConstructCachedTypeface()
   at System.Windows.Media.Typeface.get_CachedTypeface()
   at System.Windows.Media.Typeface.get_Symbol()
   at MS.Internal.TextFormatting.TextStore.FetchTextRun(Int32 cpFetch)
   at MS.Internal.TextFormatting.TextStore.FetchLSRun(Int32 lscpFetch, TextFormattingMode textFormattingMode, Boolean isSideways, Plsrun& plsrun, Int32& lsrunOffset, Int32& lsrunLength)
   at MS.Internal.TextFormatting.LineServicesCallbacks.FetchRunRedefined(IntPtr pols, Int32 lscpFetch, Int32 fIsStyle, IntPtr pstyle, Char* pwchTextBuffer, Int32 cchTextBuffer, Int32& fIsBufferUsed, Char*& pwchText, Int32& cchText, Int32& fIsHidden, LsChp& lschp, IntPtr& lsplsrun)
   --- End of inner exception stack trace ---
   at MS.Internal.TextFormatting.TextMetrics.FullTextLine.FormatLine(FullTextState fullText, Int32 cpFirst, Int32 lineLength, Int32 formatWidth, Int32 finiteFormatWidth, Int32 paragraphWidth, LineFlags lineFlags, FormattedTextSymbols collapsingSymbol)
   at MS.Internal.TextFormatting.TextFormatterImp.FormatLineInternal(TextSource textSource, Int32 firstCharIndex, Int32 lineLength, Double paragraphWidth, TextParagraphProperties paragraphProperties, TextLineBreak previousLineBreak, TextRunCache textRunCache)
   at MS.Internal.TextFormatting.TextFormatterImp.FormatLine(TextSource textSource, Int32 firstCharIndex, Double paragraphWidth, TextParagraphProperties paragraphProperties, TextLineBreak previousLineBreak)
   at System.Windows.Media.FormattedText.LineEnumerator.FormatLine(TextSource textSource, Int32 textSourcePosition, Double maxLineLength, TextParagraphProperties paraProps, TextLineBreak lineBreak)
   at System.Windows.Media.FormattedText.LineEnumerator.MoveNext()
   at System.Windows.Media.FormattedText.DrawAndCalculateMetrics(DrawingContext dc, Point drawingOffset, Boolean getBlackBoxMetrics)
   at System.Windows.Media.FormattedText.get_Metrics()
   at Microsoft.VisualStudio.Language.Intellisense.Implementation.CodeLensInterLineAdornmentTaggerProvider.TextFormatCache.UpdateTextHeight()
   at Microsoft.VisualStudio.Language.Intellisense.Implementation.CodeLensInterLineAdornmentTaggerProvider.TextFormatCache.EnsureInitialized()
   at Microsoft.VisualStudio.Language.Intellisense.Implementation.CodeLensInterLineAdornmentTaggerProvider.CodeLensInterLineAdornmentTagger.GetTags(NormalizedSnapshotSpanCollection spans)
   at Microsoft.VisualStudio.Text.Tagging.Implementation.TagAggregator`1.<GetTagsForBuffer>d__38.MoveNext()</description>
  </entry>

I found a problem. CodeLens broken. If I turn it off, then it works. How i can fix CodeLens? a problem in the font (ActivityLog.txt show some methods with font)?


问:
Dynamic id with ng-repeat
I'm working with AngularJS and I have a form with checkboxes that I generate with ng-repeat. I want to generate the id of each checkbox dynamically, I tried to do it like this:

```<code><label ng-repeat="x in placeTypes">

    <input type="checkbox" id='{{x.value}}'>
    {{x.display}}
    <br>
</label>
</code>```

But when I try to get the element by Id the element is null.

答:
Here is a working example, https://plnkr.co/edit/mMzNGsEajOxY7TyiHArL?p=preview </p>

```<code>angular.module('app', [])
  .component('app', {
    template: `<label ng-repeat="x in $ctrl.placeTypes">

    <input type="checkbox" id='input-{{x.value}}' component-did-mount>
    {{x.display}}
    <br>
</label>`,
    controller: function($scope) {
      this.$onInit = () => {
        this.placeTypes = [{
          value: '1',
          display: 'hello'
        }, {
          value: '2',
          display: 'hello world'
        }]
        $scope.$on('componentDidMount', () => {
          const $el = document.getElementById('input-1');
          console.log('$el >>', $el);
        })
      }
    }
  }).directive('componentDidMount', ['$timeout', ($timeout) => {
    var def = {
      restrict: 'A',
      transclude: false,
      link: (scope, element, attrs) => {
        $timeout(() => {
          scope.$emit('componentDidMount')
        });
      }
    };
    return def;
  }]);

angular.element(document).ready(() => {
  const bootstrapAngular = () => angular.bootstrap(document.body, ['app'], {});
  bootstrapAngular();
});
</code>```

Title: Dynamic id with ng-repeat

Body:
I'm working with AngularJS and I have a form with checkboxes that I generate with ng-repeat. I want to generate the id of each checkbox dynamically, I tried to do it like this:

    <input type="checkbox" id='{{x.value}}'>
    {{x.display}}

But when I try to get the element by Id the element is null.

Body:
Here is a working example, https://plnkr.co/edit/mMzNGsEajOxY7TyiHArL?p=preview

angular.module('app', [])
  .component('app', {
    template: `<label ng-repeat="x in $ctrl.placeTypes">

    <input type="checkbox" id='input-{{x.value}}' component-did-mount>
    {{x.display}}
    <br>
</label>`,
    controller: function($scope) {
      this.$onInit = () => {
        this.placeTypes = [{
          value: '1',
          display: 'hello'
        }, {
          value: '2',
          display: 'hello world'
        }]
        $scope.$on('componentDidMount', () => {
          const $el = document.getElementById('input-1');
          console.log('$el >>', $el);
        })
      }
    }
  }).directive('componentDidMount', ['$timeout', ($timeout) => {
    var def = {
      restrict: 'A',
      transclude: false,
      link: (scope, element, attrs) => {
        $timeout(() => {
          scope.$emit('componentDidMount')
        });
      }
    };
    return def;
  }]);

angular.element(document).ready(() => {
  const bootstrapAngular = () => angular.bootstrap(document.body, ['app'], {});
  bootstrapAngular();
});


问:
Which is a better js coding practice?
I need to send api calls to get data from multiple sources.The data that I get are in different format (arrays, objects,nested arrays). One thing I feel good about is to have an function that extract the parts I need from for me.

Now I wonder if I should have this extraction function or simply just extract the data I need when I use it.(Simply put : which one is a better practice?)

I personally prefer the latter one because I will not need to go back and forth to make sure which part of data I need to extract.
Eg.

Inline extraction

```<code>const  data = get("example.com").data[0].Users;
</code>```

Use function to extract data

```<code>const data = getData("example.com";

const getData = async(url)=>{
   const rawData= await get(url);
   switch(url){
    case EXAMPLE_URL:
      return rawData.data[0].Users;
    case OTHER_EXAMPLE_URL:
      return rawData.data;
    case  OTHER_URL:
     return rawData.data[0].Enum;

}
}
</code>```

答:
One core idea you should aim to is a function should only do one thing, but be very darn good at it, so don't aim for 'one func to rule them all.' solution.

In your case, you're looking for three things in two task, fetching from url, and extract data from result. I suggest you create function for those

```<code>// Task 1: Fetch URL
const fetchUrl = async () => {
  const response = await fetch('example.com', { ...some options });

  // Do some error checking (just demo code for idea)
  if (response.status === 'error') throw new Error('fethcing Error Message');

  // If no error found, return with response
  return response;
}

// Task 2: extract data
const getUserFromResponse = response => response.data[0].Users;

const getEnumFromResponse = response => response.data[0].Enum;
</code>```

Now you can compose those into your working functions.

```<code>const getUser = async () => {
  try {
    const response = await fetchUrl();
    const user = getUserFromResponse(response);
    return user;
  } catch (e) {
     // do error handling
  }
}

const getEnum = async () => {
  try {
    const response = await fetchUrl();
    const enum = getEnumFromResponse(response);
    return enum;
  } catch (e) {
     // do error handling
  }
}
</code>```

Breaking functions down to a single task will make it easier to create a test case and force you into write more reusable codes too, hope this helps, cheers :)

Title: Which is a better js coding practice?

Body:
I need to send api calls to get data from multiple sources.The data that I get are in different format (arrays, objects,nested arrays). One thing I feel good about is to have an function that extract the parts I need from for me.

Now I wonder if I should have this extraction function or simply just extract the data I need when I use it.(Simply put : which one is a better practice?)

I personally prefer the latter one because I will not need to go back and forth to make sure which part of data I need to extract.
Eg.

Inline extraction

const  data = get("example.com").data[0].Users;

Use function to extract data

const data = getData("example.com";

const getData = async(url)=>{
   const rawData= await get(url);
   switch(url){
    case EXAMPLE_URL:
      return rawData.data[0].Users;
    case OTHER_EXAMPLE_URL:
      return rawData.data;
    case  OTHER_URL:
     return rawData.data[0].Enum;

}
}

Body:
One core idea you should aim to is a function should only do one thing, but be very darn good at it, so don't aim for 'one func to rule them all.' solution.

In your case, you're looking for three things in two task, fetching from url, and extract data from result. I suggest you create function for those

// Task 1: Fetch URL
const fetchUrl = async () => {
  const response = await fetch('example.com', { ...some options });

  // Do some error checking (just demo code for idea)
  if (response.status === 'error') throw new Error('fethcing Error Message');

  // If no error found, return with response
  return response;
}

// Task 2: extract data
const getUserFromResponse = response => response.data[0].Users;

const getEnumFromResponse = response => response.data[0].Enum;

Now you can compose those into your working functions.

const getUser = async () => {
  try {
    const response = await fetchUrl();
    const user = getUserFromResponse(response);
    return user;
  } catch (e) {
     // do error handling
  }
}

const getEnum = async () => {
  try {
    const response = await fetchUrl();
    const enum = getEnumFromResponse(response);
    return enum;
  } catch (e) {
     // do error handling
  }
}

Breaking functions down to a single task will make it easier to create a test case and force you into write more reusable codes too, hope this helps, cheers :)


问:
How can I execute a command inside another folder and return to original directory?
I use this command to make inside a folder:

```<code>cd build/ && make
</code>```

But I want to return to original directory after the command

I tried this:

```<code>cd build/ && make && cd ..
</code>```

But this doesn't work. How can I do it? Would help in quick testing...

答:
Sounds like you want pushd and popd.

The pushd command will push the current directory onto a stack, saving it and allowing you to change to some other directory. The popd command will pop the last saved directory from the stack.

Body:
I use this command to make inside a folder:

cd build/ && make

But I want to return to original directory after the command

I tried this:

cd build/ && make && cd ..

But this doesn't work. How can I do it? Would help in quick testing...


问:
python remove dtype and the end of an array and get list of lists
Does any one know how to convert this array into a python list, my ultimate result should be [[1,2,3],[4,6,8]] . Any suggestion would be greatly appreciated.</p>

```<code>import numpy as np
from numpy import*

a = [array([  1,   2,   3], dtype=int16), array([4, 6, 8],
    dtype=int16)]
</code>```

Body:
Does any one know how to convert this array into a python list, my ultimate result should be [[1,2,3],[4,6,8]] . Any suggestion would be greatly appreciated.

import numpy as np
from numpy import*

a = [array([  1,   2,   3], dtype=int16), array([4, 6, 8],
    dtype=int16)]

Body:
Simply:

x = [list(i) for i in a]

output

[[1, 2, 3], [4, 6, 8]]


答:
Use popd/pushd:</p>

```<code>pushd build ; make ; popd
</code>```

Title: How can I execute a command inside another folder and return to original directory?

Body:
Use popd/pushd:

pushd build ; make ; popd


答:
I would propose the following command:

```<code>cd $DIR && make && cd -;
</code>```

to return to the previous directory after running your make, this work even if the path in $DIR is long.

If you want to go for more sophisticate tools like playing with a stack of accessed directory you can use:

```<code>pushd, popd
</code>```

Usage:

```<code>$ pushd some_directory
It acts as a:
$ cd some_directory
except that some_directory is also added to the stack.
"$ pushd ~/TMP  # we're in ~/
~/TMP ~
$ pushd ~/DATA  # now we're in ~/TMP
~/DATA ~/TMP ~
$ pushd ~  # now we're in ~/DATA
~ ~/DATA ~/TMP ~
$ popd   # now we're in ~/
~/DATA ~/TMP ~
$ popd   # now we're in ~/DATA
~/TMP ~
$ popd   # now we're in ~/TMP
~
$    # now we're in ~/"
</code>```

another very good approach is this function that I really likes:

```<code>"cd_func ()
{
    local x2 the_new_dir adir index;
    local -i cnt;
    if [[ $1 == ""--"" ]]; then
        dirs -v;
        return 0;
    fi;
    the_new_dir=$1;
    [[ -z $1 ]] && the_new_dir=$HOME;
    if [[ ${the_new_dir:0:1} == '-' ]]; then
        index=${the_new_dir:1};
        [[ -z $index ]] && index=1;
        adir=$(dirs +$index);
        [[ -z $adir ]] && return 1;
        the_new_dir=$adir;
    fi;
    [[ ${the_new_dir:0:1} == '~' ]] && the_new_dir=""${HOME}${the_new_dir:1}"";
    pushd ""${the_new_dir}"" > /dev/null;
    [[ $? -ne 0 ]] && return 1;
    the_new_dir=$(pwd);
    popd -n +11 2> /dev/null > /dev/null;
    for ((cnt=1; cnt <= 10; cnt++))
    do
        x2=$(dirs +${cnt} 2>/dev/null);
        [[ $? -ne 0 ]] && return 0;
        [[ ${x2:0:1} == '~' ]] && x2=""${HOME}${x2:1}"";
        if [[ ""${x2}"" == ""${the_new_dir}"" ]]; then
            popd -n +$cnt 2> /dev/null > /dev/null;
            cnt=cnt-1;
        fi;
    done;
    return 0
}"
</code>```

In your profile/bashrc, alias cd to this function:

```<code>alias cd=cd_func
</code>```

and then you can type:

```<code>"$ cd --
 0  ~
 1  ~/DATA
 2  ~/TMP"

to see all the directories you've visited. To go ~/TMP, for example, enter:

$ cd -2
</code>```

Body:
I would propose the following command:

cd $DIR && make && cd -;

to return to the previous directory after running your make, this work even if the path in $DIR is long.

If you want to go for more sophisticate tools like playing with a stack of accessed directory you can use:

pushd, popd

Usage:

$ pushd some_directory
It acts as a:
$ cd some_directory
except that some_directory is also added to the stack.
"$ pushd ~/TMP  # we're in ~/
~/TMP ~
$ pushd ~/DATA  # now we're in ~/TMP
~/DATA ~/TMP ~
$ pushd ~  # now we're in ~/DATA
~ ~/DATA ~/TMP ~
$ popd   # now we're in ~/
~/DATA ~/TMP ~
$ popd   # now we're in ~/DATA
~/TMP ~
$ popd   # now we're in ~/TMP
~
$    # now we're in ~/"

another very good approach is this function that I really likes:

"cd_func ()
{
    local x2 the_new_dir adir index;
    local -i cnt;
    if [[ $1 == ""--"" ]]; then
        dirs -v;
        return 0;
    fi;
    the_new_dir=$1;
    [[ -z $1 ]] && the_new_dir=$HOME;
    if [[ ${the_new_dir:0:1} == '-' ]]; then
        index=${the_new_dir:1};
        [[ -z $index ]] && index=1;
        adir=$(dirs +$index);
        [[ -z $adir ]] && return 1;
        the_new_dir=$adir;
    fi;
    [[ ${the_new_dir:0:1} == '~' ]] && the_new_dir=""${HOME}${the_new_dir:1}"";
    pushd ""${the_new_dir}"" > /dev/null;
    [[ $? -ne 0 ]] && return 1;
    the_new_dir=$(pwd);
    popd -n +11 2> /dev/null > /dev/null;
    for ((cnt=1; cnt <= 10; cnt++))
    do
        x2=$(dirs +${cnt} 2>/dev/null);
        [[ $? -ne 0 ]] && return 0;
        [[ ${x2:0:1} == '~' ]] && x2=""${HOME}${x2:1}"";
        if [[ ""${x2}"" == ""${the_new_dir}"" ]]; then
            popd -n +$cnt 2> /dev/null > /dev/null;
            cnt=cnt-1;
        fi;
    done;
    return 0
}"

In your profile/bashrc, alias cd to this function:

alias cd=cd_func

and then you can type:

"$ cd --
 0  ~
 1  ~/DATA
 2  ~/TMP"

to see all the directories you've visited. To go ~/TMP, for example, enter:

$ cd -2


问:
Google app engine Channel API for COMET on non Javascript clients
How to use Google app engine Channel API for COMET on non JavaScript clients.

I shall be writing a client in python or any other language, and can do HTTP or Socks from client.

How shall I proceed, I want to know what is happening in backed of  JavaScript client?

Is JS using Long Polling or what to talk to GAE server.

答:
Cool,... I found an X-Ray view of "channel api" on the app engine talk og Google I/O
http://www.youtube.com/watch?v=oMXe-xK0BWA

It uses hidden Iframe
http://en.wikipedia.org/wiki/Comet_(programming)#Hidden_iframe

Now i will try to imitate th client in  python or something.


问:
Find a sum with prompt. Stop when user gives -1
Unable to get it to print out the number when the prompt is answered with negative one. It keeps asking for more numbers.

```<code><!DOCTYPE html>
<html>
<body>

<h2>JavaScript Prompt</h2>

<script>
var sum=0;
var number = prompt("Please enter a number:");
while(number>-1)
prompt("Please enter a number:");
sum=number+sum;
if(number=-1) {
document.write(sum);
}
</code>```

答:
You can try this way.

var sum=0;
var number = 0
while(number != -1)
    {
  number = parseInt(prompt("Please enter a number:"));

    if(number==-1)
     document.write(sum);
    else
      sum= number + sum;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
Unable to get it to print out the number when the prompt is answered with negative one. It keeps asking for more numbers.

<!DOCTYPE html>

JavaScript Prompt

Body:
You can try this way.

var sum=0;
var number = 0
while(number != -1)
    {
  number = parseInt(prompt("Please enter a number:"));

    if(number==-1)
     document.write(sum);
    else
      sum= number + sum;
 }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
What is design pattern in front-end development?
I was interviewed and asked this question. I am confused about the "design pattern" in the question. Does it mean the code executive process or the front-page layout of the design? Thanks!</p>

答:
Seems to me the confusion was with front-end (software design context) as front page (graphic design context) .. design pattern... understandable misinterpretation of question.

e.g. the Mediator pattern (in the reference below) could be used (in front-end development) to act as a go-between (i.e. mediate) to facilitate communication/events between children of a user interface host element. Rather than children having to communicate with every other child separately, they all speak only to the host, which controls communication with all children.

See the Software Design Patterns reference: "Design Patterns: Elements of Reusable Object-Oriented Software" -'Gang of Four'

These patterns can be used to design/develop a User Interface, which is 'in front of the user'... so front-end development ...


问:
Javascript function not working when performing actions on a different HTML page
I have a button that if clicked calls a js function that should change the current page and display a simple hello world message, but all that happens is that the page gets changed but nothing is being displayed

Atalanta.html

```<code><button class="btn btn-info" onclick = "Atalanta1();">Read More </button>
</code>```

Article.html

```<code><div id = "NewsArticle">

</div>
</code>```

javascript file

```<code>function Atalanta1() {
    document.location.href = "../Article.html";
    var article = document.querySelector("#NewsArticle");
    var title = "";

    title += "<h2>" + "Hello World" + "</h2>";

    article.innerHTML = title;
}
</code>```

答:
Options: -

a) Shift all the 4 statements after the redirect to the onload event
   of the new page.

b) Pass parameters to new page in URL

c) Pass parameters in Local Storage

d) Use an iframe

Body:
I have a button that if clicked calls a js function that should change the current page and display a simple hello world message, but all that happens is that the page gets changed but nothing is being displayed

Atalanta.html

<button class="btn btn-info" onclick = "Atalanta1();">Read More </button>

Article.html

javascript file

function Atalanta1() {
    document.location.href = "../Article.html";
    var article = document.querySelector("#NewsArticle");
    var title = "";

    title += "
" + "Hello World" + "
";

    article.innerHTML = title;
}


问:
Polymorphism on extension functions in Kotlin
I have a several classes I don't control, upon which I've already created several identically-named extension methods across several common "attributes".  The identically-named extension functions always return the same value type, though calculated in different ways for each type of receiver.  Here is a simplified example based on built-in types for just one attribute:

```<code>// **DOES NOT COMPILE**

// three sample classes I don't control extended for .len
inline val String.len get() = length
inline val <T> List<T>.len get() = size
inline val <T> Sequence<T>.len get() = count()

// another class which needs to act on things with .len
class Calc<T>(val obj:T) {       // HERE IS THE PROBLEM...
  val dbl get() = obj?.len * 2   // dummy property that doubles len
  // ... and other methods that use .len and other parallel extensions
}

fun main(a:Array<String>) {
  val s = "abc"
  val l = listOf(5,6,7)
  val q = (10..20 step 2).asSequence()
  val cs = Calc(s)
  val cl = Calc(l)
  val cq = Calc(q)
  println("Lens:  ${cs.dbl}, ${cl.dbl}, ${cq.dbl}")
}
</code>```

Imagine several other "common" properties extended in the same manner as .len in some classes I don't control.  If I don't want to repeat myself in every class, how do I construct a properly typed class that can operate on .len (and other such properties) generically for these three classes?

I've researched the following but not found workable solutions yet:

generics, in the example above, but can't get the syntax right.

sealed classes, but I don't have control of these classes.

union types, which I've found aren't supported in Kotlin.

wrapper
classes, but couldn't get the syntax right.

passing lambdas a la
this blog explanation, but didn't get it right, and it seemed boptimalsu to pass multiple lambdas around for every method.

There must be a better way, right?

答:
Here's a example with sealed classes and a single extension property to convert anything to something which can give you len or double. Not sure if it has better readability thogh.

```<code>val Any?.calc get() = when(this) {
    is String -> Calc.CalcString(this)
    is List<*> -> Calc.CalcList(this)
    is Sequence<*> -> Calc.CalcSequense(this)
    else -> Calc.None
}

/* or alternatively without default fallback */

val String.calc get() = Calc.CalcString(this)
val List<*>.calc get() = Calc.CalcList(this)
val Sequence<*>.calc get() = Calc.CalcSequense(this)

/* sealed extension classes */

sealed class Calc {

    abstract val len: Int?

    val dbl: Int? by lazy(LazyThreadSafetyMode.NONE) { len?.let { it * 2 } }

    class CalcString(val s: String): Calc() {
        override val len: Int? get() = s.length
    }

    class CalcList<out T>(val l: List<T>): Calc() {
        override val len: Int? get() = l.size
    }

    class CalcSequense<out T>(val s: Sequence<T>): Calc() {
        override val len: Int? get() = s.count()
    }

    object None: Calc() {
        override val len: Int? get() = null
    }

}

fun main(args: Array<String>) {
    val s = "abc".calc
    val l = listOf(5,6,7).calc
    val q = (10..20 step 2).asSequence().calc

    println("Lens:  ${s.dbl}, ${l.dbl}, ${q.dbl}")
}
</code>```

Body:
I have a several classes I don't control, upon which I've already created several identically-named extension methods across several common "attributes".  The identically-named extension functions always return the same value type, though calculated in different ways for each type of receiver.  Here is a simplified example based on built-in types for just one attribute:

// **DOES NOT COMPILE**

// three sample classes I don't control extended for .len
inline val String.len get() = length
inline val <T> List<T>.len get() = size
inline val <T> Sequence<T>.len get() = count()

// another class which needs to act on things with .len
class Calc<T>(val obj:T) {       // HERE IS THE PROBLEM...
  val dbl get() = obj?.len * 2   // dummy property that doubles len
  // ... and other methods that use .len and other parallel extensions
}

fun main(a:Array<String>) {
  val s = "abc"
  val l = listOf(5,6,7)
  val q = (10..20 step 2).asSequence()
  val cs = Calc(s)
  val cl = Calc(l)
  val cq = Calc(q)
  println("Lens:  ${cs.dbl}, ${cl.dbl}, ${cq.dbl}")
}

Imagine several other "common" properties extended in the same manner as .len in some classes I don't control.  If I don't want to repeat myself in every class, how do I construct a properly typed class that can operate on .len (and other such properties) generically for these three classes?

I've researched the following but not found workable solutions yet:

generics, in the example above, but can't get the syntax right.

sealed classes, but I don't have control of these classes.

union types, which I've found aren't supported in Kotlin.

wrapper
classes, but couldn't get the syntax right.

passing lambdas a la
this blog explanation, but didn't get it right, and it seemed boptimalsu to pass multiple lambdas around for every method.

There must be a better way, right?

Body:
Here's a example with sealed classes and a single extension property to convert anything to something which can give you len or double. Not sure if it has better readability thogh.

val Any?.calc get() = when(this) {
    is String -> Calc.CalcString(this)
    is List<*> -> Calc.CalcList(this)
    is Sequence<*> -> Calc.CalcSequense(this)
    else -> Calc.None
}

/* or alternatively without default fallback */

val String.calc get() = Calc.CalcString(this)
val List<*>.calc get() = Calc.CalcList(this)
val Sequence<*>.calc get() = Calc.CalcSequense(this)

/* sealed extension classes */

sealed class Calc {

    abstract val len: Int?

    val dbl: Int? by lazy(LazyThreadSafetyMode.NONE) { len?.let { it * 2 } }

    class CalcString(val s: String): Calc() {
        override val len: Int? get() = s.length
    }

    class CalcList<out T>(val l: List<T>): Calc() {
        override val len: Int? get() = l.size
    }

    class CalcSequense<out T>(val s: Sequence<T>): Calc() {
        override val len: Int? get() = s.count()
    }

    object None: Calc() {
        override val len: Int? get() = null
    }

}

fun main(args: Array<String>) {
    val s = "abc".calc
    val l = listOf(5,6,7).calc
    val q = (10..20 step 2).asSequence().calc

    println("Lens:  ${s.dbl}, ${l.dbl}, ${q.dbl}")
}


问:
How to set focus to Firefox window using Web Extension
I am trying to create a Firefox addon that will bring the browser window to the forefront whenever a given event is fired.

This is my manifest:

```<code>{
  "manifest_version": 2,
  "name": "Test Extension",
  "version": "1.0",
  "description": "Test browser extension",

  "content_scripts": [{
    "matches": ["http://*/*", "https://*/*"],
    "js": ["content.js"]
  }],

  "background": {
    "scripts": ["background.js"],
    "persistent": true
  },

  "permissions": [
    "notifications",
    "activeTab"
  ]
}
</code>```

Content.js:

```<code>'use strict';

document.addEventListener('newOrderEvent', function() {
  console.log('New Order event received');
  browser.runtime.sendMessage('new-order-event');
});
</code>```

Background.js:

```<code>'use strict';

var windowId;

function newOrderListener(message) {
  if (message === 'new-order-event') {
    console.log('Received event!');
    browser.windows.update(windowId, {
      drawAttention: true,
      focused: true,
      state: 'maximized'
    });
  }
}

browser.windows.getCurrent().then(function(window) {
  windowId = window.id;
});

browser.runtime.onMessage.addListener(newOrderListener);
</code>```

The newOrderEvent is generated by my application's webpage and it is always being called at the right time, however sometimes the browser comes to the foreground and other times it doesn't and I don't understand exactly why. Furthermore the console output from the background.js is not being registered by the browser.

What I am doing wrong?

Note: I am using Firefox 52 and Windows 10.

答:
If what you want is a TAB to make itself focused, then you are mistaken with what windowId is. WindowId will be the ID of the window, not of a tab, and the way you are setting it, it will only ever be a single value, the first windowID when the extension is loaded

if you change background.js to the following

```<code>function newOrderListener(message, sender) {
    if (message === 'new-order-event') {
        console.log('Received event for window %s, tab %s', sender.tab.windowId, sender.tab.id);
        browser.windows.update(sender.tab.windowId, {
            drawAttention: true,
            focused: true,
            state: 'maximized'}
        ).then(() => browser.tabs.update(sender.tab.id, {
            active: true
        }));
    }
}
browser.runtime.onMessage.addListener(newOrderListener);
</code>```

Then any tab that has the content script loaded (which is basically every tab in your code) will be able to focus itself by

```<code>document.dispatchEvent(new Event("newOrderEvent"))
</code>```

Body:
I am trying to create a Firefox addon that will bring the browser window to the forefront whenever a given event is fired.

This is my manifest:

{
  "manifest_version": 2,
  "name": "Test Extension",
  "version": "1.0",
  "description": "Test browser extension",

  "content_scripts": [{
    "matches": ["http://*/*", "https://*/*"],
    "js": ["content.js"]
  }],

  "background": {
    "scripts": ["background.js"],
    "persistent": true
  },

  "permissions": [
    "notifications",
    "activeTab"
  ]
}

Content.js:

'use strict';

document.addEventListener('newOrderEvent', function() {
  console.log('New Order event received');
  browser.runtime.sendMessage('new-order-event');
});

Background.js:

'use strict';

var windowId;

function newOrderListener(message) {
  if (message === 'new-order-event') {
    console.log('Received event!');
    browser.windows.update(windowId, {
      drawAttention: true,
      focused: true,
      state: 'maximized'
    });
  }
}

browser.windows.getCurrent().then(function(window) {
  windowId = window.id;
});

browser.runtime.onMessage.addListener(newOrderListener);

The newOrderEvent is generated by my application's webpage and it is always being called at the right time, however sometimes the browser comes to the foreground and other times it doesn't and I don't understand exactly why. Furthermore the console output from the background.js is not being registered by the browser.

What I am doing wrong?

Note: I am using Firefox 52 and Windows 10.

Body:
If what you want is a TAB to make itself focused, then you are mistaken with what windowId is. WindowId will be the ID of the window, not of a tab, and the way you are setting it, it will only ever be a single value, the first windowID when the extension is loaded

if you change background.js to the following

function newOrderListener(message, sender) {
    if (message === 'new-order-event') {
        console.log('Received event for window %s, tab %s', sender.tab.windowId, sender.tab.id);
        browser.windows.update(sender.tab.windowId, {
            drawAttention: true,
            focused: true,
            state: 'maximized'}
        ).then(() => browser.tabs.update(sender.tab.id, {
            active: true
        }));
    }
}
browser.runtime.onMessage.addListener(newOrderListener);

Then any tab that has the content script loaded (which is basically every tab in your code) will be able to focus itself by

document.dispatchEvent(new Event("newOrderEvent"))


答:
Simply use Numpys tolist function.

np.array(a).tolist()

Title: python remove dtype and the end of an array and get list of lists


问:
Question about Normalisation
I am just wondering which of these would be better to use in a web application. I have a web app that lets the user post to the site. There are three different types of posts but similar enough that I could put them under one table. Is that okay to do?

I could normalise the tables in this way? (Putting type under either)

Table 1

```<code>UserPost
post_id
user_id
type
</code>```

Table 2

```<code>Post
post_id
datetime
text
</code>```

OR would using one table be better?

Table

```<code>Post
user_id
post_id
datetime
type
text
</code>```

I am leaning towards the third way, unless someone can point out disadvantages.

答: Based on your latest comment my understanding is that post_id would be a candidate key in ALL THREE of your example tables. If that is correct then I suggest you create one table for each unique set of attributes (each type of post). So if all posts have the same attributes in common then it makes sense to have them all in one table but if there are two or three types then two or three tables would be more appropriate.</p>

Title: Question about Normalisation

Body:
I am just wondering which of these would be better to use in a web application. I have a web app that lets the user post to the site. There are three different types of posts but similar enough that I could put them under one table. Is that okay to do?

I could normalise the tables in this way? (Putting type under either)

Table 1

UserPost
post_id
user_id
type

Table 2

Post
post_id
datetime
text

OR would using one table be better?

Table

Post
user_id
post_id
datetime
type
text

I am leaning towards the third way, unless someone can point out disadvantages.


问:
align-items: center makes img disappear
So with the grid, when I don't have align-items: center; the img shows fine, but once I add align-items: center; it suddenly disappears. What's causing this issue?

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  height: 100px;
}

img {
  display: block;
  max-height: 100%;
  margin: 0 auto;
}

.align {
  align-items: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div>
    <span>text</span>
  </div>
  <div>
    <img src="http://via.placeholder.com/650x1050" />
  </div>
</div>

<div class="grid align">
  <div>
    <span>text</span>
  </div>
  <div>
    <img src="http://via.placeholder.com/650x1050" />
  </div>
</div></code>```

This seems to be a Chrome issue. It's also not fitting the img properly on firefox.

答:
This happens because of the way percentage heights are rendered in the browser.

When align-items: center is not present, align-items: stretch (the default value) is in effect. This automatically gives the flex item (the div) full height.

But when align-items: center is present, it vertically centers the div. The child of the div, the img with max-height: 100%, actually computes to height: auto, because there is no height reference on the parent (the div flex items).

The problem is resolved by setting a height on the flex items.

```<code>.grid > div {
  height: 100%;
}
</code>```

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  height: 100px;
  border: 1px solid red;
}

.grid>div {
  height: 100%;
}

img {
  display: block;
  max-height: 100%;
  margin: 0 auto;
}

.align {
  align-items: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div>
    <span>text</span>
  </div>
  <div>
    <img src="http://via.placeholder.com/650x1050" />
  </div>
</div>
<br><br>
<div class="grid align">
  <div>
    <span>text</span>
  </div>
  <div>
    <img src="http://via.placeholder.com/650x1050" />
  </div>
</div></code>```

More details here:

Working with the CSS height property and percentage values

Chrome / Safari not filling 100% height of flex parent

Title: align-items: center makes img disappear

Body:
So with the grid, when I don't have align-items: center; the img shows fine, but once I add align-items: center; it suddenly disappears. What's causing this issue?

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  height: 100px;
}

img {
  display: block;
  max-height: 100%;
  margin: 0 auto;
}

.align {
  align-items: center;
}

    text

    text

This seems to be a Chrome issue. It's also not fitting the img properly on firefox.

Body:
This happens because of the way percentage heights are rendered in the browser.

When align-items: center is not present, align-items: stretch (the default value) is in effect. This automatically gives the flex item (the div) full height.

But when align-items: center is present, it vertically centers the div. The child of the div, the img with max-height: 100%, actually computes to height: auto, because there is no height reference on the parent (the div flex items).

The problem is resolved by setting a height on the flex items.

.grid > div {
  height: 100%;
}

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  height: 100px;
  border: 1px solid red;
}

.grid>div {
  height: 100%;
}

img {
  display: block;
  max-height: 100%;
  margin: 0 auto;
}

.align {
  align-items: center;
}

<div class="grid">
  <div>
    <span>text</span>
  </div>
  <div>
    <img src="http://via.placeholder.com/650x1050" />
  </div>
</div>
<br><br>
<div class="grid align">
  <div>
    <span>text</span>
  </div>
  <div>
    <img src="http://via.placeholder.com/650x1050" />
  </div>
</div>

More details here:

Working with the CSS height property and percentage values

Chrome / Safari not filling 100% height of flex parent


问:
Image paths in Django view are relative to directory instead of MEDIA_URL
I've been struggling with this problem for a few days and unable to solve it on my own. I am working on a blog site. The post view is rendered at a URL such as this:

```<code>domain.com/blog/specificpost/
</code>```

I have an ImageField in my model. The images upload properly and I can address the images at the correct URLs.

```<code>domain.com/media/asset.jpg
</code>```

In my settings.py I have defined the media paths. When I access the image files from the Admin, they work properly.

```<code>MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
</code>```

When rendering the view of the post, the image path is rendered incorrectly in the DOM. It is:

```<code>domain.com/blog/media/asset.jpg
</code>```

It should be:

```<code>domain.com/media/asset.jpg
</code>```

In my urlpattern I have appended:

```<code>+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

and added the relevant imports to urls.py. I believe this code is supposed to serve the files at the domain root during development.

I have tried all the solutions here, but the image URLs still render relative to the directory. Any help to set me on the correct path would be useful, thank you very much.

Post template:

```<code>{% extends "base.html" %}

{% block journal_entry %}
    <main class="content">
        <section class="photo">
            <img src="{{ object.image }}">
        </section>
        <section class="entry">
            <section class="entry-content">
                {{ object.body|linebreaks }}
            </section>
            <section class="entry-meta">
                {{ object.created }}<span class="user-options"> • <a href="#">Delete</a></span>
            </section>
        </section>
    </main>
{% endblock %}
</code>```

答: Try using {{ object.image.url }} instead of {{ object.image }} in your template.

Body:
I've been struggling with this problem for a few days and unable to solve it on my own. I am working on a blog site. The post view is rendered at a URL such as this:

domain.com/blog/specificpost/

I have an ImageField in my model. The images upload properly and I can address the images at the correct URLs.

domain.com/media/asset.jpg

In my settings.py I have defined the media paths. When I access the image files from the Admin, they work properly.

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

When rendering the view of the post, the image path is rendered incorrectly in the DOM. It is:

domain.com/blog/media/asset.jpg

It should be:

domain.com/media/asset.jpg

In my urlpattern I have appended:

+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

and added the relevant imports to urls.py. I believe this code is supposed to serve the files at the domain root during development.

I have tried all the solutions here, but the image URLs still render relative to the directory. Any help to set me on the correct path would be useful, thank you very much.

Post template:

{% extends "base.html" %}

{% block journal_entry %}

                {{ object.body|linebreaks }}

                {{ object.created }} • Delete

{% endblock %}


问:
creating a keyword dict with keywords and filenames from a file
I don't know why I  get this error when I try to test this function. Can anyone please help me fix this?

d[keywords] = [filename, keywords]
builtins.TypeError: unhashable type: 'list'

I want my end result to look like this.
{'keyword": ['filename1', 'filename2'...]}
where the filenames are ones which have keyword in their list of keywords

Here is the file:

```<code>images/skating.jpg,East York Arena,2014.11.03,Shea skating.,skating,Shea,boy
images/sunglasses.jpg,High Park,2013.02.03,Cool guy.,Shea,sunglasses,happy
images/skating2.jpg,East York Arena,2014.11.03,Shea skating
again!,skating,Shea

def create_keyword_dict(open_file):
'''(file) -> dict of {str: list of str}
Given an open csv file with the format:
filename,location,date,caption,keywords,keywords, ...
return a new dictionary where the key is a keyword and each value
is a list of filenames that have that keyword in their list of keywords.
'''
d = {}
for line in open_file:
    new_d = line.split(',')
    filename = new_d[0]
    keywords = new_d[5:]
    if filename not in d:
        d[keywords] = [filename, keywords]
return d
</code>```

答:
You can't use a list as a dictionary key. The type you use as a key needs to be hashable (this is what the TypeError: unhashable type refers to.

Instead of using a list, you'll need to sort and group your files by single keywords, and use those as the keys - this has the added benefit of being able to search the list by a single keyword, instead of requiring you to have all the keywords for a file to be able to find it. Something like this would work:

```<code>for line in open_file:
    new_d = line.split(',')
    filename = new_d[0]
    keywords = new_d[5:]
    for keyword in keywords:
        if keyword not in d:
            d[keyword] = [filename]
        else:
            d[keyword].append(filename)
</code>```

Body:
I don't know why I  get this error when I try to test this function. Can anyone please help me fix this?

d[keywords] = [filename, keywords]
builtins.TypeError: unhashable type: 'list'

I want my end result to look like this.
{'keyword": ['filename1', 'filename2'...]}
where the filenames are ones which have keyword in their list of keywords

Here is the file:

images/skating.jpg,East York Arena,2014.11.03,Shea skating.,skating,Shea,boy
images/sunglasses.jpg,High Park,2013.02.03,Cool guy.,Shea,sunglasses,happy
images/skating2.jpg,East York Arena,2014.11.03,Shea skating
again!,skating,Shea

def create_keyword_dict(open_file):
'''(file) -> dict of {str: list of str}
Given an open csv file with the format:
filename,location,date,caption,keywords,keywords, ...
return a new dictionary where the key is a keyword and each value
is a list of filenames that have that keyword in their list of keywords.
'''
d = {}
for line in open_file:
    new_d = line.split(',')
    filename = new_d[0]
    keywords = new_d[5:]
    if filename not in d:
        d[keywords] = [filename, keywords]
return d

Body:
You can't use a list as a dictionary key. The type you use as a key needs to be hashable (this is what the TypeError: unhashable type refers to.

Instead of using a list, you'll need to sort and group your files by single keywords, and use those as the keys - this has the added benefit of being able to search the list by a single keyword, instead of requiring you to have all the keywords for a file to be able to find it. Something like this would work:

for line in open_file:
    new_d = line.split(',')
    filename = new_d[0]
    keywords = new_d[5:]
    for keyword in keywords:
        if keyword not in d:
            d[keyword] = [filename]
        else:
            d[keyword].append(filename)


问:
Groovy way to obtain number of seconds in a period
```<code>use(TimeCategory) {(1.year + 2.months + 3.hours).toMilliseconds() }
</code>```

Any suggestions on how to get that in seconds (maintaining the level of grooviness)?

答:
You can add a closure to the groovy.time.TimeDatumDependentDuration class to hide the conversion to seconds:

```<code>TimeDatumDependentDuration.metaClass.toSeconds = { delegate.toMilliseconds() / 1000 }
</code>```

and then:

```<code>use(TimeCategory) { (1.year + 2.months + 3.hours).toSeconds() }
</code>```

will return seconds.

Body:
use(TimeCategory) {(1.year + 2.months + 3.hours).toMilliseconds() }

Any suggestions on how to get that in seconds (maintaining the level of grooviness)?

Body:
You can add a closure to the groovy.time.TimeDatumDependentDuration class to hide the conversion to seconds:

TimeDatumDependentDuration.metaClass.toSeconds = { delegate.toMilliseconds() / 1000 }

and then:

use(TimeCategory) { (1.year + 2.months + 3.hours).toSeconds() }

will return seconds.


问:
Mismatched proxy types (JDK vs CGLIB) when using @EnableCaching with custom AOP advice
I have been trying to get Spring's declarative caching working in an application alongside some custom AOP advice, and have hit an issue with mismatched proxy types.

Given the following Spring Boot application main class:

```<code>@SpringBootApplication
@EnableCaching
public class Application {

    @Bean
    public DefaultAdvisorAutoProxyCreator proxyCreator() {
        return new DefaultAdvisorAutoProxyCreator();
    }

    @Bean
    public NameMatchMethodPointcutAdvisor pointcutAdvisor() {
        NameMatchMethodPointcutAdvisor advisor = new NameMatchMethodPointcutAdvisor();
        advisor.setClassFilter(new RootClassFilter(Service.class));
        advisor.addMethodName("*");
        advisor.setAdvice(new EnsureNonNegativeAdvice());
        return advisor;
    }

    public static class EnsureNonNegativeAdvice implements MethodBeforeAdvice {

        @Override
        public void before(Method method, Object[] args, Object target)
                throws Throwable {
            if ((int) args[0] < 0) {
                throw new IllegalArgumentException();
            }
        }
    }
}
</code>```

and service:

```<code>@Component
public class Service {

    @Cacheable(cacheNames = "int-strings")
    public String getString(int i) {
        return String.valueOf(i);
    }
}
</code>```

I would expect the following test to pass:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Application.class)
public class ApplicationIT {

    @Autowired
    private Service service;

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void getStringWithNegativeThrowsException() {
        thrown.expect(IllegalArgumentException.class);

        service.getString(-1);
    }
}
</code>```

(This code is all available in a runnable project on https://github.com/hdpe/spring-cache-and-aop-issue).

However, running this test gives:

```<code>org.springframework.beans.factory.UnsatisfiedDependencyException:
    ...<snip>...
Caused by: org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'service' is expected to be of type 'me.hdpe.spring.cacheandaop.Service' but was actually of type 'com.sun.proxy.$Proxy61'
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.checkBeanNotOfRequiredType(DefaultListableBeanFactory.java:1520)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1498)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1099)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1060)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:578)
    ...
</code>```

So why is this? Well, I think...

@EnableCaching triggers the creation of an InfrastructureAdvisorAutoProxyCreator, which will happily apply the cache advice via a proxy around Service

As Service implements no interfaces, CGLIB is used to create its proxy

My DefaultAdvisorAutoProxyCreator then runs to apply my custom advice (and, it seems, the cache advice again) around the service method

As the service is now actually a CGLIB proxy, and has been made to implement the SpringProxy and Advised interfaces by Spring, this time Spring creates a JDK dynamic proxy

The dynamic proxy is no longer a Service, and so autowiring into the test class fails.

So to fix the problem (or, at least, hide this problem) I can force my proxy creator to generate CGLIB proxies:

```<code>public DefaultAdvisorAutoProxyCreator proxyCreator() {
    DefaultAdvisorAutoProxyCreator proxyCreator = new DefaultAdvisorAutoProxyCreator();
    proxyCreator.setProxyTargetClass(true);
    return proxyCreator;
}
</code>```

My test then passes, and similarly I can test that the declarative caching is also operational.

So my question(s):

Is this the best way to fix this problem? Is it legal, or a good idea, to have two auto proxy creators applicable to a given bean? And if not, what is the best way to make Spring's implicit auto proxy creators play nicely with custom advice? I'm suspicious that "nested" proxies are a good idea, but can't work out how to override @Enable*'s implicit auto proxy creators.

答:
I've spent an enormous amount of time looking at this problem and have made a little bit of headway.

Having thought about it some more, I've decided the root problem is not really that Spring is choosing the wrong type of proxy to wrap around an already-proxied bean. It's that Spring is trying to double-proxy a bean in the first place!

TL;DR - use @AspectJ instead of DefaultAdvisorAutoProxyCreator

The issue as I've encountered it appears to be a manifestation of SPR-13990 (DefaultAdvisorAutoProxyCreator doesn't get the target class of existing proxy - closed as Won't Fix). The comments later in the discussion are particularly pertinent to my use case. From the maintainer:

Spring's AutoProxyCreators actually always create a new proxy...

SPR-6083 (DefaultAdvisorAutoProxyCreator doesn't work with tx:annotation-driven on Cglib classes - also Won't Fix) is also illuminating; the maintainer says:

We do explicitly avoid double proxying, but only when using implicit
  proxies such as through <tx:annotation-driven> or <aop:config>. I'm
  afraid that an explicit DefaultAdvisorAutoProxyCreator definition
  won't participate in that process...

The suggestions seem to be to:

register the infrastructure (caching, in this case) Advisors with
your DefaultAdvisorAutoProxyCreator yourself; or to

switch to
"<aop:config> style" configuration.

Registering the Advisor yourself

By removing @EnableCaching and defining the beans it contains myself, the InfrastructureAdvisorAutoProxyCreator won't be registered, and I can continue to use my own auto-proxy creator, which my @Cacheable methods will also leverage. My configuration then looks like this:

```<code>@SpringBootApplication
public class Application {

    @Bean
    public DefaultAdvisorAutoProxyCreator proxyCreator() {
        return new DefaultAdvisorAutoProxyCreator();
    }

    @Bean
    public CacheOperationSource cacheOperationSource() {
        return new AnnotationCacheOperationSource();
    }

    @Bean
    public CacheInterceptor cacheInterceptor() {
        CacheInterceptor interceptor = new CacheInterceptor();
        interceptor.setCacheOperationSources(cacheOperationSource());
        return interceptor;
    }

    @Bean
    public BeanFactoryCacheOperationSourceAdvisor cacheOperationSourceAdvisor() {
        BeanFactoryCacheOperationSourceAdvisor advisor = new BeanFactoryCacheOperationSourceAdvisor();
        advisor.setAdvice(cacheInterceptor());
        advisor.setCacheOperationSource(cacheOperationSource());
        return advisor;
    }

    @Bean
    public NameMatchMethodPointcutAdvisor pointcutAdvisor() {
        ...
</code>```

Now this is pretty horrible - I've had to pointlessly redefine lots of core Spring configuration just so I can turn the AutoProxyRegistrar off and I've lost the ability to use CachingConfigurers and probably all sorts of other things.

@AspectJ

So the second approach - once I figured out that "<aop:config> style" in JavaConfig meant @AspectJ annotations - is the way to go. Note that @AspectJ here doesn't mean you're using the AspectJ compiler/weaver! It's still just Spring AOP creating JDK or CGLIB proxies from the @AspectJ annotations.

With @AspectJ-style config, the whole configuration condenses to this:

```<code>@SpringBootApplication
@EnableCaching
@EnableAspectJAutoProxy
public class Application {

    @Aspect
    @Component
    public static class EnsureNonNegativeAspect {

        @Before("execution(* me.hdpe.spring.cacheandaop.Service.*(..)) && args(i)")
        public void ensureNonNegative(int i) {
            if (i < 0) {
                throw new IllegalArgumentException();
            }
        }
    }
}
</code>```

Incredibly this works because @EnableAspectJAutoProxy promotes any existing InfrastructureAdvisorAutoProxyCreator to an @AspectJ auto-proxy creator, resulting in just a single proxy applying both my custom and the caching advice.

So in summary

I think if you want to use custom Spring AOP advice with the implicit advice created by @EnableCaching, @EnableTransactionManagement etc., you're probably  much better off using @AspectJ rather than a DefaultAdvisorAutoProxyCreator. This seems to be the direction Spring want you to go down and they hint as much in the docs:

The previous chapter described the Spring's support for AOP using
  @AspectJ and schema-based aspect definitions. In this chapter we
  discuss the lower-level Spring AOP APIs and the AOP support typically
  used in Spring 1.2 applications. For new applications, we recommend
  the use of the Spring 2.0 and later AOP support described in the
  previous chapter...

...but the DefaultAdvisorAutoProxyCreator seemed sufficiently ubiquitous that I imagined it was 'lower-level' rather than 'Spring 1.2'.

Body:
I have been trying to get Spring's declarative caching working in an application alongside some custom AOP advice, and have hit an issue with mismatched proxy types.

Given the following Spring Boot application main class:

@SpringBootApplication
@EnableCaching
public class Application {

    @Bean
    public DefaultAdvisorAutoProxyCreator proxyCreator() {
        return new DefaultAdvisorAutoProxyCreator();
    }

    @Bean
    public NameMatchMethodPointcutAdvisor pointcutAdvisor() {
        NameMatchMethodPointcutAdvisor advisor = new NameMatchMethodPointcutAdvisor();
        advisor.setClassFilter(new RootClassFilter(Service.class));
        advisor.addMethodName("*");
        advisor.setAdvice(new EnsureNonNegativeAdvice());
        return advisor;
    }

    public static class EnsureNonNegativeAdvice implements MethodBeforeAdvice {

        @Override
        public void before(Method method, Object[] args, Object target)
                throws Throwable {
            if ((int) args[0] < 0) {
                throw new IllegalArgumentException();
            }
        }
    }
}

and service:

@Component
public class Service {

    @Cacheable(cacheNames = "int-strings")
    public String getString(int i) {
        return String.valueOf(i);
    }
}

I would expect the following test to pass:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Application.class)
public class ApplicationIT {

    @Autowired
    private Service service;

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void getStringWithNegativeThrowsException() {
        thrown.expect(IllegalArgumentException.class);

        service.getString(-1);
    }
}

(This code is all available in a runnable project on https://github.com/hdpe/spring-cache-and-aop-issue).

However, running this test gives:

org.springframework.beans.factory.UnsatisfiedDependencyException:
    ...<snip>...
Caused by: org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'service' is expected to be of type 'me.hdpe.spring.cacheandaop.Service' but was actually of type 'com.sun.proxy.$Proxy61'
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.checkBeanNotOfRequiredType(DefaultListableBeanFactory.java:1520)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1498)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1099)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1060)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:578)
    ...

So why is this? Well, I think...

@EnableCaching triggers the creation of an InfrastructureAdvisorAutoProxyCreator, which will happily apply the cache advice via a proxy around Service

As Service implements no interfaces, CGLIB is used to create its proxy

My DefaultAdvisorAutoProxyCreator then runs to apply my custom advice (and, it seems, the cache advice again) around the service method

As the service is now actually a CGLIB proxy, and has been made to implement the SpringProxy and Advised interfaces by Spring, this time Spring creates a JDK dynamic proxy

The dynamic proxy is no longer a Service, and so autowiring into the test class fails.

So to fix the problem (or, at least, hide this problem) I can force my proxy creator to generate CGLIB proxies:

public DefaultAdvisorAutoProxyCreator proxyCreator() {
    DefaultAdvisorAutoProxyCreator proxyCreator = new DefaultAdvisorAutoProxyCreator();
    proxyCreator.setProxyTargetClass(true);
    return proxyCreator;
}

My test then passes, and similarly I can test that the declarative caching is also operational.

So my question(s):

Is this the best way to fix this problem? Is it legal, or a good idea, to have two auto proxy creators applicable to a given bean? And if not, what is the best way to make Spring's implicit auto proxy creators play nicely with custom advice? I'm suspicious that "nested" proxies are a good idea, but can't work out how to override @Enable*'s implicit auto proxy creators.

Body:
I've spent an enormous amount of time looking at this problem and have made a little bit of headway.

Having thought about it some more, I've decided the root problem is not really that Spring is choosing the wrong type of proxy to wrap around an already-proxied bean. It's that Spring is trying to double-proxy a bean in the first place!

TL;DR - use @AspectJ instead of DefaultAdvisorAutoProxyCreator

The issue as I've encountered it appears to be a manifestation of SPR-13990 (DefaultAdvisorAutoProxyCreator doesn't get the target class of existing proxy - closed as Won't Fix). The comments later in the discussion are particularly pertinent to my use case. From the maintainer:

Spring's AutoProxyCreators actually always create a new proxy...

SPR-6083 (DefaultAdvisorAutoProxyCreator doesn't work with tx:annotation-driven on Cglib classes - also Won't Fix) is also illuminating; the maintainer says:

We do explicitly avoid double proxying, but only when using implicit
  proxies such as through <tx:annotation-driven> or <aop:config>. I'm
  afraid that an explicit DefaultAdvisorAutoProxyCreator definition
  won't participate in that process...

The suggestions seem to be to:

register the infrastructure (caching, in this case) Advisors with
your DefaultAdvisorAutoProxyCreator yourself; or to

switch to
"<aop:config> style" configuration.

Registering the Advisor yourself

By removing @EnableCaching and defining the beans it contains myself, the InfrastructureAdvisorAutoProxyCreator won't be registered, and I can continue to use my own auto-proxy creator, which my @Cacheable methods will also leverage. My configuration then looks like this:

@SpringBootApplication
public class Application {

    @Bean
    public DefaultAdvisorAutoProxyCreator proxyCreator() {
        return new DefaultAdvisorAutoProxyCreator();
    }

    @Bean
    public CacheOperationSource cacheOperationSource() {
        return new AnnotationCacheOperationSource();
    }

    @Bean
    public CacheInterceptor cacheInterceptor() {
        CacheInterceptor interceptor = new CacheInterceptor();
        interceptor.setCacheOperationSources(cacheOperationSource());
        return interceptor;
    }

    @Bean
    public BeanFactoryCacheOperationSourceAdvisor cacheOperationSourceAdvisor() {
        BeanFactoryCacheOperationSourceAdvisor advisor = new BeanFactoryCacheOperationSourceAdvisor();
        advisor.setAdvice(cacheInterceptor());
        advisor.setCacheOperationSource(cacheOperationSource());
        return advisor;
    }

    @Bean
    public NameMatchMethodPointcutAdvisor pointcutAdvisor() {
        ...

Now this is pretty horrible - I've had to pointlessly redefine lots of core Spring configuration just so I can turn the AutoProxyRegistrar off and I've lost the ability to use CachingConfigurers and probably all sorts of other things.

@AspectJ

So the second approach - once I figured out that "<aop:config> style" in JavaConfig meant @AspectJ annotations - is the way to go. Note that @AspectJ here doesn't mean you're using the AspectJ compiler/weaver! It's still just Spring AOP creating JDK or CGLIB proxies from the @AspectJ annotations.

With @AspectJ-style config, the whole configuration condenses to this:

@SpringBootApplication
@EnableCaching
@EnableAspectJAutoProxy
public class Application {

    @Aspect
    @Component
    public static class EnsureNonNegativeAspect {

        @Before("execution(* me.hdpe.spring.cacheandaop.Service.*(..)) && args(i)")
        public void ensureNonNegative(int i) {
            if (i < 0) {
                throw new IllegalArgumentException();
            }
        }
    }
}

Incredibly this works because @EnableAspectJAutoProxy promotes any existing InfrastructureAdvisorAutoProxyCreator to an @AspectJ auto-proxy creator, resulting in just a single proxy applying both my custom and the caching advice.

So in summary

I think if you want to use custom Spring AOP advice with the implicit advice created by @EnableCaching, @EnableTransactionManagement etc., you're probably  much better off using @AspectJ rather than a DefaultAdvisorAutoProxyCreator. This seems to be the direction Spring want you to go down and they hint as much in the docs:

The previous chapter described the Spring's support for AOP using
  @AspectJ and schema-based aspect definitions. In this chapter we
  discuss the lower-level Spring AOP APIs and the AOP support typically
  used in Spring 1.2 applications. For new applications, we recommend
  the use of the Spring 2.0 and later AOP support described in the
  previous chapter...

...but the DefaultAdvisorAutoProxyCreator seemed sufficiently ubiquitous that I imagined it was 'lower-level' rather than 'Spring 1.2'.


问:
Javascript: Transform object with arrays into array of objects
Please excuse if I am using wrong terms, but I am completely new to this type of technology. Concerning my question:
I have a webapp that returns either

```<code> {
    "amount": "1",
    "unit": "59edd0b2b714531cac8afced",
    "part": "59ede77d52023619d45e949a",
    "comment": "comment 1"
}
</code>```

or

```<code>{
    "amount":["12","24"],
    "unit":["59edd0b2b714531cac8afced","59edd0b7b714531cac8afcee"],
    "part":["59ede77d52023619d45e949a","59fe50ca25811e25cc38446d"],
    "comment":["comment xyz","comment whatever"]
}
</code>```

In both scenarios, I'd like to have an array of objects like below:

```<code>[
{
    "amount": "12",
    "unit": "59edd0b2b714531cac8afced",
    "part": "59ede77d52023619d45e949a",
    "comment": "comment xyz"
},
{
    "amount": "24",
    "unit": "59edd0b7b714531cac8afcee",
    "part": "59fe50ca25811e25cc38446d",
    "comment": "comment whatever""
}
]
</code>```

Whats the easiest way to achieve this?
Thanks for your help.

答:
I would probably just build a function that converts it to the format you want, like this:

function convert(data) {
  if (!Array.isArray(data.amount)) {
    return [data];
  }
  var final = [];
  for (var i = 0; i < data.amount.length; i++) {
    var obj = {};
    for (var key in data) {
        obj[key] = data[key][i];
    }
    final.push(obj);
  }
  return final;
}

var data = {
    "amount":["12","24"],
    "unit":["59edd0b2b714531cac8afced","59edd0b7b714531cac8afcee"],
    "part":["59ede77d52023619d45e949a","59fe50ca25811e25cc38446d"],
    "comment":["comment xyz","comment whatever"]
}
data = convert(data);
console.log(data);

data = {
  "amount": "1",
  "unit": "59edd0b2b714531cac8afced",
  "part": "59ede77d52023619d45e949a",
  "comment": "comment 1"
}
data = convert(data);
console.log(data);```

This works on the assumption that if it comes in the array format, each key will contain an array of the same length.

Body:
Please excuse if I am using wrong terms, but I am completely new to this type of technology. Concerning my question:
I have a webapp that returns either

 {
    "amount": "1",
    "unit": "59edd0b2b714531cac8afced",
    "part": "59ede77d52023619d45e949a",
    "comment": "comment 1"
}

or

{
    "amount":["12","24"],
    "unit":["59edd0b2b714531cac8afced","59edd0b7b714531cac8afcee"],
    "part":["59ede77d52023619d45e949a","59fe50ca25811e25cc38446d"],
    "comment":["comment xyz","comment whatever"]
}

In both scenarios, I'd like to have an array of objects like below:

[
{
    "amount": "12",
    "unit": "59edd0b2b714531cac8afced",
    "part": "59ede77d52023619d45e949a",
    "comment": "comment xyz"
},
{
    "amount": "24",
    "unit": "59edd0b7b714531cac8afcee",
    "part": "59fe50ca25811e25cc38446d",
    "comment": "comment whatever""
}
]

Whats the easiest way to achieve this?
Thanks for your help.

Body:
I would probably just build a function that converts it to the format you want, like this:

function convert(data) {
  if (!Array.isArray(data.amount)) {
    return [data];
  }
  var final = [];
  for (var i = 0; i < data.amount.length; i++) {
    var obj = {};
    for (var key in data) {
        obj[key] = data[key][i];
    }
    final.push(obj);
  }
  return final;
}

var data = {
    "amount":["12","24"],
    "unit":["59edd0b2b714531cac8afced","59edd0b7b714531cac8afcee"],
    "part":["59ede77d52023619d45e949a","59fe50ca25811e25cc38446d"],
    "comment":["comment xyz","comment whatever"]
}
data = convert(data);
console.log(data);

data = {
  "amount": "1",
  "unit": "59edd0b2b714531cac8afced",
  "part": "59ede77d52023619d45e949a",
  "comment": "comment 1"
}
data = convert(data);
console.log(data);

This works on the assumption that if it comes in the array format, each key will contain an array of the same length.