问:
Wavesurfer How to speed up the process of playing music
I'm use WaveSurferJs to playing streaming audio and set on wavesurfer init backend as MediaElement. Also do a drawing of peaks

```<code>var wavesurfer = WaveSurfer.create({
        .....
        container: '#waveform',
        barWidth: 2,
        barHeight: 1,
        backend: 'MediaElement',
        normalize: true
    });

wavesurfer.load(mp3_url, peakData);
wavesurfer.play();
</code>```

And I do something in the form of a playlist first audio in audio element uses preload=true but next audio loading so slow, It is logical that it takes time for preloading. But how to speed up the process of playing music? Is there anyone who tried to do this?

答:
This is very late, so probably not of use to the author but could be of use for someone else who is looking for this info.

You need to use the setPlaybackRate method Wavesurfer Methods

So for example I have a slider in YII2 that has this code

```<code><?php
echo Slider::widget([
'name'=>'audio_speed',
'value'=>1,
'sliderColor'=>Slider::TYPE_GREY,
'handleColor'=>Slider::TYPE_DANGER,
'pluginOptions'=>[
'min'=>1,
    'max'=>2,
    'step'=>.1
],
'pluginEvents' => [
"slideStop" => 'function(level) { awp_player.setPlaybackRate(level.value);
}',
]
]);
?>
</code>```

So it starts at normal speed, 1 and allows the user to double the speed, in 0.1 increments by moving the slider and when the user stop "sliding", the method is called.

Body:
I'm use WaveSurferJs to playing streaming audio and set on wavesurfer init backend as MediaElement. Also do a drawing of peaks

var wavesurfer = WaveSurfer.create({
        .....
        container: '#waveform',
        barWidth: 2,
        barHeight: 1,
        backend: 'MediaElement',
        normalize: true
    });

wavesurfer.load(mp3_url, peakData);
wavesurfer.play();

And I do something in the form of a playlist first audio in audio element uses preload=true but next audio loading so slow, It is logical that it takes time for preloading. But how to speed up the process of playing music? Is there anyone who tried to do this?

Body:
This is very late, so probably not of use to the author but could be of use for someone else who is looking for this info.

You need to use the setPlaybackRate method Wavesurfer Methods

So for example I have a slider in YII2 that has this code

<?php
echo Slider::widget([
'name'=>'audio_speed',
'value'=>1,
'sliderColor'=>Slider::TYPE_GREY,
'handleColor'=>Slider::TYPE_DANGER,
'pluginOptions'=>[
'min'=>1,
    'max'=>2,
    'step'=>.1
],
'pluginEvents' => [
"slideStop" => 'function(level) { awp_player.setPlaybackRate(level.value);
}',
]
]);
?>

So it starts at normal speed, 1 and allows the user to double the speed, in 0.1 increments by moving the slider and when the user stop "sliding", the method is called.


来源: stackexchange

问:
AS3: Model and View Communication in a Game
So I'm attempting to use the MVC pattern for a game I'm working on. Everything has been going pretty smoothly so far, but I'm having trouble figuring out how to get my model and my view to talk to each other effectively.

My general model structure involves lots of nested information.

```<code>a Level has Rooms
    a Room have Layers
        a Layer has Objects
</code>```

Each layer has an index and a corresponding layer in the view that is rendering it. I need the objects to post an update message as they animate so it's corresponding layer in the view can update. I'm trying to use the built in event system to handle these updates.

My issue is I'm not sure how to avoid putting listeners on every object in the game - which strikes me as bad ( perhaps I'm wrong here ). If I change the rooms, the layer doesn't have a way of removing listeners from the objects in the last room because it only accesses layers through the current room. Objects are only updated when they are in the current room, so the other objects won't need to fire events.

The view is set up to cascade events to all of the children, so the root node can receive all updates ( I think I did that part correctly ), and the layer can match the target because it knows which layer it's rendering. The problem is getting the message out from the objects to the view.

Of course this makes sense to me, because I've been working with the code for a while now.

If I can provide more clarification please ask. This is my first time working with the MVC pattern, so I'm sure I could do things better.

If you have any suggestions as to how I might solve this conundrum, please share!

Edit: I have something working keeping track of the current layerset from outside of the view and the model which manages adding/removing the appropriate event listeners and delegating the update event to the layer as suggested. But please, anything I can do to improve this please do.

答:
Using the Mediator pattern in PureMVC, rather than putting listeners on every object, you could have a Mediator listen to the application instance for the events. Then inside the actual objects, send a bubbling event that bubbles up the display hierarchy to the application where the Mediator hears it. Then the mediator takes the appropriate action such as sending off a notification to trigger a command with some logic, perhaps. The target of the event, would of course be the item in your world that sent the event, so if the Command would need to manipulate or inspect that item, then just pass the event.target in the notification body. QED.

-=Cliff>

ContentLicense: CC BY-SA 2.5

Body:
So I'm attempting to use the MVC pattern for a game I'm working on. Everything has been going pretty smoothly so far, but I'm having trouble figuring out how to get my model and my view to talk to each other effectively.

My general model structure involves lots of nested information.

a Level has Rooms
    a Room have Layers
        a Layer has Objects

Each layer has an index and a corresponding layer in the view that is rendering it. I need the objects to post an update message as they animate so it's corresponding layer in the view can update. I'm trying to use the built in event system to handle these updates.

My issue is I'm not sure how to avoid putting listeners on every object in the game - which strikes me as bad ( perhaps I'm wrong here ). If I change the rooms, the layer doesn't have a way of removing listeners from the objects in the last room because it only accesses layers through the current room. Objects are only updated when they are in the current room, so the other objects won't need to fire events.

The view is set up to cascade events to all of the children, so the root node can receive all updates ( I think I did that part correctly ), and the layer can match the target because it knows which layer it's rendering. The problem is getting the message out from the objects to the view.

Of course this makes sense to me, because I've been working with the code for a while now.

If I can provide more clarification please ask. This is my first time working with the MVC pattern, so I'm sure I could do things better.

If you have any suggestions as to how I might solve this conundrum, please share!

Edit: I have something working keeping track of the current layerset from outside of the view and the model which manages adding/removing the appropriate event listeners and delegating the update event to the layer as suggested. But please, anything I can do to improve this please do.


问:
Subtracting two date columns in PySpark Python
I am trying to subtract two columns in PySpark Dataframe in Python I have got a number of problems doing it, I have column type  as timestamp, the column is date1 = 2011-01-03 13:25:59 and want to subtract this from other date column date2 = 2011-01-03 13:27:00 so I want date2 - date1 and from those dataframe columns and making a seperate timediff column, which shows difference of these both columns such as timeDiff = 00:01:01

how can I do this in PySaprk

I tried the following code:

```<code>#timeDiff = df.withColumn(('timeDiff', col(df['date2']) - col(df['date1'])))
</code>```

this code didn't work

I tried doing this simple thing:

```<code>timeDiff = df['date2'] - df['date1']
</code>```

this actually worked, but after that I tried to add this seperate column to the my dataframe by the following piece of code

```<code>df = df.withColumn("Duration", timeDiff)
</code>```

it is having the follwing error:

```<code>Py4JJavaError: An error occurred while calling o107.withColumn.
: org.apache.spark.sql.AnalysisException: cannot resolve '(`date2` - `date1`)' due to data type mismatch: '(`date2` - `date1`)' requires (numeric or calendarinterval) type, not timestamp;;
</code>```

Any one can help me with any other method or how can I resolve this error ??

ContentLicense: CC BY-SA 3.0

Body:
I am trying to subtract two columns in PySpark Dataframe in Python I have got a number of problems doing it, I have column type  as timestamp, the column is date1 = 2011-01-03 13:25:59 and want to subtract this from other date column date2 = 2011-01-03 13:27:00 so I want date2 - date1 and from those dataframe columns and making a seperate timediff column, which shows difference of these both columns such as timeDiff = 00:01:01

how can I do this in PySaprk

I tried the following code:

#timeDiff = df.withColumn(('timeDiff', col(df['date2']) - col(df['date1'])))

this code didn't work

I tried doing this simple thing:

timeDiff = df['date2'] - df['date1']

this actually worked, but after that I tried to add this seperate column to the my dataframe by the following piece of code

df = df.withColumn("Duration", timeDiff)

it is having the follwing error:

Py4JJavaError: An error occurred while calling o107.withColumn.
: org.apache.spark.sql.AnalysisException: cannot resolve '(`date2` - `date1`)' due to data type mismatch: '(`date2` - `date1`)' requires (numeric or calendarinterval) type, not timestamp;;

Any one can help me with any other method or how can I resolve this error ??

Body:
from pyspark.sql.functions import unix_timestamp

#sample data
df = sc.parallelize([
    ['2011-01-03 13:25:59', '2011-01-03 13:27:00'],
    ['2011-01-03 3:25:59',  '2011-01-03 3:30:00']
]).toDF(('date1', 'date2'))

timeDiff = (unix_timestamp('date2', "yyyy-MM-dd HH:mm:ss") - unix_timestamp('date1', "yyyy-MM-dd HH:mm:ss"))
df = df.withColumn("Duration", timeDiff)
df.show()

Output is:

+-------------------+-------------------+--------+
|              date1|              date2|Duration|
+-------------------+-------------------+--------+
|2011-01-03 13:25:59|2011-01-03 13:27:00|      61|
| 2011-01-03 3:25:59| 2011-01-03 3:30:00|     241|
+-------------------+-------------------+--------+

ContentLicense: CC BY-SA 4.0


问:
Guide for migrating from Swiper 2.5.5 to 4.0.7?
I'm looking for some kind of guidelines, known issues, risks or any kind of information to help migrating an app written using idangerous Swiper 2.5.5 to the latest (4.0.7 as of December 2017). My major concern is support for latest Chrome / FF for desktop, although mobile and other browsers are a plus.

I found this Change Log page with some release notes from version 3.0.0 on. I found nothing about older versions and no guide to upgrade, specially useful for major versions

Obs: the same question was originally posted on their forum

答:
Here are a few lessons learned after some initial tests (the list is most likely not complete). APIs updated:

jQuery/Zepto usage changed from $('.swiper-container').swiper({}) to new Swiper ('.swiper-container', {})

resizeFix() removed

reInit() removed

navigation APIs renamed:

swipeTo() to slideTo()

swipePrev() to slidePrev()

swipeNext() to slideNext()

pagination param type changed from '.tgt' to { el: '.tgt'} obj


问:
Group and center images of varying width?
I have 4 images that need to be "grouped" then centered horizontally.  These are letters in a word. They cannot be combined into a single image.

Here is what I have right now:

#imageContainer {
  width: 100%;
  border: 1px solid blue;
}
#images {
  display: block;
  margin: auto;
}
#imageContainer img {
  display: inline;
  margin: auto;
  padding: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="imageContainer">
  <div id="images">
    <img src="https://dummyimage.com/100x100/000/fff" alt="">
    <img src="https://dummyimage.com/80x100/000/fff" alt="">
    <img src="https://dummyimage.com/105x100/000/fff" alt="">
    <img src="https://dummyimage.com/135x100/000/fff" alt="">
  </div>
</div></code>```

The desired behavior would look more like this:

How can I achieve this?

答: Also you can use #images{display:flex;align-items:center}

Body:
I have 4 images that need to be "grouped" then centered horizontally.  These are letters in a word. They cannot be combined into a single image.

Here is what I have right now:

#imageContainer {
  width: 100%;
  border: 1px solid blue;
}
#images {
  display: block;
  margin: auto;
}
#imageContainer img {
  display: inline;
  margin: auto;
  padding: 5px;
}

The desired behavior would look more like this:

How can I achieve this?


问:
Submit multiple form using ajax in laravel
I am facing a problem.I have multiple form submission in one page. I need to submit all of those with out page reload. I am try with some Ajax code. with ajax code, first form are submit properly but rest of form is not working.

here is my view file

```<code><div class="col-md-6 col-lg-6 col-sm-6 col-lg-offset-5">
</code>```

@foreach($questions as $question)

```<code><form method="post" action="{{route('answer.store')}}" id="ansform">
    {{ csrf_field() }}

    <h1>{{$question->question}} ?</h1>
    <div class="col-lg-offset-1">
        <input type="hidden" name="question" value="{{$question->question}}">
        <input type="hidden" name="student_id" value="{{$student_id}}">
        <input type="hidden" name="true_answer" value="{{$question->answer}}">
        <input name="answer" value="{{$question->choice1}}" type="radio"> {{$question->choice1}} <br>
        <input name="answer" value="{{$question->choice2}}" type="radio">{{$question->choice2}}<br>
        <input name="answer" value="{{$question->choice3}}" type="radio">{{$question->choice3}}<br>
        <input name="answer" value="{{$question->choice4}}" type="radio">{{$question->choice4}}<br>
        <input type="submit" name="submit" value="submit" class="btn btn-primary">
    </div>
 </form>
</code>```

@endforeach

Output of view file is-

My route Answer.store is here

```<code>public function store(Request $request)
{
    //
    if ($request->ajax()) {
        $answer=Answer::create([
            'stu_id' => $request->input('student_id'),
            'question' => $request->input('question'),
            'given_answer' => $request->input('answer'),
            'true_answer' => $request->input('true_answer')

        ]);
        return response($answer);
    }else{
        return "ajax not done";
    }
}
</code>```

And finally ajax script is

```<code><script type="text/javascript">
    $(document).ready(function(){
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
    });

    $('#ansform').on('submit',function(e){
        e.preventDefault();
        var data = $(this).serialize();
        var url = $(this).attr('action');
        var post = $(this).attr('method');
        $.ajax({
            type : post,
            url : url,
            data :data,
            success:function(data){
                console.log(data)
            }
        })
    })
</script>
</code>```

Anyone please help me. How can I do this?

答:
I'm answering to last comment.

```<code>$('.ansform').on('submit',function(e){
    var form = $(this);
    var submit = form.find("[type=submit]");
    var submitOriginalText = submit.attr("value");

    e.preventDefault();
    var data = form.serialize();
    var url = form.attr('action');
    var post = form.attr('method');
    $.ajax({
        type : post,
        url : url,
        data :data,
        success:function(data){
           submit.attr("value", "Submitted");
        },
        beforeSend: function(){
           submit.attr("value", "Loading...");
           submit.prop("disabled", true);
        },
        error: function() {
            submit.attr("value", submitOriginalText);
            submit.prop("disabled", false);
           // show error to end user
        }
    })
})
</code>```

This should work.
Before sending the form we are disabling submit button (this protects us from double submit). And then we are changing the text to "Loading..." or something that tells end user that he must wait until query completes.

If AJAX is successfully: We are leaving the button disabled and we are changing text to submitted.

If ERROR occurs: we enable submit, returns the original text and allow end user to submit again. You must show him error or something else.

You can look at AJAX events: https://api.jquery.com/Ajax_Events/.

Body:
I am facing a problem.I have multiple form submission in one page. I need to submit all of those with out page reload. I am try with some Ajax code. with ajax code, first form are submit properly but rest of form is not working.

here is my view file

@foreach($questions as $question)

<form method="post" action="{{route('answer.store')}}" id="ansform">
    {{ csrf_field() }}

{{$question->question}} ?

        <input type="hidden" name="question" value="{{$question->question}}">
        <input type="hidden" name="student_id" value="{{$student_id}}">
        <input type="hidden" name="true_answer" value="{{$question->answer}}">
        <input name="answer" value="{{$question->choice1}}" type="radio"> {{$question->choice1}}

        <input name="answer" value="{{$question->choice2}}" type="radio">{{$question->choice2}}

        <input name="answer" value="{{$question->choice3}}" type="radio">{{$question->choice3}}

        <input name="answer" value="{{$question->choice4}}" type="radio">{{$question->choice4}}

        <input type="submit" name="submit" value="submit" class="btn btn-primary">

 </form>

@endforeach

Output of view file is-

My route Answer.store is here

public function store(Request $request)
{
    //
    if ($request->ajax()) {
        $answer=Answer::create([
            'stu_id' => $request->input('student_id'),
            'question' => $request->input('question'),
            'given_answer' => $request->input('answer'),
            'true_answer' => $request->input('true_answer')

        ]);
        return response($answer);
    }else{
        return "ajax not done";
    }
}

And finally ajax script is

Anyone please help me. How can I do this?

Body:
I'm answering to last comment.

$('.ansform').on('submit',function(e){
    var form = $(this);
    var submit = form.find("[type=submit]");
    var submitOriginalText = submit.attr("value");

    e.preventDefault();
    var data = form.serialize();
    var url = form.attr('action');
    var post = form.attr('method');
    $.ajax({
        type : post,
        url : url,
        data :data,
        success:function(data){
           submit.attr("value", "Submitted");
        },
        beforeSend: function(){
           submit.attr("value", "Loading...");
           submit.prop("disabled", true);
        },
        error: function() {
            submit.attr("value", submitOriginalText);
            submit.prop("disabled", false);
           // show error to end user
        }
    })
})

This should work.
Before sending the form we are disabling submit button (this protects us from double submit). And then we are changing the text to "Loading..." or something that tells end user that he must wait until query completes.

If AJAX is successfully: We are leaving the button disabled and we are changing text to submitted.

If ERROR occurs: we enable submit, returns the original text and allow end user to submit again. You must show him error or something else.

You can look at AJAX events: https://api.jquery.com/Ajax_Events/.


问:
Office/Word Add-in Uploading File to MVC Application
I am building an add-in for Word, with the goal of being able to save the open Word document to our MVC web application. I have followed this guide and am sending the slices like this:

```<code>function sendSlice(slice, state) {
    var data = slice.data;

    if (data) {
        var fileData = myEncodeBase64(data);
        var request = new XMLHttpRequest();

        request.onreadystatechange = function () {
            if (request.readyState == 4) {

                updateStatus("Sent " + slice.size + " bytes.");
                state.counter++;

                if (state.counter < state.sliceCount) {
                    getSlice(state);
                }
                else {
                    closeFile(state);
                }
            }
        }
        request.open("POST", "http://localhost:44379/api/officeupload/1");
        request.setRequestHeader("Slice-Number", slice.index);
        request.setRequestHeader("Total-Slices", state.sliceCount);
        request.setRequestHeader("FileId", "abc29572-8eca-473d-80de-8b87d64e06a0");
        request.setRequestHeader("FileName", "file.docx");

        request.send(fileData);
    }
}
</code>```

And then receiving the slices like this:

```<code>    public void Post()
    {
        if (Files == null) Files = new Dictionary<Guid, Dictionary<int, byte[]>>();

        var slice = int.Parse(Request.Headers.GetValues("Slice-Number").First());
        var numSlices = int.Parse(Request.Headers.GetValues("Total-Slices").First());
        var filename = Request.Headers.GetValues("FileName").First();
        var fileId = Guid.Parse(Request.Headers.GetValues("FileId").First());

        var content = Request.Content.ReadAsStringAsync().Result;

        if (!Files.ContainsKey(fileId)) Files[fileId] = new Dictionary<int, byte[]>();
        Files[fileId][slice] = Convert.FromBase64String(content);

        if (Files[fileId].Keys.Count == numSlices)
        {
            byte[] array = Combine(Files[fileId].OrderBy(x => x.Key).Select(x => x.Value).ToArray());

            System.IO.FileStream writeFileStream = new System.IO.FileStream("c:\\temp\\test.docx", System.IO.FileMode.Create, System.IO.FileAccess.Write);
            writeFileStream.Write(array, 0, array.Length);
            writeFileStream.Close();

            Files.Remove(fileId);
        }
    }
</code>```

The problem is that the file that is produced by the controller is unreadable in Word. I have tested with a word document with "Test123" as the entire contents of the document, and when the file is saved through word it is 13kb, but when sent to the web app and saved from there the file is 41kb.

My assumption is that the I am missing something either with the encoding or decoding, since I am only sending a single slice so there shouldn't be an issue with recombining them.

答: There's an Excel snippet in Script Lab that produces the base64 encoded file which you can paste into an online decoder like www.base64decode.org. The APIs are the same as in Word. This can help you isolate the encoding code. After you install Script Lab, open the Samples tab, scroll to the Document section. It's the Get file (using slicing) snippet.

Body:
I am building an add-in for Word, with the goal of being able to save the open Word document to our MVC web application. I have followed this guide and am sending the slices like this:

function sendSlice(slice, state) {
    var data = slice.data;

    if (data) {
        var fileData = myEncodeBase64(data);
        var request = new XMLHttpRequest();

        request.onreadystatechange = function () {
            if (request.readyState == 4) {

                updateStatus("Sent " + slice.size + " bytes.");
                state.counter++;

                if (state.counter < state.sliceCount) {
                    getSlice(state);
                }
                else {
                    closeFile(state);
                }
            }
        }
        request.open("POST", "http://localhost:44379/api/officeupload/1");
        request.setRequestHeader("Slice-Number", slice.index);
        request.setRequestHeader("Total-Slices", state.sliceCount);
        request.setRequestHeader("FileId", "abc29572-8eca-473d-80de-8b87d64e06a0");
        request.setRequestHeader("FileName", "file.docx");

        request.send(fileData);
    }
}

And then receiving the slices like this:

    public void Post()
    {
        if (Files == null) Files = new Dictionary<Guid, Dictionary<int, byte[]>>();

        var slice = int.Parse(Request.Headers.GetValues("Slice-Number").First());
        var numSlices = int.Parse(Request.Headers.GetValues("Total-Slices").First());
        var filename = Request.Headers.GetValues("FileName").First();
        var fileId = Guid.Parse(Request.Headers.GetValues("FileId").First());

        var content = Request.Content.ReadAsStringAsync().Result;

        if (!Files.ContainsKey(fileId)) Files[fileId] = new Dictionary<int, byte[]>();
        Files[fileId][slice] = Convert.FromBase64String(content);

        if (Files[fileId].Keys.Count == numSlices)
        {
            byte[] array = Combine(Files[fileId].OrderBy(x => x.Key).Select(x => x.Value).ToArray());

            System.IO.FileStream writeFileStream = new System.IO.FileStream("c:\\temp\\test.docx", System.IO.FileMode.Create, System.IO.FileAccess.Write);
            writeFileStream.Write(array, 0, array.Length);
            writeFileStream.Close();

            Files.Remove(fileId);
        }
    }

The problem is that the file that is produced by the controller is unreadable in Word. I have tested with a word document with "Test123" as the entire contents of the document, and when the file is saved through word it is 13kb, but when sent to the web app and saved from there the file is 41kb.

My assumption is that the I am missing something either with the encoding or decoding, since I am only sending a single slice so there shouldn't be an issue with recombining them.


问:
Pythonic multiple inheritance to generate collections of custom classes
I've got two class trees in my Python code:

```<code>       BaseComponent                      BaseSeries
      /      |      \                          |
Resistor Capacitor Inductor                 ESeries
</code>```

The BaseSeries class tree implements preferred numbers such as the E-series, and generates sets of values between a pair of powers (e.g. [1.0, 2.2, 4.7, 10, 22, 47, 100, 220, 470] for the E3 series with exponents between 1 to 3).

By default, ESeries and any other instance of BaseSeries creates sequences of float objects. I'd like to use these classes to instead create sequences of Resistor, Capacitor and Inductor objects. Ideally, the individual Resistor, Capacitor, Inductor and ESeries classes would remain usable on their own (i.e. not rely on methods being implemented by other classes).

This sounds like a job for multiple inheritance, but I'm a bit confused about how best to implement this in Python (3). Ideally I'd like to just define something like:

```<code>class ResistorESeries(Resistor, ESeries):
    pass

class CapacitorESeries(Capacitor, ESeries):
    pass

class InductorESeries(Inductor, ESeries):
    pass
</code>```

in order to create classes that yield sequences of resistors, capacitors and inductors, but I don't know how best to tell BaseSeries instances to create objects of type Resistor, Capacitor and Inductor. I can think of two ways, but I can't decide which one is best, and I have a feeling there is a simpler, more Pythonic way that I'm missing:

have BaseSeries contain a property or variable pointing to the element type (e.g. Resistor) set either by the constructor, a class variable in the child class (e.g. Resistor.ELEMENT_TYPE = Resistor) or with an abstract property provided by the child class:

```<code>class BaseSeries(object):
    ...
    def elements(self):
        # loop over numbers in this series
        for v in self.values():
            yield self.element_type(v)

    @property
    @abc.abstractmethod
    def element_type(self):
        return NotImplemented

class ESeries(BaseSeries):
    ....

class BaseComponent(object):
    ...
    @property
    def element_type(self):
        return self

class Resistor(BaseComponent):
    ...

class ResistorESeries(Resistor, ESeries):
    # now BaseSeries' `element_type` property is provided by `BaseComponent`
    pass
</code>```

This would mean ESeries cannot be used on its own as a concrete object, as it does not implement this property/variable, which is not ideal.

use self when creating elements in BaseSeries, where self will, as long as Resistor is earlier in the method resolution order, refer to the desired element:

```<code>class BaseSeries(object):
    ...
    def elements(self):
        # loop over numbers in this series
        for v in self.values():
            # self here would refer to `Resistor` in
            # `ResistorESeries` instances
            yield self(v)

class ESeries(BaseSeries):
    ....

class BaseComponent(object):
    ...

class Resistor(BaseComponent):
    ...

class ResistorESeries(Resistor, ESeries):
    pass
</code>```

This has the downside that, in instances of ESeries without being used as a mix-in, self will refer to itself, which does not support the correct __init__ signature.

So, does anyone have an idea of how best to do this in a Pythonic way, with maximum ability to reuse classes on their own?

答:
You are likely mixing some concepts there - notably "instances" and "classes" - your example calls that do self(v) are perplexing.

I can't see from your design why the classes on the BaseComponent tree would need to be inherited along the BaseSeries tree: can't the component type simply be an attribute on the BaseSeries class?

It is simply a matter of using a class attribute, and in the code suggested on your first attempt, use a prosaic if statement.

```<code>class BaseSeries:
   component = None

    def elements(self):
        # loop over numbers in this series
        for v in self.values():
            yield self.component(v) if self.component else v

class Capacitor(BaseComponent):
   ...

class CapacitorSeries(BaseSeries):
   component = Capacitor
</code>```

If you think you need multiple inheritance, you can just go for your idea of using a property, and use the same "if" statement there. But if both hierarchies are that ortogonal, I don't see why force the use of multiple inheritance, just because the language permits it.

Maybe you prefer to have it the other way around: a factory method on the component tree that will take an ESeries class as input, and extract the values from that ...

Anyway, you are not making clear the disctinction of classes and instances there. Do you need to have a way to produce several subclasses of

"CapacitorESeries", each class  for a different value?
Or would you need just instances of "Capacitors", each for a different value produced on the series?

```<code>class BaseComponent:
    ...
    @classmethod
    def series_factory(self, series):
          for value in series.values():
                yield self.__class__(value)
</code>```

Of course, there could be use cases for really needing classes for everything you claim, including the factories for series of classes, but your use of self as a callable in your snippets suggests that your stance on that is not that solid.

In that case, first, you need all methods to make proper use of super. even if they ar enot supposed to exist across both hierarchies, using super will just call the proper method on the superclasses. But for methods like __init__ this is just needed.

If you design a proper __init__ method using super, and always using named parameters, your second strategy will work out of the box, just fixing the instantiating call  (to something other than self(v). Using named parameters and passing the remaining parameters to super will ensure each class in the tree consumes what it needs of those parameters - and when Python gets to the root of both your hierarchies and calls object's __init__, no parameter is remaining,

```<code>class BaseSeries:
    def __init__(self, value_min, value_max, **kwargs):
         self.value_min = value_min
         selfvalue_max = value_max
         super().__init__(**kwargs)

    def elements(self):
        # loop over numbers in this series
        for v in self.values():
            yield self.__class__(value_min = self.value_min, value_max=self.value_max, value=value)

class BaseComponent:
    def __init__(self, value, **kwargs):
         self.value = value

...

class CapacitorESeries(Capacitor, Eseries):
    pass
</code>```

Body:
I've got two class trees in my Python code:

       BaseComponent                      BaseSeries
      /      |      \                          |
Resistor Capacitor Inductor                 ESeries

The BaseSeries class tree implements preferred numbers such as the E-series, and generates sets of values between a pair of powers (e.g. [1.0, 2.2, 4.7, 10, 22, 47, 100, 220, 470] for the E3 series with exponents between 1 to 3).

By default, ESeries and any other instance of BaseSeries creates sequences of float objects. I'd like to use these classes to instead create sequences of Resistor, Capacitor and Inductor objects. Ideally, the individual Resistor, Capacitor, Inductor and ESeries classes would remain usable on their own (i.e. not rely on methods being implemented by other classes).

This sounds like a job for multiple inheritance, but I'm a bit confused about how best to implement this in Python (3). Ideally I'd like to just define something like:

class ResistorESeries(Resistor, ESeries):
    pass

class CapacitorESeries(Capacitor, ESeries):
    pass

class InductorESeries(Inductor, ESeries):
    pass

in order to create classes that yield sequences of resistors, capacitors and inductors, but I don't know how best to tell BaseSeries instances to create objects of type Resistor, Capacitor and Inductor. I can think of two ways, but I can't decide which one is best, and I have a feeling there is a simpler, more Pythonic way that I'm missing:

have BaseSeries contain a property or variable pointing to the element type (e.g. Resistor) set either by the constructor, a class variable in the child class (e.g. Resistor.ELEMENT_TYPE = Resistor) or with an abstract property provided by the child class:

class BaseSeries(object):
    ...
    def elements(self):
        # loop over numbers in this series
        for v in self.values():
            yield self.element_type(v)

    @property
    @abc.abstractmethod
    def element_type(self):
        return NotImplemented

class ESeries(BaseSeries):
    ....

class BaseComponent(object):
    ...
    @property
    def element_type(self):
        return self

class Resistor(BaseComponent):
    ...

class ResistorESeries(Resistor, ESeries):
    # now BaseSeries' `element_type` property is provided by `BaseComponent`
    pass

This would mean ESeries cannot be used on its own as a concrete object, as it does not implement this property/variable, which is not ideal.

use self when creating elements in BaseSeries, where self will, as long as Resistor is earlier in the method resolution order, refer to the desired element:

class BaseSeries(object):
    ...
    def elements(self):
        # loop over numbers in this series
        for v in self.values():
            # self here would refer to `Resistor` in
            # `ResistorESeries` instances
            yield self(v)

class ESeries(BaseSeries):
    ....

class BaseComponent(object):
    ...

class Resistor(BaseComponent):
    ...

class ResistorESeries(Resistor, ESeries):
    pass

This has the downside that, in instances of ESeries without being used as a mix-in, self will refer to itself, which does not support the correct __init__ signature.

So, does anyone have an idea of how best to do this in a Pythonic way, with maximum ability to reuse classes on their own?

Body:
You are likely mixing some concepts there - notably "instances" and "classes" - your example calls that do self(v) are perplexing.

I can't see from your design why the classes on the BaseComponent tree would need to be inherited along the BaseSeries tree: can't the component type simply be an attribute on the BaseSeries class?

It is simply a matter of using a class attribute, and in the code suggested on your first attempt, use a prosaic if statement.

class BaseSeries:
   component = None

    def elements(self):
        # loop over numbers in this series
        for v in self.values():
            yield self.component(v) if self.component else v

class Capacitor(BaseComponent):
   ...

class CapacitorSeries(BaseSeries):
   component = Capacitor

If you think you need multiple inheritance, you can just go for your idea of using a property, and use the same "if" statement there. But if both hierarchies are that ortogonal, I don't see why force the use of multiple inheritance, just because the language permits it.

Maybe you prefer to have it the other way around: a factory method on the component tree that will take an ESeries class as input, and extract the values from that ...

Anyway, you are not making clear the disctinction of classes and instances there. Do you need to have a way to produce several subclasses of

"CapacitorESeries", each class  for a different value?
Or would you need just instances of "Capacitors", each for a different value produced on the series?

class BaseComponent:
    ...
    @classmethod
    def series_factory(self, series):
          for value in series.values():
                yield self.__class__(value)

Of course, there could be use cases for really needing classes for everything you claim, including the factories for series of classes, but your use of self as a callable in your snippets suggests that your stance on that is not that solid.

In that case, first, you need all methods to make proper use of super. even if they ar enot supposed to exist across both hierarchies, using super will just call the proper method on the superclasses. But for methods like __init__ this is just needed.

If you design a proper __init__ method using super, and always using named parameters, your second strategy will work out of the box, just fixing the instantiating call  (to something other than self(v). Using named parameters and passing the remaining parameters to super will ensure each class in the tree consumes what it needs of those parameters - and when Python gets to the root of both your hierarchies and calls object's __init__, no parameter is remaining,

class BaseSeries:
    def __init__(self, value_min, value_max, **kwargs):
         self.value_min = value_min
         selfvalue_max = value_max
         super().__init__(**kwargs)

    def elements(self):
        # loop over numbers in this series
        for v in self.values():
            yield self.__class__(value_min = self.value_min, value_max=self.value_max, value=value)

class BaseComponent:
    def __init__(self, value, **kwargs):
         self.value = value

...

class CapacitorESeries(Capacitor, Eseries):
    pass


问:
is it possible to use XMLHTTP request to bind asp.net server controls
i only found websites that uses the XMLHTTP request to call an aspx page or what ever page ( make a request to a page that appears the piece of data in a div or so )

but i have a question

is it possible to use it to bind  asp.net server controls

Examples
1- bind a gridview or datalist from this XMLHTTP request
2- after click an edit button in a grid can i use  XMLHTTP request to fill some text boxes and dropdowns and other asp.net server controls
3- can i use upload files using  XMLHTTP request

i want to know if this is possible or not because Ajax and update panels are very slow and affect the server and client performance

is there another alternative if my senarios are imposible with  XMLHTTP request
where can i learn about this alternative

if this possible  where can i learn more about this
 XMLHTTP request with asp.net server side controls
instead of ajax and updatepanel

答: You should consider scrapping the ASP.NET server-side approach with XHR type implementation, and focus on the rendering on the client, if you are looking for pure AJAX performance.  This is the best and most peformant way, but requires more coding.  .NET 4 has a lot of nice improvements, and IMHO, JQuery is a must.</p>


问:
NoClassDefFoundError - RunListener : Maven-surefire / JUnit
I've been following a PluralSight course on JavaEE using eclipse and maven. I'm currently trying to write some tests, but when running mvn package from the cmd line I've been getting this error:

Execution default-test of goal org.apache.maven.plugins:maven-surefire-plugin:2.19.1:test failed: There was an error in the forked process

Sometimes it refers to:

java.lang.NoClassDefFoundError: org/junit/runner/notification/RunListener

and sometimes:

java.lang.NoClassDefFoundError: org/junit/runner/Description

I've done a bit of reading around and RunListener seems to have been introduced in JUnit 4.0. But as far as I can tell I have the correct dependency - JUnit 4.12 is in my dependency hierarchy. And I've now changed all my files to the Exercise files in order to trouble shoot this.

I'm guessing that maybe I've fundamentally misunderstood how maven and dependencies work, RE jars and the classpath, and that I still need to point eclipse or the cmd line to the JUnit jar? (I get the same errors in both). I just find that odd given that other JUnit classes are recognised in my java objects.
Here's my (pluralsight's) pom anyway:

```<code><project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

        <modelVersion>4.0.0</modelVersion>
        <groupId>com.pluralsight.javaee-getting-started.javaee-getting-started-m6</groupId>
        <artifactId>bookstore-back</artifactId>
        <version>1.0</version>
        <packaging>war</packaging>
        <name>Getting Started :: javaee-getting-started-m6 :: Testing the Repository :: Back</name>

        <properties>
            <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <!-- Test -->
            <version.junit>4.12</version.junit>
            <version.arquillian>1.1.13.5</version.arquillian>
            <version.arquillian.wildfly>2.0.2.Final</version.arquillian.wildfly>
            <version.shrinkwrap>1.2.6</version.shrinkwrap>
            <!-- Plugins -->
            <version.surefire.plugin>2.19.1</version.surefire.plugin>
        </properties>

        <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>org.arquillian</groupId>
                    <artifactId>arquillian-universe</artifactId>
                    <version>${version.arquillian}</version>
                    <type>pom</type>
                    <scope>import</scope>
                </dependency>
            </dependencies>
        </dependencyManagement>

        <dependencies>
            <dependency>
                <groupId>javax</groupId>
                <artifactId>javaee-web-api</artifactId>
                <version>7.0</version>
                <scope>provided</scope>
            </dependency>

            <!-- TEST -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${version.junit}</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.arquillian.universe</groupId>
                <artifactId>arquillian-junit</artifactId>
                <scope>test</scope>
                <type>pom</type>
            </dependency>
            <dependency>
                <groupId>org.jboss.shrinkwrap</groupId>
                <artifactId>shrinkwrap-api</artifactId>
                <version>${version.shrinkwrap}</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.wildfly.arquillian</groupId>
                <artifactId>wildfly-arquillian-container-remote</artifactId>
                <version>${version.arquillian.wildfly}</version>
                <scope>test</scope>
            </dependency>
        </dependencies>

        <build>
            <finalName>bookstore-back</finalName>

            <plugins>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>${version.surefire.plugin}</version>
                    <configuration>
                        <systemPropertyVariables>
                            <arquillian.launch>arquillian-wildfly-remote</arquillian.launch>
                        </systemPropertyVariables>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.1</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                        <compilerArguments>
                            <endorseddirs>${endorsed.dir}</endorseddirs>
                        </compilerArguments>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>2.3</version>
                    <configuration>
                        <failOnMissingWebXml>false</failOnMissingWebXml>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-dependency-plugin</artifactId>
                    <version>2.6</version>
                    <executions>
                        <execution>
                            <phase>validate</phase>
                            <goals>
                                <goal>copy</goal>
                            </goals>
                            <configuration>
                                <outputDirectory>${endorsed.dir}</outputDirectory>
                                <silent>true</silent>
                                <artifactItems>
                                    <artifactItem>
                                        <groupId>javax</groupId>
                                        <artifactId>javaee-endorsed-api</artifactId>
                                        <version>7.0</version>
                                        <type>jar</type>
                                    </artifactItem>
                                </artifactItems>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <artifactId>maven-assembly-plugin</artifactId>
                    <version>3.0.0</version>
                    <configuration>
                        <descriptorRefs>
                            <descriptorRef>src</descriptorRef>
                        </descriptorRefs>
                    </configuration>
                </plugin>
            </plugins>
        </build>

    </project>
</code>```

Am I on the right track with the classpath idea?

答: Delete your .m2 folder where Maven stores it's dependencies and do another build. Sometimes jar files get corrupted (ex. Junit jar file might be corrupted, which could explain why it does not find classes).</p>

Body:
I've been following a PluralSight course on JavaEE using eclipse and maven. I'm currently trying to write some tests, but when running mvn package from the cmd line I've been getting this error:

Execution default-test of goal org.apache.maven.plugins:maven-surefire-plugin:2.19.1:test failed: There was an error in the forked process

Sometimes it refers to:

java.lang.NoClassDefFoundError: org/junit/runner/notification/RunListener

and sometimes:

java.lang.NoClassDefFoundError: org/junit/runner/Description

I've done a bit of reading around and RunListener seems to have been introduced in JUnit 4.0. But as far as I can tell I have the correct dependency - JUnit 4.12 is in my dependency hierarchy. And I've now changed all my files to the Exercise files in order to trouble shoot this.

I'm guessing that maybe I've fundamentally misunderstood how maven and dependencies work, RE jars and the classpath, and that I still need to point eclipse or the cmd line to the JUnit jar? (I get the same errors in both). I just find that odd given that other JUnit classes are recognised in my java objects.
Here's my (pluralsight's) pom anyway:

<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

        <modelVersion>4.0.0</modelVersion>
        <groupId>com.pluralsight.javaee-getting-started.javaee-getting-started-m6</groupId>
        <artifactId>bookstore-back</artifactId>
        <version>1.0</version>
        <packaging>war</packaging>
        <name>Getting Started :: javaee-getting-started-m6 :: Testing the Repository :: Back</name>

        <properties>
            <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

            <version.junit>4.12</version.junit>
            <version.arquillian>1.1.13.5</version.arquillian>
            <version.arquillian.wildfly>2.0.2.Final</version.arquillian.wildfly>
            <version.shrinkwrap>1.2.6</version.shrinkwrap>

            <version.surefire.plugin>2.19.1</version.surefire.plugin>
        </properties>

        <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>org.arquillian</groupId>
                    <artifactId>arquillian-universe</artifactId>
                    <version>${version.arquillian}</version>
                    <type>pom</type>
                    <scope>import</scope>
                </dependency>
            </dependencies>
        </dependencyManagement>

        <dependencies>
            <dependency>
                <groupId>javax</groupId>
                <artifactId>javaee-web-api</artifactId>
                <version>7.0</version>
                <scope>provided</scope>
            </dependency>

            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${version.junit}</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.arquillian.universe</groupId>
                <artifactId>arquillian-junit</artifactId>
                <scope>test</scope>
                <type>pom</type>
            </dependency>
            <dependency>
                <groupId>org.jboss.shrinkwrap</groupId>
                <artifactId>shrinkwrap-api</artifactId>
                <version>${version.shrinkwrap}</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.wildfly.arquillian</groupId>
                <artifactId>wildfly-arquillian-container-remote</artifactId>
                <version>${version.arquillian.wildfly}</version>
                <scope>test</scope>
            </dependency>
        </dependencies>

        <build>
            <finalName>bookstore-back</finalName>

            <plugins>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>${version.surefire.plugin}</version>
                    <configuration>
                        <systemPropertyVariables>
                            <arquillian.launch>arquillian-wildfly-remote</arquillian.launch>
                        </systemPropertyVariables>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.1</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                        <compilerArguments>
                            <endorseddirs>${endorsed.dir}</endorseddirs>
                        </compilerArguments>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>2.3</version>
                    <configuration>
                        <failOnMissingWebXml>false</failOnMissingWebXml>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-dependency-plugin</artifactId>
                    <version>2.6</version>
                    <executions>
                        <execution>
                            <phase>validate</phase>
                            <goals>
                                <goal>copy</goal>
                            </goals>
                            <configuration>
                                <outputDirectory>${endorsed.dir}</outputDirectory>
                                <silent>true</silent>
                                <artifactItems>
                                    <artifactItem>
                                        <groupId>javax</groupId>
                                        <artifactId>javaee-endorsed-api</artifactId>
                                        <version>7.0</version>
                                        <type>jar</type>
                                    </artifactItem>
                                </artifactItems>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <artifactId>maven-assembly-plugin</artifactId>
                    <version>3.0.0</version>
                    <configuration>
                        <descriptorRefs>
                            <descriptorRef>src</descriptorRef>
                        </descriptorRefs>
                    </configuration>
                </plugin>
            </plugins>
        </build>

    </project>

Am I on the right track with the classpath idea?


问:
How do I set state in React when there is no class or constructor?
I'm looking at the default demo React code in https://codesandbox.io/s/new, which comes out like this:

```<code>import React from 'react';
import { render } from 'react-dom';
import Hello from './Hello';

const App = () => <Hello name="CodeSandbox" />;

render(<App />, document.getElementById('root'));
</code>```

This is different than many of the other examples I've seen, which usually have something more like:

```<code>class Layout extends React.Component {
  constructor(props) {
    super(props);
    this.state = {...};
  }
  render() {...}
}
</code>```

Since the codesandbox example doesn't have a class or a constructor, I don't have a place to put this.state. So how and where would I add a state?

答:
You can't.

```<code>const App = () => <Hello name='CodeSandbox' />;
</code>```

That is an stateless component.

The only way to interact with that kind of components is through props.

```<code>const App = ({ name }) => <Hello name={name} />;

render(<App name='CodeSandbox' />, document.getElementById('root'));
</code>```

Body:
I'm looking at the default demo React code in https://codesandbox.io/s/new, which comes out like this:

import React from 'react';
import { render } from 'react-dom';
import Hello from './Hello';

const App = () => <Hello name="CodeSandbox" />;

render(<App />, document.getElementById('root'));

This is different than many of the other examples I've seen, which usually have something more like:

class Layout extends React.Component {
  constructor(props) {
    super(props);
    this.state = {...};
  }
  render() {...}
}

Since the codesandbox example doesn't have a class or a constructor, I don't have a place to put this.state. So how and where would I add a state?

Body:
You can't.

const App = () => <Hello name='CodeSandbox' />;

That is an stateless component.

The only way to interact with that kind of components is through props.

const App = ({ name }) => <Hello name={name} />;

render(<App name='CodeSandbox' />, document.getElementById('root'));


问:
How to make Bash's read abort after trapping interrupt?
Consider:

```<code>$ cat b.sh
#!/bin/bash

trap 'echo $$ was interrupted' INT
read foo
echo done
$ ./b.sh
^C27104 was interrupted
^C27104 was interrupted
^C27104 was interrupted
done
$
</code>```

(ctrl-c was hit 3 times, followed by ctrl-d)

I'd like the read to abort after execution of the trap.  Is there a clean way to make that happen?

答:
Seems like not interrupting immediately is a Bash non-POSIX extension (see read_builtin in read.def of Bash builtin source (look for posixly_correct)).

You can override this behavior, and exit on the first Ctrl+C by forcing POSIX behavior for read (by setting the POSIXLY_CORRECT environment variable):

```<code>#!/bin/bash
trap 'echo $$ was interrupted' INT
POSIXLY_CORRECT=1 read foo
echo done
</code>```

Body:
Consider:

$ cat b.sh
#!/bin/bash

trap 'echo $$ was interrupted' INT
read foo
echo done
$ ./b.sh
^C27104 was interrupted
^C27104 was interrupted
^C27104 was interrupted
done
$

(ctrl-c was hit 3 times, followed by ctrl-d)

I'd like the read to abort after execution of the trap.  Is there a clean way to make that happen?

Body:
Seems like not interrupting immediately is a Bash non-POSIX extension (see read_builtin in read.def of Bash builtin source (look for posixly_correct)).

You can override this behavior, and exit on the first Ctrl+C by forcing POSIX behavior for read (by setting the POSIXLY_CORRECT environment variable):

#!/bin/bash
trap 'echo $$ was interrupted' INT
POSIXLY_CORRECT=1 read foo
echo done


问:
How to get content-desc in Android app using appium
I am writing automation test for Android app.

When I am trying to get content-desc for article title. I am not able to fetch it.

FYI I don't have text.

```<code>List<WebElement> arrayOfProperties2 = driver.findElementsByClassName("android.view.View");

for (WebElement property : arrayOfProperties2){
    System.out.println("property" + property.getClass());

    String contentDesc = property.getAttribute("name");
    String contentDesc1 = property.getAttribute("className");
    String contentDesc2 = property.getAttribute("resourceId");
    System.out.println("contentDesc" + contentDesc);
    System.out.println("contentDesc1" + contentDesc1);
    System.out.println("contentDesc2" + contentDesc2);
}
</code>```

Result:-

```<code>contentDesc
contentDesc1android.view.View
contentDesc2
</code>```

答:
Try this</p>

```<code>WebElement webElement = driver.findElement(By.xpath("//android.view.View[@content-desc='Click to Resize']"));
webElement.click();
</code>```

Body:
I am writing automation test for Android app.

When I am trying to get content-desc for article title. I am not able to fetch it.

FYI I don't have text.

List<WebElement> arrayOfProperties2 = driver.findElementsByClassName("android.view.View");

for (WebElement property : arrayOfProperties2){
    System.out.println("property" + property.getClass());

    String contentDesc = property.getAttribute("name");
    String contentDesc1 = property.getAttribute("className");
    String contentDesc2 = property.getAttribute("resourceId");
    System.out.println("contentDesc" + contentDesc);
    System.out.println("contentDesc1" + contentDesc1);
    System.out.println("contentDesc2" + contentDesc2);
}

Result:-

contentDesc
contentDesc1android.view.View
contentDesc2

Body:
Try this

WebElement webElement = driver.findElement(By.xpath("//android.view.View[@content-desc='Click to Resize']"));
webElement.click();


问:
MYSQL Query Cross Database Join return NULL
```<code>select t1.CardID,t2.Description,t5.BioData
from db2.tblemployeeinfob t1
left join (db2.tbldepartments t2,db1.tblbiometrics t5)
on
(t1.Department = t2.DepartmentID and
t1.CardID=t5.CardID
)
</code>```

Return Result is 1420 | (NULL) | (NULL)

Expected Result is  1420 | DB2_Description_Value | DB1_BioData_value

if i remove cross database join, like remove db1 then query will work fine to join remaining two tables from same database.

if i do cross database join between db1 and db2, even table t2 from same database db2 is returning NULL.

Where is problem with my Query, so i can get value from both databases.

答:
```<code>            <?php
            include('../dbcon.php');
            include('../session.php');
            if (isset($_POST['delete_user'])){
            $id=$_POST['selector'];
            $class_id = $_POST['teacher_class_id'];
             $get_id=$_POST['get_id'];
            $N = count($id);
            for($i=0; $i < $N; $i++)
            {
                $result = mysql_query("select * from files  where file_id = '$id[$i]' ")or die(mysql_error());
                while($row = mysql_fetch_array($result)){

                $fname = $row['fname'];
                $floc = $row['floc'];
                $fdesc = $row['fdesc'];
                $uploaded_by = $row['uploaded_by'];

                mysql_query("insert into files (floc,fdatein,fdesc,class_id,fname,uploaded_by) value('$floc',NOW(),'$fdesc','$class_id','$fname','$uploaded_by')")or die(mysql_error());

                }
            }
            ?>
            <script>
            window.location = 'downloadable.php<?php echo '?id='.$get_id; ?>';
            </script>
            <?php
            }

            if (isset($_POST['copy'])){
            $id=$_POST['selector'];

            $N = count($id);
            for($i=0; $i < $N; $i++)
            {
                $result = mysql_query("select * from files  where file_id = '$id[$i]' ")or die(mysql_error());
                while($row = mysql_fetch_array($result)){

                    $fname = $row['fname'];
                $floc = $row['floc'];
                $fdesc = $row['fdesc'];

                mysql_query("insert into teacher_backpack (floc,fdatein,fdesc,teacher_id,fname) value('$floc',NOW(),'$fdesc','$session_id','$fname')")or die(mysql_error());

                }
            }
            ?>
            <script>
            window.location = 'backpack.php';
            </script>
            <?php
            }
            ?>
            <?php

            if (isset($_POST['share'])){
            $id=$_POST['selector'];
            $teacher_id = $_POST['teacher_id1'];
            echo $teacher_id ;
            $N = count($id);
            for($i=0; $i < $N; $i++)
            {
                $result = mysql_query("select * from files  where file_id = '$id[$i]' ")or die(mysql_error());
                while($row = mysql_fetch_array($result)){

                    $fname = $row['fname'];
                $floc = $row['floc'];
                $fdesc = $row['fdesc'];

                mysql_query("insert into teacher_shared (floc,fdatein,fdesc,teacher_id,fname,shared_teacher_id) value('$floc',NOW(),'$fdesc','$session_id','$fname','$teacher_id')")or die(mysql_error());

                }
            }
            ?>
            <script>
             window.location = 'tambah_share_file.php';
            </script>
            <?php
            }
            ?>
</code>```

Body:
select t1.CardID,t2.Description,t5.BioData
from db2.tblemployeeinfob t1
left join (db2.tbldepartments t2,db1.tblbiometrics t5)
on
(t1.Department = t2.DepartmentID and
t1.CardID=t5.CardID
)

Return Result is 1420 | (NULL) | (NULL)

Expected Result is  1420 | DB2_Description_Value | DB1_BioData_value

if i remove cross database join, like remove db1 then query will work fine to join remaining two tables from same database.

if i do cross database join between db1 and db2, even table t2 from same database db2 is returning NULL.

Where is problem with my Query, so i can get value from both databases.


问:
How do i reverse each character in a string?
```<code>class Solution {
public String reverseWords(String s) {
    int count = 0;
    int current = 0;
    StringBuilder build = new StringBuilder();
    for(int i = 0; i< s.length(); i++){
        count++;
        current = count;
        if(s.charAt(i) == ' '){
            while(current > 0){
                build.append(s.charAt(current - 1));
                current--;
            }
            build.append(s.charAt(i));
        }

    }
    return build.toString();
}
}
</code>```

I am having trouble understanding why this doesn't work. I went through the
entire code a couple of times but there seems to be an issue.

Input :          "Let's take LeetCode contest"
my answer:       " s'teL  ekat s'teL  edoCteeL ekat s'teL "
correct answer:  "s'teL ekat edoCteeL tsetnoc"
whats going on?

答:
This is the easy way:</p>

```<code>return Arrays.stream(s.split(" " ))
        .map(StringBuilder::new)
        .map(StringBuilder::reverse)
        .map(StringBuilder::toString)
        .collect(Collectors.joining(" "));
</code>```

Body:
class Solution {
public String reverseWords(String s) {
    int count = 0;
    int current = 0;
    StringBuilder build = new StringBuilder();
    for(int i = 0; i< s.length(); i++){
        count++;
        current = count;
        if(s.charAt(i) == ' '){
            while(current > 0){
                build.append(s.charAt(current - 1));
                current--;
            }
            build.append(s.charAt(i));
        }

    }
    return build.toString();
}
}

I am having trouble understanding why this doesn't work. I went through the
entire code a couple of times but there seems to be an issue.

Input :          "Let's take LeetCode contest"
my answer:       " s'teL  ekat s'teL  edoCteeL ekat s'teL "
correct answer:  "s'teL ekat edoCteeL tsetnoc"
whats going on?

Body:
This is the easy way:

return Arrays.stream(s.split(" " ))
        .map(StringBuilder::new)
        .map(StringBuilder::reverse)
        .map(StringBuilder::toString)
        .collect(Collectors.joining(" "));


问:
How to download partial s3 aws cli using the terminal? Its a 1 TB json/xml file, I only want 100-200MB of sequential, numbered files
Here is what I have tried:
 aws s3 cp s3://bucket name/folder ~/downloads --range bytes=0-200000000. I get an unknown options range error.

Please provide me some guidance. I have about 1 TB of data, but I would like to do a partial download of about 100 MB of sequential, numbered files to my external hard drive.
Thank you.

答:
To perform this for a single file, you could use the AWS S3 CLI api:

aws s3api get-object --bucket YOUR_BUCKET --key YOUR_FOLDER/KEY --range 100 TARGET_FILE_NAME

Note the use of s3api instead of s3.

The range parameter here will determine which range of bytes of your file you'd like to download.

Two weeks ago, however, AWS announced Amazon S3 Select.

Amazon S3 Select is now available in Preview. S3 Select is a new Amazon S3 capability designed to pull out only the data you need from an object, dramatically improving the performance and reducing the cost of applications that need to access data in S3.

It's currently in preview but you can opt-in for it and once you're approved should be able to use this API.

Click here to find out more.

EDIT

You can use the sync api operation of the S3 service to download contents of a bucket.

A possible solution would be aws s3 sync s3://bucketname .

To include or exclude certain files, use the flags --include "*.json" and --exclude "*test.json" respectively


问:
How to disable scrolling temporarily?
I'm using the scrollTo jQuery plugin and would like to know if it is somehow possible to temporarily disable scrolling on the window element through Javascript? The reason I'd like to disable scrolling is that when you scroll while scrollTo is animating, it gets really ugly ;)

Of course, I could do a $("body").css("overflow", "hidden"); and then put it back to auto when the animation stops, but it would be better if the scrollbar was still visible but inactive.

答:
The scroll event cannot be canceled. But you can do it by canceling these interaction events:

Mouse & Touch scroll and Buttons associated with scrolling.

[Working demo]

```<code>// left: 37, up: 38, right: 39, down: 40,
// spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36
var keys = {37: 1, 38: 1, 39: 1, 40: 1};

function preventDefault(e) {
  e.preventDefault();
}

function preventDefaultForScrollKeys(e) {
  if (keys[e.keyCode]) {
    preventDefault(e);
    return false;
  }
}

// modern Chrome requires { passive: false } when adding event
var supportsPassive = false;
try {
  window.addEventListener("test", null, Object.defineProperty({}, 'passive', {
    get: function () { supportsPassive = true; }
  }));
} catch(e) {}

var wheelOpt = supportsPassive ? { passive: false } : false;
var wheelEvent = 'onwheel' in document.createElement('div') ? 'wheel' : 'mousewheel';

// call this to Disable
function disableScroll() {
  window.addEventListener('DOMMouseScroll', preventDefault, false); // older FF
  window.addEventListener(wheelEvent, preventDefault, wheelOpt); // modern desktop
  window.addEventListener('touchmove', preventDefault, wheelOpt); // mobile
  window.addEventListener('keydown', preventDefaultForScrollKeys, false);
}

// call this to Enable
function enableScroll() {
  window.removeEventListener('DOMMouseScroll', preventDefault, false);
  window.removeEventListener(wheelEvent, preventDefault, wheelOpt);
  window.removeEventListener('touchmove', preventDefault, wheelOpt);
  window.removeEventListener('keydown', preventDefaultForScrollKeys, false);
}
</code>```

UPDATE: fixed Chrome desktop and modern mobile browsers with passive listeners

Title: How to disable scrolling temporarily?

Body:
The scroll event cannot be canceled. But you can do it by canceling these interaction events:

Mouse & Touch scroll and Buttons associated with scrolling.

[Working demo]

// left: 37, up: 38, right: 39, down: 40,
// spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36
var keys = {37: 1, 38: 1, 39: 1, 40: 1};

function preventDefault(e) {
  e.preventDefault();
}

function preventDefaultForScrollKeys(e) {
  if (keys[e.keyCode]) {
    preventDefault(e);
    return false;
  }
}

// modern Chrome requires { passive: false } when adding event
var supportsPassive = false;
try {
  window.addEventListener("test", null, Object.defineProperty({}, 'passive', {
    get: function () { supportsPassive = true; }
  }));
} catch(e) {}

var wheelOpt = supportsPassive ? { passive: false } : false;
var wheelEvent = 'onwheel' in document.createElement('div') ? 'wheel' : 'mousewheel';

// call this to Disable
function disableScroll() {
  window.addEventListener('DOMMouseScroll', preventDefault, false); // older FF
  window.addEventListener(wheelEvent, preventDefault, wheelOpt); // modern desktop
  window.addEventListener('touchmove', preventDefault, wheelOpt); // mobile
  window.addEventListener('keydown', preventDefaultForScrollKeys, false);
}

// call this to Enable
function enableScroll() {
  window.removeEventListener('DOMMouseScroll', preventDefault, false);
  window.removeEventListener(wheelEvent, preventDefault, wheelOpt);
  window.removeEventListener('touchmove', preventDefault, wheelOpt);
  window.removeEventListener('keydown', preventDefaultForScrollKeys, false);
}

UPDATE: fixed Chrome desktop and modern mobile browsers with passive listeners


问:
Adding a Image Within a switch - PaintComponent Override
Im trying to add a small burger.jpg img to a game I am making. The burger should be added whenever 'f'(food) is passed in Switch. Im having issues implementing this in my code.

I was originally just filling an orange rectangle g2.fillRect(), but I would like to replace this with an actual image instead. I've tried scaling the image and adding it but it doesn't show up. If I replace theg2.fillRect at the end of the for loop, it makes every square a burger, instead of just the 'f'

How would I do this?

```<code>private class Game extends JPanel {

    BufferedImage img = null;

    @Override
    public void paintComponent(Graphics g2) {

        super.paintComponent(g2);

        try {

            img = ImageIO.read(new File("src/burger.jpg"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        BufferedImage otherImage = new BufferedImage(50, 50,
                BufferedImage.TYPE_INT_RGB);
        Graphics g = otherImage.createGraphics();

        int width = getWidth() / game.getBoardWidth();
        int height = getHeight() / game.getBoardHeight();

        char[] symbols = game.toString().toCharArray();

        int x = 0;
        int y = 0;

        for (char c : symbols) {

            switch (c) {
            case 'Q':
                g2.setColor(Color.BLACK);
                break;
            case 'H':
                g2.setColor(Color.GREEN);
                break;
            case 'f':
                //g2.setColor(Color.ORANGE);
                g2.drawImage(img, x, y, width, height, null);
                break;
            case '-':
                g2.setColor(Color.WHITE);
                break;
            case '\n':
                y += height;
                x = 0;
            }

           //g2.drawImage(img, x, y, width, height, null);
           g2.fillRect(x, y, width, height);
            x += width;
        }
    }

}
</code>```

答:
Haven't tested yet, but this is what is happening right now in your program:

Get a symbol

if ('f') then drawImage then fillRect

What you want is:

Get a symbol

if('f') then drawImage otherwise fillRect

So you compare:

```<code>if (symbol == 'f') {
    g2.drawImage(img, x, y, width, height, null);
} else {
    g2.fillRect(x, y, width, height);
}
</code>```

Or what I'd do is:

```<code>switch (c) {
    case 'Q':
        g2.setColor(Color.BLACK);
        g2.fillRect(x, y, width, height);
        break;
    case 'H':
        g2.setColor(Color.GREEN);
        g2.fillRect(x, y, width, height);
        break;
    case 'f':
        //g2.setColor(Color.ORANGE);
        g2.drawImage(img, x, y, width, height, null);
        break;
    case '-':
        g2.setColor(Color.WHITE);
        g2.fillRect(x, y, width, height);
        break;
    case '\n':
        y += height;
        x = 0;
}
</code>```

And comment out or remove the last call to:

```<code>g2.fillRect(x, y, width, height);
</code>```

TIP:

```<code>try {
    img = ImageIO.read(new File("src/burger.jpg"));
} catch (IOException e) {
    e.printStackTrace();
}
</code>```

Those lines should be in the constructor, not in the paintComponent method, it gets called by Swing several times, doing so might slow or block / freeze your application until it finishes reading it.

Also, you're not using otherImage variable so you can delete it as well...

Body:
Im trying to add a small burger.jpg img to a game I am making. The burger should be added whenever 'f'(food) is passed in Switch. Im having issues implementing this in my code.

I was originally just filling an orange rectangle g2.fillRect(), but I would like to replace this with an actual image instead. I've tried scaling the image and adding it but it doesn't show up. If I replace theg2.fillRect at the end of the for loop, it makes every square a burger, instead of just the 'f'

How would I do this?

private class Game extends JPanel {

    BufferedImage img = null;

    @Override
    public void paintComponent(Graphics g2) {

        super.paintComponent(g2);

        try {

            img = ImageIO.read(new File("src/burger.jpg"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        BufferedImage otherImage = new BufferedImage(50, 50,
                BufferedImage.TYPE_INT_RGB);
        Graphics g = otherImage.createGraphics();

        int width = getWidth() / game.getBoardWidth();
        int height = getHeight() / game.getBoardHeight();

        char[] symbols = game.toString().toCharArray();

        int x = 0;
        int y = 0;

        for (char c : symbols) {

            switch (c) {
            case 'Q':
                g2.setColor(Color.BLACK);
                break;
            case 'H':
                g2.setColor(Color.GREEN);
                break;
            case 'f':
                //g2.setColor(Color.ORANGE);
                g2.drawImage(img, x, y, width, height, null);
                break;
            case '-':
                g2.setColor(Color.WHITE);
                break;
            case '\n':
                y += height;
                x = 0;
            }

           //g2.drawImage(img, x, y, width, height, null);
           g2.fillRect(x, y, width, height);
            x += width;
        }
    }

}

Body:
Haven't tested yet, but this is what is happening right now in your program:

Get a symbol

if ('f') then drawImage then fillRect

What you want is:

Get a symbol

if('f') then drawImage otherwise fillRect

So you compare:

if (symbol == 'f') {
    g2.drawImage(img, x, y, width, height, null);
} else {
    g2.fillRect(x, y, width, height);
}

Or what I'd do is:

switch (c) {
    case 'Q':
        g2.setColor(Color.BLACK);
        g2.fillRect(x, y, width, height);
        break;
    case 'H':
        g2.setColor(Color.GREEN);
        g2.fillRect(x, y, width, height);
        break;
    case 'f':
        //g2.setColor(Color.ORANGE);
        g2.drawImage(img, x, y, width, height, null);
        break;
    case '-':
        g2.setColor(Color.WHITE);
        g2.fillRect(x, y, width, height);
        break;
    case '\n':
        y += height;
        x = 0;
}

And comment out or remove the last call to:

g2.fillRect(x, y, width, height);

TIP:

try {
    img = ImageIO.read(new File("src/burger.jpg"));
} catch (IOException e) {
    e.printStackTrace();
}

Those lines should be in the constructor, not in the paintComponent method, it gets called by Swing several times, doing so might slow or block / freeze your application until it finishes reading it.

Also, you're not using otherImage variable so you can delete it as well...


问:
Query with GROUP BY and ORDER BY not working when multiple columns in SELECT are chosen
I'm updating an old website and one of the queries isn't working anymore:

```<code>SELECT * FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2
</code>```

I noticed if I dropped the GROUP BY it works, but the result set doesn't match the original:

```<code>SELECT * FROM tbl WHERE col1 IS NULL ORDER BY col2
</code>```

So I tried reading up on GROUP BY in the docs to see what might be the issue, and it seemed to suggest not using * to select all the fields, but explicitly using the column name so I tried it with just the column that was being ordered and grouped:

```<code>SELECT col2 FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2
</code>```

Which works but after looking through the code the query requires 2 columns in the query so whoever added * was overdoing it, but if I add that column produces an error, similarly adding a third column produces the same error:

```<code>SELECT col2, col3 FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2
SELECT col1, col2, col3 FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2
</code>```

Can anyone tell me why this last query doesn't work?  I can't decipher why from the docs, but this is the minimum query required to get the result set I need.

Running the query in Adminer I get this error

```<code>Error in query (1055): Expression #2 of SELECT list is not in GROUP BY
clause and contains nonaggregated column 'name.table.column'
which is not functionally dependent on columns in GROUP BY clause; this is
incompatible with sql_mode=only_full_group_by
</code>```

答:
You need to be careful when you use GROUP BY. Once you understand what GROUP BY does, you will know the issue yourself. It does an aggregation on your data or in other words, it reduces your data by doing some operation on the raw entries and creating new reduced number of entries on which some aggregation function has been applied(SUM, COUNT, AVG, etc.)

The fields you provide in the GROUP BY clause represents the level of aggregation/roll-up you are going for.

```<code>SELECT col2, col3 FROM tbl WHERE col1 IS NULL GROUP BY col1 ORDER BY col1
</code>```

Here you are trying to do the aggregation at col1 level, meaning that for every distinct value present in column col1, there will be some operation done on some other columns you provide in SELECT clause(here col2,col3) so that in the output you have non-repeating values in col1 and some rolled-up values of col2 and col3 against each distinct col1 value based on what function you apply(SUM, COUNT, AVG, etc.).

How do you apply this function? That is what is missing in your above query. To solve it, you need to apply some aggregation function on the fields that are present in the SELECT clause but not in GROUP BY clause. Taking an example of SUM, try this:

```<code>SELECT SUM(col2), SUM(col3) FROM tbl WHERE col1 IS NULL GROUP BY col1 ORDER BY col1
</code>```

OR for a better idea, removing WHERE filter and checking the output by running:

```<code>SELECT col1, SUM(col2), SUM(col3) FROM tbl GROUP BY col1 ORDER BY col1
</code>```

Additionally, the reason why your other query

```<code>SELECT col2 FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2
</code>```

worked is because you need not apply aggregation to the field(here col2) which is present in the GROUP BY clause.

Body:
I'm updating an old website and one of the queries isn't working anymore:

SELECT * FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2

I noticed if I dropped the GROUP BY it works, but the result set doesn't match the original:

SELECT * FROM tbl WHERE col1 IS NULL ORDER BY col2

So I tried reading up on GROUP BY in the docs to see what might be the issue, and it seemed to suggest not using * to select all the fields, but explicitly using the column name so I tried it with just the column that was being ordered and grouped:

SELECT col2 FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2

Which works but after looking through the code the query requires 2 columns in the query so whoever added * was overdoing it, but if I add that column produces an error, similarly adding a third column produces the same error:

SELECT col2, col3 FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2
SELECT col1, col2, col3 FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2

Can anyone tell me why this last query doesn't work?  I can't decipher why from the docs, but this is the minimum query required to get the result set I need.

Running the query in Adminer I get this error

Error in query (1055): Expression #2 of SELECT list is not in GROUP BY
clause and contains nonaggregated column 'name.table.column'
which is not functionally dependent on columns in GROUP BY clause; this is
incompatible with sql_mode=only_full_group_by

Body:
You need to be careful when you use GROUP BY. Once you understand what GROUP BY does, you will know the issue yourself. It does an aggregation on your data or in other words, it reduces your data by doing some operation on the raw entries and creating new reduced number of entries on which some aggregation function has been applied(SUM, COUNT, AVG, etc.)

The fields you provide in the GROUP BY clause represents the level of aggregation/roll-up you are going for.

SELECT col2, col3 FROM tbl WHERE col1 IS NULL GROUP BY col1 ORDER BY col1

Here you are trying to do the aggregation at col1 level, meaning that for every distinct value present in column col1, there will be some operation done on some other columns you provide in SELECT clause(here col2,col3) so that in the output you have non-repeating values in col1 and some rolled-up values of col2 and col3 against each distinct col1 value based on what function you apply(SUM, COUNT, AVG, etc.).

How do you apply this function? That is what is missing in your above query. To solve it, you need to apply some aggregation function on the fields that are present in the SELECT clause but not in GROUP BY clause. Taking an example of SUM, try this:

SELECT SUM(col2), SUM(col3) FROM tbl WHERE col1 IS NULL GROUP BY col1 ORDER BY col1

OR for a better idea, removing WHERE filter and checking the output by running:

SELECT col1, SUM(col2), SUM(col3) FROM tbl GROUP BY col1 ORDER BY col1

Additionally, the reason why your other query

SELECT col2 FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2

worked is because you need not apply aggregation to the field(here col2) which is present in the GROUP BY clause.


问:
Using Java Inheritance, how do I refer to a specific subclass while I'm in the superclass
I have 3 different Classes:

Class 1 (Super Class)
Class 2 (SubClass)
Class 3 (SubClass)

In Class 1, I have an instance variable called NUMBER, and a method called myNumber.

I am trying to make an if/else statement, so that if we are calling the .myNumber method for Class 2, NUMBER equals 7.  However, in Class 3, I want that number to equal 8.

My if else statement looked like this:

```<code>if (Class2)
{
   myNumber = 7
}

else if (Class3)
 {
   myNumber = 8
 }
</code>```

However, I have no idea how to refer to Class2 and Class3, while I'm making the code in Class3.

Any help would be great!  :)

答:
You don't understand polymorphysm. Instead of use if/else statements you need to extends from desired class and introduce new behavior with help of overriding methods. All code that accept parent class will accept child classes because all of them is-a parent (https://en.wikipedia.org/wiki/Is-a), and can do anything what parent do, but may differ they behavior. Example:

```<code>class ClassOne {
    private int number = 1;

    public int getNumber() {
        return number;
    }

}

class ClassTwo extends ClassOne {

    public int getNumber() {
        return 2;
}

class ClassThree extends ClassOne {

    public int getNumber() {
        return 3;
}
</code>```

Test class:

```<code> public class TestClass {

        public static void main(String... args) {
            ClassOne classOne = new ClassOne();
            ClassOne classTwo = new ClassTwo();
            ClassOne classThree = new ClassThree();

            TestClass test = new TestClass();
            test.printNumberFrom(classOne);   // prints 1
            test.printNumberFrom(classTwo);   // prints 2
            test.printNumberFrom(classThree); // prints 3
        }

        //knows only about ClassOne but may accept it's childs
        public void printNumberFrom(ClassOne classOne) {
            System.out.println(classOne.getNumber());
        }

    }
</code>```

Body:
I have 3 different Classes:

Class 1 (Super Class)
Class 2 (SubClass)
Class 3 (SubClass)

In Class 1, I have an instance variable called NUMBER, and a method called myNumber.

I am trying to make an if/else statement, so that if we are calling the .myNumber method for Class 2, NUMBER equals 7.  However, in Class 3, I want that number to equal 8.

My if else statement looked like this:

if (Class2)
{
   myNumber = 7
}

else if (Class3)
 {
   myNumber = 8
 }

However, I have no idea how to refer to Class2 and Class3, while I'm making the code in Class3.

Any help would be great!  :)

Body:
You don't understand polymorphysm. Instead of use if/else statements you need to extends from desired class and introduce new behavior with help of overriding methods. All code that accept parent class will accept child classes because all of them is-a parent (https://en.wikipedia.org/wiki/Is-a), and can do anything what parent do, but may differ they behavior. Example:

class ClassOne {
    private int number = 1;

    public int getNumber() {
        return number;
    }

}

class ClassTwo extends ClassOne {

    public int getNumber() {
        return 2;
}

class ClassThree extends ClassOne {

    public int getNumber() {
        return 3;
}

Test class:

 public class TestClass {

        public static void main(String... args) {
            ClassOne classOne = new ClassOne();
            ClassOne classTwo = new ClassTwo();
            ClassOne classThree = new ClassThree();

            TestClass test = new TestClass();
            test.printNumberFrom(classOne);   // prints 1
            test.printNumberFrom(classTwo);   // prints 2
            test.printNumberFrom(classThree); // prints 3
        }

        //knows only about ClassOne but may accept it's childs
        public void printNumberFrom(ClassOne classOne) {
            System.out.println(classOne.getNumber());
        }

    }


问:
Auth0 Angular 2 sso single sign on
I have just started playing around with auth0 and I am trying to create a proof of concept.

I am trying to create a single sign on solution in angular 2. Can anyone point me to any example code that does this?

答:
I know It is an old question, But if anyone is looking for the solution then
Github Repo example of sso in angular 2

And a Detail explanation of this example.

https://auth0.com/blog/angular-2-authentication/

I hope It will help somebody.

Title: Auth0 Angular 2 sso single sign on


问:
Set of numbers evenly distributed between a min and max on log scale
I have a graph on a log scale with a min and max. I need to specify ticks on this scale. I would like to specify 5 ticks. However, the issue is that I would like the ticks to be evenly distributed. At first naively, I tried this:

```<code>while (tickValue <= upperTickValue) {
   tickValues.push(
       this.formatNumber.toView(tickValue, 3)
   );
   tickValue = tickValue + interval;
}
</code>```

However, this does not produce evenly spaced ticks on a logarithmic scale (duh).

I need to have a set of numbers that is evenly spaced on the log scale. So, for example, if I was graphing 0.01 to 100, a correct answer would be:

```<code>[0.01, 0.1, 1, 10, 100]
</code>```

Thanks in advance.

答:
You could take the nth root of the given values for a scale. Take the min and max value for preventing floating point errors.

function parts(min, max, scale) {
    var f = Math.pow(max / min, 1 / --scale),
        result = [min];

    while (--scale) {
        result.push(result[result.length - 1] * f);

    }
    result.push(max);
    return result;
}

console.log(parts(0.01, 100, 5));
console.log(parts(4, 5, 5));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have a graph on a log scale with a min and max. I need to specify ticks on this scale. I would like to specify 5 ticks. However, the issue is that I would like the ticks to be evenly distributed. At first naively, I tried this:

while (tickValue <= upperTickValue) {
   tickValues.push(
       this.formatNumber.toView(tickValue, 3)
   );
   tickValue = tickValue + interval;
}

However, this does not produce evenly spaced ticks on a logarithmic scale (duh).

I need to have a set of numbers that is evenly spaced on the log scale. So, for example, if I was graphing 0.01 to 100, a correct answer would be:

[0.01, 0.1, 1, 10, 100]

Thanks in advance.

Body:
You could take the nth root of the given values for a scale. Take the min and max value for preventing floating point errors.

function parts(min, max, scale) {
    var f = Math.pow(max / min, 1 / --scale),
        result = [min];

    while (--scale) {
        result.push(result[result.length - 1] * f);

    }
    result.push(max);
    return result;
}

console.log(parts(0.01, 100, 5));
console.log(parts(4, 5, 5));

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Can I include dll in exe (in Visual Studio)?

Possible Duplicate:

  .NET windows application, can it be compressed into a single .exe?

To run my App I need AxInterop.WMPLib.dll and Interop.WMPLib.dll that are located in Debug and Release folder. Is there any way to include those dlls into exe so my app is available in one file only?

答: Include them as embedded.  You can then extract them at run-time.</p>

OwnerDisplayName: mark

OwnerDisplayName: cookre