问:
ArgumentNullException in a unit test for AutoFixture AutoDataAttribute
I was writing a unit test for ApiControllerConventions from a related SO question and I wrote a AutoMoqApiControllerDataAttribute to integrate this ICustomization in xUnit.net.

```<code>public class AutoMoqApiControllerDataAttribute : AutoDataAttribute
{
    public AutoMoqApiControllerDataAttribute() : this(new Fixture())
    {
    }

    public AutoMoqApiControllerDataAttribute(IFixture fixture) : base(
        fixture.Customize(new ApiControllerConventions()))
    {
    }
}
</code>```

I tried writing a unit test for this attribute like this:

```<code>public class AutoMoqDataAttribute : AutoDataAttribute
{
    public AutoMoqDataAttribute() : this(new Fixture())
    {
    }

    public AutoMoqDataAttribute(IFixture fixture) :
        base(fixture.Customize(new AutoMoqCustomization()))
    {
    }
}

[Theory, AutoMoqData]
public void AutoMoqApiControllerDataAttribute_ContainsCorrectCustomization(
    Mock<IFixture> mockFixture)
{
    // Arrange
    mockFixture.Setup(f => f.Customize(It.IsAny<ApiControllerConventions>())).Verifiable();

    // Act
    var sut = new AutoMoqApiControllerDataAttribute(mockFixture.Object);

    // Assert
    mockFixture.Verify(f => f.Customize(It.IsAny<ApiControllerConventions>()), Times.Once);
}
</code>```

This fails with an exception from AutoDataAttribute:

System.ArgumentNullException
  Value cannot be null.
  Parameter name: fixture
    at Ploeh.AutoFixture.Xunit2.AutoDataAttribute..ctor(IFixture fixture)

I thought this is related to my usage of the AutoMoqDataAttribute so I reverted to a vanilla Fact, same exception still:

```<code>[Fact]
public void AutoMoqApiControllerDataAttribute_ContainsCorrectCustomization()
{
    // Arrange
    var mockFixture = new Mock<IFixture>();
    mockFixture.Setup(f => f.Customize(It.IsAny<ApiControllerConventions>())).Verifiable();

    // Act
    var sut = new AutoMoqApiControllerDataAttribute(mockFixture.Object);

    // Assert
    mockFixture.Verify(f => f.Customize(It.IsAny<ApiControllerConventions>()), Times.Once);
}
</code>```

Why am I getting the exception? I obviously have the IFixture mocked and it is definitely not null.

答:
When you get an exception, it's always a good idea to look at the call stack. The exception isn't thrown in AutoMoqApiControllerDataAttribute, but in AutoDataAttribute:

```<code>System.ArgumentNullException : Value cannot be null.
Parameter name: fixture
    at Ploeh.AutoFixture.Xunit2.AutoDataAttribute..ctor(IFixture fixture)
    AutoMoqApiControllerDataAttribute.cs(12,0): at _44380395.AutoMoqApiControllerDataAttribute..ctor(IFixture fixture)
    Tests.cs(22,0): at _44380395.Tests.AutoMoqApiControllerDataAttribute_ContainsCorrectCustomization()
</code>```

While fixture isn't null when it's passed to AutoMoqApiControllerDataAttribute, it is null when passed to base(IFixture).

Why?

Consider the call to base:

```<code>base(fixture.Customize(new ApiControllerConventions()))
</code>```

Which value is being passed to base?

Not fixture, but the return value from invoking fixture.Customize.

The test doesn't set up a return value for this method call, so Moq defaults to the default value for the type. Since IFixture is a reference type, that means null, and that null value is then passed to base.

You can easily address the problem by configuring mockFixture with a return value in the test:

```<code>[Fact]
public void AutoMoqApiControllerDataAttribute_ContainsCorrectCustomization()
{
    // Arrange
    var mockFixture = new Mock<IFixture>();
    mockFixture
        .Setup(f => f.Customize(It.IsAny<ApiControllerConventions>()))
        .Returns(mockFixture.Object)
        .Verifiable();

    // Act
    var sut = new AutoMoqApiControllerDataAttribute(mockFixture.Object);

    // Assert
    mockFixture.Verify(
        f => f.Customize(It.IsAny<ApiControllerConventions>()),
        Times.Once());
}
</code>```

Now the test passes in my repro.

This isn't a problem specific to AutoFixture. You could reproduce it with any Fluent Interface.

Body:
I was writing a unit test for ApiControllerConventions from a related SO question and I wrote a AutoMoqApiControllerDataAttribute to integrate this ICustomization in xUnit.net.

public class AutoMoqApiControllerDataAttribute : AutoDataAttribute
{
    public AutoMoqApiControllerDataAttribute() : this(new Fixture())
    {
    }

    public AutoMoqApiControllerDataAttribute(IFixture fixture) : base(
        fixture.Customize(new ApiControllerConventions()))
    {
    }
}

I tried writing a unit test for this attribute like this:

public class AutoMoqDataAttribute : AutoDataAttribute
{
    public AutoMoqDataAttribute() : this(new Fixture())
    {
    }

    public AutoMoqDataAttribute(IFixture fixture) :
        base(fixture.Customize(new AutoMoqCustomization()))
    {
    }
}

[Theory, AutoMoqData]
public void AutoMoqApiControllerDataAttribute_ContainsCorrectCustomization(
    Mock<IFixture> mockFixture)
{
    // Arrange
    mockFixture.Setup(f => f.Customize(It.IsAny<ApiControllerConventions>())).Verifiable();

    // Act
    var sut = new AutoMoqApiControllerDataAttribute(mockFixture.Object);

    // Assert
    mockFixture.Verify(f => f.Customize(It.IsAny<ApiControllerConventions>()), Times.Once);
}

This fails with an exception from AutoDataAttribute:

System.ArgumentNullException
  Value cannot be null.
  Parameter name: fixture
    at Ploeh.AutoFixture.Xunit2.AutoDataAttribute..ctor(IFixture fixture)

I thought this is related to my usage of the AutoMoqDataAttribute so I reverted to a vanilla Fact, same exception still:

[Fact]
public void AutoMoqApiControllerDataAttribute_ContainsCorrectCustomization()
{
    // Arrange
    var mockFixture = new Mock<IFixture>();
    mockFixture.Setup(f => f.Customize(It.IsAny<ApiControllerConventions>())).Verifiable();

    // Act
    var sut = new AutoMoqApiControllerDataAttribute(mockFixture.Object);

    // Assert
    mockFixture.Verify(f => f.Customize(It.IsAny<ApiControllerConventions>()), Times.Once);
}

Why am I getting the exception? I obviously have the IFixture mocked and it is definitely not null.

Body:
When you get an exception, it's always a good idea to look at the call stack. The exception isn't thrown in AutoMoqApiControllerDataAttribute, but in AutoDataAttribute:

System.ArgumentNullException : Value cannot be null.
Parameter name: fixture
    at Ploeh.AutoFixture.Xunit2.AutoDataAttribute..ctor(IFixture fixture)
    AutoMoqApiControllerDataAttribute.cs(12,0): at _44380395.AutoMoqApiControllerDataAttribute..ctor(IFixture fixture)
    Tests.cs(22,0): at _44380395.Tests.AutoMoqApiControllerDataAttribute_ContainsCorrectCustomization()

While fixture isn't null when it's passed to AutoMoqApiControllerDataAttribute, it is null when passed to base(IFixture).

Why?

Consider the call to base:

base(fixture.Customize(new ApiControllerConventions()))

Which value is being passed to base?

Not fixture, but the return value from invoking fixture.Customize.

The test doesn't set up a return value for this method call, so Moq defaults to the default value for the type. Since IFixture is a reference type, that means null, and that null value is then passed to base.

You can easily address the problem by configuring mockFixture with a return value in the test:

[Fact]
public void AutoMoqApiControllerDataAttribute_ContainsCorrectCustomization()
{
    // Arrange
    var mockFixture = new Mock<IFixture>();
    mockFixture
        .Setup(f => f.Customize(It.IsAny<ApiControllerConventions>()))
        .Returns(mockFixture.Object)
        .Verifiable();

    // Act
    var sut = new AutoMoqApiControllerDataAttribute(mockFixture.Object);

    // Assert
    mockFixture.Verify(
        f => f.Customize(It.IsAny<ApiControllerConventions>()),
        Times.Once());
}

Now the test passes in my repro.

This isn't a problem specific to AutoFixture. You could reproduce it with any Fluent Interface.


来源: stackexchange

问:
Parameter 'Name' is required by @Test on method parametertest but has not been marked @Optional
Here is my selenium testng script and XML file. I am getting the error message. Please help me how to proceed this

Err MSG : Parameter 'Name' is required by @Test on method parametertest but has not been marked @Optional

```<code>import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class Sampleparameterized {

@Test
@Parameters("Name")
public void parametertest(String Name) {
System.out.println("Parameterized value is " +Name);
}
}
</code>```

XML file is

```<code><?xml version="1.0" encoding="UTF-8"?>
<suite name="Suite" parallel="false">
<test name="Test">
<parameter name = "Name" value ="TOM"/>

<classes>
<class name="Testing.Sampleparameterized"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
</code>```

答: This error normally comes when you are trying to run individual TestNg class instead of run *.xml. Your parameter is set in *.xml file, so right click on *.xml file and Run as TestNg. Make sure your TestNg class is properly mapped in your *.xml file (class name="com.test.WebServices"). Here WebServices.java is your TestNg class.</p>

ContentLicense: CC BY-SA 3.0

Body:
Here is my selenium testng script and XML file. I am getting the error message. Please help me how to proceed this

Err MSG : Parameter 'Name' is required by @Test on method parametertest but has not been marked @Optional

import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class Sampleparameterized {

@Test
@Parameters("Name")
public void parametertest(String Name) {
System.out.println("Parameterized value is " +Name);
}
}

XML file is

<?xml version="1.0" encoding="UTF-8"?>
<suite name="Suite" parallel="false">
<test name="Test">
<parameter name = "Name" value ="TOM"/>

<classes>
<class name="Testing.Sampleparameterized"/>
</classes>
</test>
</suite>


问:
Single Form Hide on Startup
I have an application with one form in it, and on the Load method I need to hide the form.

The form will display itself when it has a need to (think along the lines of a outlook 2003 style popup), but I can' figure out how to hide the form on load without something messy.

Any suggestions?

答:
Override OnVisibleChanged in Form

```<code>protected override void OnVisibleChanged(EventArgs e)
{
    this.Visible = false;

    base.OnVisibleChanged(e);
}
</code>```

You can add trigger if you may need to show it at some point

```<code>public partial class MainForm : Form
{
public bool hideForm = true;
...
public MainForm (bool hideForm)
    {
        this.hideForm = hideForm;
        InitializeComponent();
    }
...
protected override void OnVisibleChanged(EventArgs e)
    {
        if (this.hideForm)
            this.Visible = false;

        base.OnVisibleChanged(e);
    }
...
}
</code>```

OwnerDisplayName: Andy

Title: Single Form Hide on Startup

LastEditorDisplayName: Andy

Body:
Override OnVisibleChanged in Form

protected override void OnVisibleChanged(EventArgs e)
{
    this.Visible = false;

    base.OnVisibleChanged(e);
}

You can add trigger if you may need to show it at some point

public partial class MainForm : Form
{
public bool hideForm = true;
...
public MainForm (bool hideForm)
    {
        this.hideForm = hideForm;
        InitializeComponent();
    }
...
protected override void OnVisibleChanged(EventArgs e)
    {
        if (this.hideForm)
            this.Visible = false;

        base.OnVisibleChanged(e);
    }
...
}


问:
Database connection error - not due to wp-config.php - wordpress
I am new to WordPress. I have developed a website and uploaded it.
The issue I am facing is now that sometimes my site opens perfectly but sometimes it shows an error "ERROR ESTABLISHING A DATABASE CONNECTION".

I have googled and everyone is saying that please check wp-config.php file, But my concerns is here that if there is a problem with this file, the site will not open at all. After doing some research, I came to know that there may be some issues with the hosting server usage, but When i checked, there is nothing to worry.
I don't know why its happening, But anyone here any idea ?

Here is my website link

and here are some images about the memory and CPU usage for the server(digital ocean 1GB droplet).

答:
It seems your MySQL stops working due to low memory(1GB RAM). You may try following to resolve this issue.

Increase RAM

Try to optimize your site. Check your website performance score here https://gtmetrix.com/reports/www.daewoo.com.pk/vqXWl2I7 . Use wordpress caching plugin to improve performance.

Try to optimize Mysql configuration. See this http://www.tocker.ca/2014/03/10/configuring-mysql-to-use-minimal-memory.html

Check Mysql error log and apache error log for exact issue.


问:
Reading a string from and to a certain character
I would like to know if it is possible to read a certain string of n-length, from x character to y character without having to split it into smaller pieces.

I have the following string, for a path in AD CN=someName,OU=someGroup,OU=groups,DC=some,DC=domain,DC=com, and I would like to be able to just read the someName part of it, without splitting by = or , first. How do I achieve that?

Reason is, that I do not have to do group comparison as I am doing it right now:

```<code>SearchResult t1 = search.FindOne();
foreach (string s in t1.Properties["memberof"])
{
    foreach (string g in groups)
    {
        if (s.ToLower().Contains(g.ToLower()))
        {
            // do something
        }
    }
}
</code>```

I would rather make the if clause to equals, but I do not want to always split the above path/groups into an array twice. How do I do that?

答:
You can use String.IndexOf to find the correct offset, then use String.SubString to read the part you want.

```<code>const string input = "CN=someName,OU=someGroup,OU=groups,DC=some,DC=domain,DC=com";
const string start = "CN=";
const string stop = ",";

int startIndex = input.IndexOf(start, 0);
int stopIndex = input.IndexOf(stop, startIndex);

var extracted = input.Substring(startIndex + start.Length, stopIndex - startIndex - start.Length);

Console.WriteLine(extracted);
</code>```

.net Fiddle

PS: maybe also take a look at Is there a .NET class that can parse CN= strings out of LDAP? for your special usecase!

Body:
I would like to know if it is possible to read a certain string of n-length, from x character to y character without having to split it into smaller pieces.

I have the following string, for a path in AD CN=someName,OU=someGroup,OU=groups,DC=some,DC=domain,DC=com, and I would like to be able to just read the someName part of it, without splitting by = or , first. How do I achieve that?

Reason is, that I do not have to do group comparison as I am doing it right now:

SearchResult t1 = search.FindOne();
foreach (string s in t1.Properties["memberof"])
{
    foreach (string g in groups)
    {
        if (s.ToLower().Contains(g.ToLower()))
        {
            // do something
        }
    }
}

I would rather make the if clause to equals, but I do not want to always split the above path/groups into an array twice. How do I do that?

Body:
You can use String.IndexOf to find the correct offset, then use String.SubString to read the part you want.

const string input = "CN=someName,OU=someGroup,OU=groups,DC=some,DC=domain,DC=com";
const string start = "CN=";
const string stop = ",";

int startIndex = input.IndexOf(start, 0);
int stopIndex = input.IndexOf(stop, startIndex);

var extracted = input.Substring(startIndex + start.Length, stopIndex - startIndex - start.Length);

Console.WriteLine(extracted);

.net Fiddle

PS: maybe also take a look at Is there a .NET class that can parse CN= strings out of LDAP? for your special usecase!


问:
2D openGL drawing lines that don't exactly fit pixel raster
I'm drawing something similar to a LED VU meter in OpenGL. Result should be like on vertical bar of this:

Unfortunately, my drawing space is restricted, and I have to fit exactly 18 bars on it. That yields a spacing between bars of 3.6 pixels.

When drawn, this causes visible differences in the gaps between lines, because the gaps are either 2 or 1 pixel wide. I'm looking for a solution to use subpixel rendering and than "fake" the lines by some kind of anti-aliasing, so that all gaps appear of the same width.

This is my code so far

```<code>glEnable(GL_LINE_SMOOTH);
glHint(GL_LINE_SMOOTH, GL_NICEST);
for (int i = 0; i < 18; ++i) {
            float bBottom = barBottom + i*3.6f;
            glBegin(GL_LINES);
            glLineWidth(2);
            glVertex2f(bRight,bBottom);
            glVertex2f(bLeft,bBottom);
            glEnd();
}
glDisable(GL_LINE_SMOOTH);
</code>```

Unfortunately, turning on line smoothing showed no visible effect. Any suggestions?

答:
Use multisampling (Multisampling specs).

Additionally, I would use quads (and not lines) for rendering those blocks.

ContentLicense: CC BY-SA 2.5

Body:
I'm drawing something similar to a LED VU meter in OpenGL. Result should be like on vertical bar of this:

Unfortunately, my drawing space is restricted, and I have to fit exactly 18 bars on it. That yields a spacing between bars of 3.6 pixels.

When drawn, this causes visible differences in the gaps between lines, because the gaps are either 2 or 1 pixel wide. I'm looking for a solution to use subpixel rendering and than "fake" the lines by some kind of anti-aliasing, so that all gaps appear of the same width.

This is my code so far

glEnable(GL_LINE_SMOOTH);
glHint(GL_LINE_SMOOTH, GL_NICEST);
for (int i = 0; i < 18; ++i) {
            float bBottom = barBottom + i*3.6f;
            glBegin(GL_LINES);
            glLineWidth(2);
            glVertex2f(bRight,bBottom);
            glVertex2f(bLeft,bBottom);
            glEnd();
}
glDisable(GL_LINE_SMOOTH);

Unfortunately, turning on line smoothing showed no visible effect. Any suggestions?


问:
Comparing SimpleDateFormat output with number
I am making a program that executes something every time the time reaches an hour.

Here is the code:

```<code>import java.text.*;
import java.util.Date;
class NMAP {
 public static void main(String[] args) {
  DateFormat dateFormat = new SimpleDateFormat("HH");
  Date date = new Date();
  if (dateFormat.format(date).equals(17)) {
   System.out.println(dateFormat.format(date));
  }
 }
}
</code>```

It should be outputting 17 (since it is 17:00), but it doesn't output anything.

Why not?

答:
you are comparing dateFormat.equals(17) a string against an integer

that returns false no matter what because they are different types.

you have to do dateFormat.equals("17")

And because some when you will need the power of java8:

```<code>LocalTime now = LocalTime.now();
System.out.println(now);
System.out.println(now.getHour() == 17);
</code>```

Body:
I am making a program that executes something every time the time reaches an hour.

Here is the code:

import java.text.*;
import java.util.Date;
class NMAP {
 public static void main(String[] args) {
  DateFormat dateFormat = new SimpleDateFormat("HH");
  Date date = new Date();
  if (dateFormat.format(date).equals(17)) {
   System.out.println(dateFormat.format(date));
  }
 }
}

It should be outputting 17 (since it is 17:00), but it doesn't output anything.

Why not?

Body:
you are comparing dateFormat.equals(17) a string against an integer

that returns false no matter what because they are different types.

you have to do dateFormat.equals("17")

And because some when you will need the power of java8:

LocalTime now = LocalTime.now();
System.out.println(now);
System.out.println(now.getHour() == 17);


问:
laravel jquery select2 multiselect - initialize selected elements
Good morning everybody, I'm stuck while trying to set initial selected options (got through an ajax requests) to a jquery select2 (multi-select). If I use the control, multi selection works just fine. The problem arise when I have to edit a previously saved model, as none of the options I previously selected are shown.

This is my view:

```<code><div class="form-group {{ $errors->has('pubblicazione_giuridica_id') ? 'has-error' : ''}}">
    {!! Form::label('pubblicazione_giuridica_id', 'Law Pubs', ['class' => 'col-sm-3 control-label']) !!}
    <div class="col-sm-6">
        {!! Form::select('pubblicazione_giuridica_id[]', [$pubGiurList], null, ['class' => 'form-control', 'id'=>'select-pgiur', 'multiple'=>'multiple']) !!}
        {!! $errors->first('pubblicazione_giuridica_id', '<p class="help-block">:message</p>') !!}
    </div>
</code>```

The javascript:

```<code>$('#select-pgiur').select2({
    ajax: {
        url: "{!! URL::to('/gare/proc-getpubgiur') !!}",
        dataType: 'json',
        delay: 150,
        data: function (params) {
            return { q: params.term, };
        },
        processResults: function (data, params) {
            return { results: data.items, };
        },
        cache: true
    },
    language: 'it',
    theme: "bootstrap",
    placeholder: "Choose an option."
});
</code>```

The Controller:

```<code>public function edit($id, Request $request) {
    $procedure = $this->getProcedure($id, $request, true);
    if (!$procedure) {
        return redirect('gare/procedure')->with('alert-warning', 'Gara non trovata - Operazione non consentita');
    }
    return view('gare.procedures.edit', [ 'procedure'=>$procedure, 'opChoiceList'=>$this->getOpChoiceList(), 'pubGiurList'=>json_encode(GaraPubblicazioneGiuridica::GetPubByGaraId($procedure->id)) ]);
}
</code>```

Model:

```<code>public static function GetPubByGaraId($id){
    //TODO: visualizzare le selected publications
    $procagg = GaraPubblicazioneGiuridica::where('gara_id','=',$id)->select('id')->get();
    if($procagg){
        $plucked = $procagg->pluck('nome');
        $toReturn = array();
        foreach($plucked as $key=>$value){
            $toReturn[$key]=$value;
        }
        return $toReturn;
    }
    return "";
}
</code>```

Could you shed some light on this?
Thank you in advance.

答:
If I understand your end-goal correctly, you want to update the Select2 multi-select by selecting options after the Select2 has been initialized using data received from an Ajax request.

If that's the case, you're looking for the .trigger('change') event.

I personally use VueJS and hand-crafted forms, but this should point you in the right direction:

```<code>$("#your_select2_id").val(selected_values_array).trigger("change");
</code>```

The selected_values_array is a JS array that contains the values: <option value="1"></option> that you want selected. The .trigger() then updates the Select2 to show them.

Hope that helps!

Body:
Good morning everybody, I'm stuck while trying to set initial selected options (got through an ajax requests) to a jquery select2 (multi-select). If I use the control, multi selection works just fine. The problem arise when I have to edit a previously saved model, as none of the options I previously selected are shown.

This is my view:

has('pubblicazione_giuridica_id') ? 'has-error' : ''}}">
    {!! Form::label('pubblicazione_giuridica_id', 'Law Pubs', ['class' => 'col-sm-3 control-label']) !!}

        {!! Form::select('pubblicazione_giuridica_id[]', [$pubGiurList], null, ['class' => 'form-control', 'id'=>'select-pgiur', 'multiple'=>'multiple']) !!}
        {!! $errors->first('pubblicazione_giuridica_id', '
:message
') !!}

The javascript:

$('#select-pgiur').select2({
    ajax: {
        url: "{!! URL::to('/gare/proc-getpubgiur') !!}",
        dataType: 'json',
        delay: 150,
        data: function (params) {
            return { q: params.term, };
        },
        processResults: function (data, params) {
            return { results: data.items, };
        },
        cache: true
    },
    language: 'it',
    theme: "bootstrap",
    placeholder: "Choose an option."
});

The Controller:

public function edit($id, Request $request) {
    $procedure = $this->getProcedure($id, $request, true);
    if (!$procedure) {
        return redirect('gare/procedure')->with('alert-warning', 'Gara non trovata - Operazione non consentita');
    }
    return view('gare.procedures.edit', [ 'procedure'=>$procedure, 'opChoiceList'=>$this->getOpChoiceList(), 'pubGiurList'=>json_encode(GaraPubblicazioneGiuridica::GetPubByGaraId($procedure->id)) ]);
}

Model:

public static function GetPubByGaraId($id){
    //TODO: visualizzare le selected publications
    $procagg = GaraPubblicazioneGiuridica::where('gara_id','=',$id)->select('id')->get();
    if($procagg){
        $plucked = $procagg->pluck('nome');
        $toReturn = array();
        foreach($plucked as $key=>$value){
            $toReturn[$key]=$value;
        }
        return $toReturn;
    }
    return "";
}

Could you shed some light on this?
Thank you in advance.

Body:
If I understand your end-goal correctly, you want to update the Select2 multi-select by selecting options after the Select2 has been initialized using data received from an Ajax request.

If that's the case, you're looking for the .trigger('change') event.

I personally use VueJS and hand-crafted forms, but this should point you in the right direction:

$("#your_select2_id").val(selected_values_array).trigger("change");

The selected_values_array is a JS array that contains the values: <option value="1"></option> that you want selected. The .trigger() then updates the Select2 to show them.

Hope that helps!


问:
Android project broken after Blue Screen on Windows 10
I re-opened my Android Project after blue screen on my machine running Windows 10, all classes and components are unfound. Anybody any idea? I tried re-build and re-start my machines n times.</p>

答: Check that your module(-s) uses valid Android SDK: press Ctrl+Shift+Alt+S and check modules one by one. May be the same validation should be done in build.gradle script</p>


问:
window.open being flagged as a pop-up
I'm trying to figure out how I can bypass the pop blocking issue when using window.open. Here is the code I'm working on.

The first script I've built a script uses bit.ly API in shortening a URL address. Basically it gets the parameters then passes it to the API.

Then the second script calls the get_short_url function in order to share the bit.ly url via twitter using an on-click event. Unfortunately window.open seems to be flagged as a pop up by the browser. Is there way to bypass this

```<code><script>
var base_url      = window.location.origin,
    hash_bang     = "/#/sign-up?referral=",
    login         = "login",
    api_key       = "api_key";

function get_short_url(login, api_key, func, value) {
    var value = document.getElementById('input-refcode').value;

    $.getJSON(
        "https://api-ssl.bitly.com//v3/shorten?callback=?",
        {
            "format": "json",
            "apiKey": api_key,
            "login": login,
            "longUrl": base_url + hash_bang + value
        },

        function(response)
        {
            func(response.data.url);
        }
    );
}
</script>
</code>```

```<code><script>

$('#twitter').on('click', function() {

    get_short_url(login, api_key, function(short_url) {
        win = window.open('https://twitter.com/intent/tweet?text=Get Free Rides at Electric Studio! Sign up ' + short_url + ' to purchase your first timer package! After your first ride, you get 1 ride on us!' + ' https://www.electricstudio.ph/', '_blank');
        win.focus();
    });
});
</script>
</code>```

答:
I don't think you can bypass the popup alert as it is something which browser handles for safety. For your personal machine, you can change the security settings to mark this site as exception and then you won't be prompted again.

For your second part where you want to pass a value from on ajax call to another, you can create an object as below and pass it as a response

```<code>function(response)
{
    func({'shortURL' : response.data.url, 'yourValue': customValue });
}
</code>```

And access this in your other function as

```<code>get_short_url(login, api_key, function(result) {
    var custVal = result.customValue;  //Your custom value
    win = window.open('https://twitter.com/intent/tweet?text=Get Free Rides at Electric Studio! Sign up ' + result.shortURL + ' to purchase your first timer package! After your first ride, you get 1 ride on us!' + ' https://www.electricstudio.ph/', '_blank');
    win.focus();
});
</code>```

Title: window.open being flagged as a pop-up

Body:
I don't think you can bypass the popup alert as it is something which browser handles for safety. For your personal machine, you can change the security settings to mark this site as exception and then you won't be prompted again.

For your second part where you want to pass a value from on ajax call to another, you can create an object as below and pass it as a response

function(response)
{
    func({'shortURL' : response.data.url, 'yourValue': customValue });
}

And access this in your other function as

get_short_url(login, api_key, function(result) {
    var custVal = result.customValue;  //Your custom value
    win = window.open('https://twitter.com/intent/tweet?text=Get Free Rides at Electric Studio! Sign up ' + result.shortURL + ' to purchase your first timer package! After your first ride, you get 1 ride on us!' + ' https://www.electricstudio.ph/', '_blank');
    win.focus();
});


问:
Toggle and animate height of a ul within a li
I have a list inside a li which needs to slide into view when the parent li is clicked.

My code works nicely but if i click any li all of the sub lists show where as i want it only to apply to the one that was clicked...

```<code>$("#offering li").click(function() {
        $("#offering li ul").animate({height: "toggle"}, 1000);
    });

<ul id="offering">
     <li class="t current"><a href="#solutions"><span>sage solutions</span></a>
                    <ul>
                        <li><a href="#">50</a></li>
                        <li><a href="#">200</a></li>
                        <li><a href="#">CRM</a></li>
                    </ul>
                </li>
     <li class="m"><a href="#management"><span>solutions</span></a>
                  <ul>
                      <li><a href="#">50</a></li>
                      <li><a href="#">200</a></li>
                      <li><a href="#">CRM</a></li>
                  </ul>
              </li>
     <li class="b"><a href="#thirdparty"><span>third party additions</span></a></li>
            </ul>
</code>```

答:
Here you are applying the animation to all elements that match the selector #offering ul li, when infact you just need to apply it to the child ul of the li clicked.

Instead of the following

```<code>$("#offering li").click(function() {
        $("#offering li ul").animate({height: "toggle"}, 1000);
    });
</code>```

Try this

```<code>$("#offering li").click(function() {
        this.childNodes[0].animate({height:"toggle"},1000);
    });
</code>```

I'm not as familiar with jQuery as I am with Mootools, so there may be a more appropriate way to get the child ul element than using the childNodes array - but you get the idea.

Body:
I have a list inside a li which needs to slide into view when the parent li is clicked.

My code works nicely but if i click any li all of the sub lists show where as i want it only to apply to the one that was clicked...

$("#offering li").click(function() {
        $("#offering li ul").animate({height: "toggle"}, 1000);
    });

sage solutions

50

200

CRM

solutions

50

200

CRM

third party additions

Body:
Here you are applying the animation to all elements that match the selector #offering ul li, when infact you just need to apply it to the child ul of the li clicked.

Instead of the following

$("#offering li").click(function() {
        $("#offering li ul").animate({height: "toggle"}, 1000);
    });

Try this

$("#offering li").click(function() {
        this.childNodes[0].animate({height:"toggle"},1000);
    });

I'm not as familiar with jQuery as I am with Mootools, so there may be a more appropriate way to get the child ul element than using the childNodes array - but you get the idea.


问:
Hibernate @OneToMany / @ManyToOne column not appearing
I have a @OneToMany / @ManyToOne relationship, where a Project can have one or many Phases and a Phase depends on a Project. Pretty simple.

Here are my entities (the relevant parts):

```<code>@Entity
@Table(name = "project")
public class ProjectEntity {

    @Id
    @Column(name = "project_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    // Our Set of phases to be saved in the database as an array
    @OneToMany(targetEntity = PhaseEntity.class)
    private Set<PhaseEntity> phases = new HashSet<>(0);

    // Getters and setters
}
</code>```

And my PhaseEntity:

```<code>@Entity
@Table(name = "phase")
public class PhaseEntity {
    @Id
    @Column(unique = true, name="phase_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    // Our project on which the phases are appart of
    @NotNull
    @ManyToOne(targetEntity = ProjectEntity.class)
    private ProjectEntity project;

    // Getters and setters
}
</code>```

Upon creating phases in an already existing project, I save them one by one by creating an entity and

```<code>phaseDao.save(phaseEntity);
</code>```

And finally save the set of phases in my project like such:

```<code>project.setPhases(phaseSet);
</code>```

My phases ARE correctly created and are linked to a project but my projects do not show any sign of phases as they do not have a phases column.

EDIT: Turns out that Hibernate creates a link table called project_phases, is there a way to save an array of phases without creating a link table?

What am I not understanding?

答:
use mappedBy attribute in @OneToMany Annotation</p>

```<code>@OneToMany(targetEntity = PhaseEntity.class, mappedby="project")
private Set<PhaseEntity> phases = new HashSet<>(0);
</code>```

Body:
I have a @OneToMany / @ManyToOne relationship, where a Project can have one or many Phases and a Phase depends on a Project. Pretty simple.

Here are my entities (the relevant parts):

@Entity
@Table(name = "project")
public class ProjectEntity {

    @Id
    @Column(name = "project_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    // Our Set of phases to be saved in the database as an array
    @OneToMany(targetEntity = PhaseEntity.class)
    private Set<PhaseEntity> phases = new HashSet<>(0);

    // Getters and setters
}

And my PhaseEntity:

@Entity
@Table(name = "phase")
public class PhaseEntity {
    @Id
    @Column(unique = true, name="phase_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    // Our project on which the phases are appart of
    @NotNull
    @ManyToOne(targetEntity = ProjectEntity.class)
    private ProjectEntity project;

    // Getters and setters
}

Upon creating phases in an already existing project, I save them one by one by creating an entity and

phaseDao.save(phaseEntity);

And finally save the set of phases in my project like such:

project.setPhases(phaseSet);

My phases ARE correctly created and are linked to a project but my projects do not show any sign of phases as they do not have a phases column.

EDIT: Turns out that Hibernate creates a link table called project_phases, is there a way to save an array of phases without creating a link table?

What am I not understanding?

Body:
use mappedBy attribute in @OneToMany Annotation

@OneToMany(targetEntity = PhaseEntity.class, mappedby="project")
private Set<PhaseEntity> phases = new HashSet<>(0);


问:
Dynamic timer in rxjs
I am creating a slider with images and videos and am want to assign a certain amount of screen time for each type.

```<code>let data =  [{"path":"http://localhost:8091/public/testimg.jpg","type":"image"},{"path":"http://localhost:8091/public/testvideo.mp4","type":"video"}]
Observable.timer(0, 3000)
                            .map(e => {
                                console.log(e); return data[e % data.length];
                            })
                            .subscribe(item => {
                                this.activeItem = item;
                            });
</code>```

I am able to set a generic time for all the slides using the code above but am unable to do set separate values for each of the items in the array.

Here is what I actually want to achieve
1) Iterate through the array from 0 to the last index once it has completed iterating infinitely
2) To be able to set a time when the next iteration takes place based on the type property inside each object.

Right now only 1) is satisfiable.

答:
```<code>let data =  [{"path":"http://localhost:8091/public/testimg.jpg","type":"image"},{ "path":"http://localhost:8091/public/testvideo.mp4","type":"video"}];

const delayByMediaType = {image: 1000, video: 5000};

Observable.from(data)
.concatMap(media => {
   return Observable.of(media).delay(delayByMediaType[media.type])
}).subscribe(console.log);
</code>```

Title: Dynamic timer in rxjs

Body:
I am creating a slider with images and videos and am want to assign a certain amount of screen time for each type.

let data =  [{"path":"http://localhost:8091/public/testimg.jpg","type":"image"},{"path":"http://localhost:8091/public/testvideo.mp4","type":"video"}]
Observable.timer(0, 3000)
                            .map(e => {
                                console.log(e); return data[e % data.length];
                            })
                            .subscribe(item => {
                                this.activeItem = item;
                            });

I am able to set a generic time for all the slides using the code above but am unable to do set separate values for each of the items in the array.

Here is what I actually want to achieve
1) Iterate through the array from 0 to the last index once it has completed iterating infinitely
2) To be able to set a time when the next iteration takes place based on the type property inside each object.

Right now only 1) is satisfiable.


问:
Angular2 functions
Does there exists a build in function that keeps on reloading the whole component until a boolean gets true. Bacause now before I can get some data I need to wait until a user has clicked a button in another component. But there is no relationship between those 2 components.

Does someone knows a way how to do this.

thx!

答:
you can make use of Event Emitters in components to share information so that you need not wait for a user dependent action . Also make use of Service classes in order to pass information between components.

https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

Also if you are getting information from a http call try and use observables or promises and then use ngIf or a elvus operator to get info into the component.

More on Angular Concepts https://rahulrsingh09.github.io/AngularConcepts/

Title: Angular2 functions


问:
Placeholder/Hoover containing data from Model
I have  view with a list of images and I want to show the title of that image from a placeholder or on hoover.
Is there a way to do that? Perhaps with jquery or JS?

This is my view

```<code>@using (Html.BeginForm())
{
   <div>@Html.DisplayFor(@model => model.Product)</div>
    if (Model.Images != null)
    {
        foreach (var item in Model.Images)
        {
            <img src='@Url.Content(item.ImagePath)' alt="Image" onclick="SendEmail()" id="images" class="imagethesame" placeholder="@Model.Product??" />   }
    }

}
</code>```

答:
I found another work-around for this problem, easier for developers. The data from the controller comes with JSon in a stylish popup from SweetAlert.

```<code>function GetNames() {
        $.ajax({

            url: '@Url.Action("GetProductName","Shop")',
            type: 'GET',
            dataType: 'json',
            success: function (data) {

                swal({
                    title: data + " costs 4$. Click Ok for adding it to your shopping cart! ",
                },

            function () {
                window.location = '@Url.Action("Index", "MainPage")';
            })
            }
        });
    }
</code>```

Perhaps is not related to the question, but it is a simple, elegant solution.

Body:
I have  view with a list of images and I want to show the title of that image from a placeholder or on hoover.
Is there a way to do that? Perhaps with jquery or JS?

This is my view

@using (Html.BeginForm())
{

@Html.DisplayFor(@model => model.Product)

    if (Model.Images != null)
    {
        foreach (var item in Model.Images)
        {
               }
    }

}

Body:
I found another work-around for this problem, easier for developers. The data from the controller comes with JSon in a stylish popup from SweetAlert.

function GetNames() {
        $.ajax({

            url: '@Url.Action("GetProductName","Shop")',
            type: 'GET',
            dataType: 'json',
            success: function (data) {

                swal({
                    title: data + " costs 4$. Click Ok for adding it to your shopping cart! ",
                },

            function () {
                window.location = '@Url.Action("Index", "MainPage")';
            })
            }
        });
    }

Perhaps is not related to the question, but it is a simple, elegant solution.


问:
how to get ng-template to work in ionic 2 project
I had previously attempted to use virtual scroll for an array of cards that will have a varying amount of items. Virtual scroll wouldn't work with my cards and it was suggested I try ng-template which kept giving me an error in the terminal that said this :

Error: Template parse errors:  [01:38:47]  'ng-template' is not a
  known element:  [01:38:47]  1. If 'ng-template' is an Angular
  component, then verify that it is part of this module.  [01:38:47]  2.
  If 'ng-template' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA"
  to the '@NgModule.schemas' of this

The other solutions I've tried to get virtual scroll to work have left me with a blank, white, unrendered page, which is strange because you'd think if there was an error the terminal would have told me and the build would fail. I want to try to figure out how to make ng-template work for me. Googling hasn't turned up sufficient examples.
This is how I was originally using virtualScroll, which is the wrong way to do it. I've tried swapping in div and list elements to put the virtualScroll property on and I get the same result of a blank page.

HTML

```<code><ion-content id="content">
   <ion-card id="card" *ngFor="let event of listOfEvents
     [virtualScroll]="listOfEvents">
     <ion-item *virtualItem="let event">
       <ion-row>
         <ion-col>
           <span class="showDetails">Guests Needed:</span> {{event.guests}}
         </ion-col>
         <ion-col>
           <span class="showDetails">Cover:</span> {{event.coverCharge}}
         </ion-col>
         <ion-col>
           <span class="showDetails">Drink Min:</span>{{event.drinkMin}
         </ion-col>
       </ion-row>
    </ion-item>
  </ion-card>
</ion-content>
</code>```

答:
Angular4 has renamed the template component to ng-template. And there is also a possibility that you are getting this error as you're still using angular2 but also depend on some package which depends on angular4.

Just run

npm update

to update to Angular 4 and you should be fine.

Body:
I had previously attempted to use virtual scroll for an array of cards that will have a varying amount of items. Virtual scroll wouldn't work with my cards and it was suggested I try ng-template which kept giving me an error in the terminal that said this :

Error: Template parse errors:  [01:38:47]  'ng-template' is not a
  known element:  [01:38:47]  1. If 'ng-template' is an Angular
  component, then verify that it is part of this module.  [01:38:47]  2.
  If 'ng-template' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA"
  to the '@NgModule.schemas' of this

The other solutions I've tried to get virtual scroll to work have left me with a blank, white, unrendered page, which is strange because you'd think if there was an error the terminal would have told me and the build would fail. I want to try to figure out how to make ng-template work for me. Googling hasn't turned up sufficient examples.
This is how I was originally using virtualScroll, which is the wrong way to do it. I've tried swapping in div and list elements to put the virtualScroll property on and I get the same result of a blank page.

HTML

<ion-content id="content">
   <ion-card id="card" *ngFor="let event of listOfEvents
     [virtualScroll]="listOfEvents">
     <ion-item *virtualItem="let event">
       <ion-row>
         <ion-col>
           Guests Needed: {{event.guests}}
         </ion-col>
         <ion-col>
           Cover: {{event.coverCharge}}
         </ion-col>
         <ion-col>
           Drink Min:{{event.drinkMin}
         </ion-col>
       </ion-row>
    </ion-item>
  </ion-card>
</ion-content>


问:
React Native: How to styling the TextInput?
So I have component in my React Native app

This component should render the TextInput at the bottom.

When the keyboard is showing, the container (includes TextInput and Send Button) should move above the keyboard.

Also, I want to make the input height change everytime user click the enter in keyboard, just like this:

But all I've got is like these:

Below is my codes:

test_page2.js

```<code>import React from 'react'
import { View, Text, TouchableHighlight, TextInput, Dimensions, StyleSheet } from 'react-native'
import { StackNavigator } from 'react-navigation'
import { colors } from '../styles/colors'

let windowSize = Dimensions.get('window')

export default class TestScreen extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      message:'',
    }
  }

    static navigationOptions = {
        title: 'Test Page 2',
    };

    onBackPress(){
      console.log("thesauhduiahduisahd")
    }

    onSendPress() {
      console.log("send message");
      // this.setState({message: ''});
    }

    render() {
        return (
          <View style={styles.container}>
            <View style={styles.chatContainer}>
              <Text style={{color: '#000'}}>Others Component</Text>
            </View>
            <View style={styles.inputContainer }>
              <View style={styles.textContainer}>
                <TextInput
                  multiline={true}
                  value={this.state.message}
                  style={styles.input}
                  placeholder="Tulis pesan"
                  onChangeText={(text) => this.setState({message: text})}
                  underlineColorAndroid='rgba(0,0,0,0)' />
              </View>
              <View style={styles.sendContainer}>
                <TouchableHighlight
                  underlayColor={'#4e4273'}
                  onPress={() => this.onSendPress()}
                  >
                  <Text style={styles.sendLabel}>SEND</Text>
                </TouchableHighlight>
              </View>
            </View>
          </View>
        );
    }
}

var styles = StyleSheet.create({
    container: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'stretch',
      backgroundColor: '#ffffff'
    },
    topContainer: {
      flex: 1,
      flexDirection: 'row',
      justifyContent: 'flex-start',
      alignItems: 'center',
      backgroundColor: '#6E5BAA',
      paddingTop: 20,
    },
    chatContainer: {
      flex: 11,
      justifyContent: 'center',
      alignItems: 'stretch'
    },
    inputContainer: {
      flex: 1,
      flexDirection: 'row',
      justifyContent: 'space-around',
      alignItems: 'center',
      backgroundColor: '#6E5BAA'
    },
    textContainer: {
      flex: 1,
      justifyContent: 'center'
    },
    sendContainer: {
      justifyContent: 'flex-end',
      paddingRight: 10
    },
    sendLabel: {
      color: '#ffffff',
      fontSize: 15
    },
    input: {
      width: windowSize.width - 70,
      color: '#555555',
      paddingRight: 10,
      paddingLeft: 10,
      paddingTop: 5,
      height: '100%',
      borderColor: '#6E5BAA',
      borderWidth: 1,
      borderRadius: 2,
      alignSelf: 'center',
      backgroundColor: '#ffffff'
    },
  });
</code>```

How can I achieved the design just like my example?

Thanks in advance

答:
What i do in my application to tackle these type of situation is as follows:

1) Install a node module -

```<code>npm install react-native-keyboard-aware-scroll-view --save or yarn add react-native-keyboard-aware-scroll-view --save
</code>```

2) Import the project into your project:

```<code>import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'
</code>```

3) Encapsulate everything inside the <keyboardAwareScrollView> </keyboardAwareScrollView> like this:

```<code>render(){
    return (
      <KeyboardAwareScrollView  contentContainerStyle={{flex: 1,
      justifyContent: 'space-around',
      alignItems: 'center',
      width: null,
      height: null,}}>
       <View>
       ....
       </View>
      </KeyboardAwareScrollView>
     )
}
</code>```

everything seems pretty good.

Cheers :)

Body:
So I have component in my React Native app

This component should render the TextInput at the bottom.

When the keyboard is showing, the container (includes TextInput and Send Button) should move above the keyboard.

Also, I want to make the input height change everytime user click the enter in keyboard, just like this:

But all I've got is like these:

Below is my codes:

test_page2.js

import React from 'react'
import { View, Text, TouchableHighlight, TextInput, Dimensions, StyleSheet } from 'react-native'
import { StackNavigator } from 'react-navigation'
import { colors } from '../styles/colors'

let windowSize = Dimensions.get('window')

export default class TestScreen extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      message:'',
    }
  }

    static navigationOptions = {
        title: 'Test Page 2',
    };

    onBackPress(){
      console.log("thesauhduiahduisahd")
    }

    onSendPress() {
      console.log("send message");
      // this.setState({message: ''});
    }

    render() {
        return (
          <View style={styles.container}>
            <View style={styles.chatContainer}>
              <Text style={{color: '#000'}}>Others Component</Text>
            </View>
            <View style={styles.inputContainer }>
              <View style={styles.textContainer}>
                <TextInput
                  multiline={true}
                  value={this.state.message}
                  style={styles.input}
                  placeholder="Tulis pesan"
                  onChangeText={(text) => this.setState({message: text})}
                  underlineColorAndroid='rgba(0,0,0,0)' />
              </View>
              <View style={styles.sendContainer}>
                <TouchableHighlight
                  underlayColor={'#4e4273'}
                  onPress={() => this.onSendPress()}
                  >
                  <Text style={styles.sendLabel}>SEND</Text>
                </TouchableHighlight>
              </View>
            </View>
          </View>
        );
    }
}

var styles = StyleSheet.create({
    container: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'stretch',
      backgroundColor: '#ffffff'
    },
    topContainer: {
      flex: 1,
      flexDirection: 'row',
      justifyContent: 'flex-start',
      alignItems: 'center',
      backgroundColor: '#6E5BAA',
      paddingTop: 20,
    },
    chatContainer: {
      flex: 11,
      justifyContent: 'center',
      alignItems: 'stretch'
    },
    inputContainer: {
      flex: 1,
      flexDirection: 'row',
      justifyContent: 'space-around',
      alignItems: 'center',
      backgroundColor: '#6E5BAA'
    },
    textContainer: {
      flex: 1,
      justifyContent: 'center'
    },
    sendContainer: {
      justifyContent: 'flex-end',
      paddingRight: 10
    },
    sendLabel: {
      color: '#ffffff',
      fontSize: 15
    },
    input: {
      width: windowSize.width - 70,
      color: '#555555',
      paddingRight: 10,
      paddingLeft: 10,
      paddingTop: 5,
      height: '100%',
      borderColor: '#6E5BAA',
      borderWidth: 1,
      borderRadius: 2,
      alignSelf: 'center',
      backgroundColor: '#ffffff'
    },
  });

How can I achieved the design just like my example?

Thanks in advance

Body:
What i do in my application to tackle these type of situation is as follows:

1) Install a node module -

npm install react-native-keyboard-aware-scroll-view --save or yarn add react-native-keyboard-aware-scroll-view --save

2) Import the project into your project:

import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'

3) Encapsulate everything inside the <keyboardAwareScrollView> </keyboardAwareScrollView> like this:

render(){
    return (
      <KeyboardAwareScrollView  contentContainerStyle={{flex: 1,
      justifyContent: 'space-around',
      alignItems: 'center',
      width: null,
      height: null,}}>
       <View>
       ....
       </View>
      </KeyboardAwareScrollView>
     )
}

everything seems pretty good.

Cheers :)


问:
Keeping route coherent when navigating between components
I have a router connecting several components. Each component can modify the route so that its state can be preserved (copy paste to someone etc.).

Example :

/route/mycomp

play with some field

route becomes /route/mycomp;field=value

click on /route/othercomp, route adapts

click on /route/mycomp

route becomes route/mycomp

I would like it to remain /route/mycomp;field=value instead, since the component itself did not change.

What I tried :

changing my RouteReuseStrategy implementation

saving url in each component after each filter action

changing the DOM

Any ideas ?

Angular 2.3.1.

答:
This lecture helped :

How to implement RouteReuseStrategy shouldDetach for specific routes in Angular 2

```<code>import { RouteReuseStrategy } from '@angular/router'
import { DetachedRouteHandle } from '@angular/router'
import { ActivatedRouteSnapshot } from '@angular/router'

/**
 * Basic implementation comes from @manfredsteyer.
 * We extended it to add functionality described in current issue.
 */
export class CustomReuseStrategy implements RouteReuseStrategy {

  tab: string = null
  handlers: {[key: string]: any/*DetachedRouteHandle*/} = {}

  /// Should detach and not destroy: true (always)
  shouldDetach(route: ActivatedRouteSnapshot): boolean {

    return true

  }

  /// If detached, store
  store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {

    this.handlers[route.routeConfig.path] = {
      handle: handle,
      params: route.params
    }

  }

  /// Should reuse existing component: if avalaible
  shouldAttach(route: ActivatedRouteSnapshot): boolean {

    // Avoid multiple calls
    this.tab = route.routeConfig.path // current tab

    // the double exclamation mark (!!) casts to actual boolean
    return !!route.routeConfig && !!this.handlers[route.routeConfig.path]

  }

  /// Should we retrieve component and parameters
  retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {

    if (!route.routeConfig || !this.handlers[route.routeConfig.path])
      return null

    let handler = this.handlers[route.routeConfig.path]
    let sentParameters = route.url.slice(-1)[0].parameters
    let parameters = null

    // Send back params (only if current tab, last retrieve call)
    if (this.tab === route.routeConfig.path) {
      // Which parameters to send to the retrieved component ?

      // If you send parameters from one panel to another
      // (like clicking on a button to access a related object in another panel),
      // then use them
      if (Object.keys(sentParameters).length)
        parameters = sentParameters
      // if you don't, use the old ones (cf. **Expected behavior**)
      else
        parameters = handler.params

      // urlParse() is in each panel component (inheritance is your friend)
      // and can do some specific parameters name and/or value parsing
      // before injecting them into said component
      handler.handle.componentRef.instance.urlParse(parameters)
    }

    return handler.handle

  }

  // I'm not too sure about this part
  /// Should we load/retrieve other component: if path is different
  //  @todo /!\ if routeConfig is null, say "yes"
  shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {

    // @todo: strange case with null/null values
    return future.routeConfig === curr.routeConfig

  }

}
</code>```

(Copy paste of github.)

Body:
This lecture helped :

How to implement RouteReuseStrategy shouldDetach for specific routes in Angular 2

import { RouteReuseStrategy } from '@angular/router'
import { DetachedRouteHandle } from '@angular/router'
import { ActivatedRouteSnapshot } from '@angular/router'

/**
 * Basic implementation comes from @manfredsteyer.
 * We extended it to add functionality described in current issue.
 */
export class CustomReuseStrategy implements RouteReuseStrategy {

  tab: string = null
  handlers: {[key: string]: any/*DetachedRouteHandle*/} = {}

  /// Should detach and not destroy: true (always)
  shouldDetach(route: ActivatedRouteSnapshot): boolean {

    return true

  }

  /// If detached, store
  store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {

    this.handlers[route.routeConfig.path] = {
      handle: handle,
      params: route.params
    }

  }

  /// Should reuse existing component: if avalaible
  shouldAttach(route: ActivatedRouteSnapshot): boolean {

    // Avoid multiple calls
    this.tab = route.routeConfig.path // current tab

    // the double exclamation mark (!!) casts to actual boolean
    return !!route.routeConfig && !!this.handlers[route.routeConfig.path]

  }

  /// Should we retrieve component and parameters
  retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {

    if (!route.routeConfig || !this.handlers[route.routeConfig.path])
      return null

    let handler = this.handlers[route.routeConfig.path]
    let sentParameters = route.url.slice(-1)[0].parameters
    let parameters = null

    // Send back params (only if current tab, last retrieve call)
    if (this.tab === route.routeConfig.path) {
      // Which parameters to send to the retrieved component ?

      // If you send parameters from one panel to another
      // (like clicking on a button to access a related object in another panel),
      // then use them
      if (Object.keys(sentParameters).length)
        parameters = sentParameters
      // if you don't, use the old ones (cf. **Expected behavior**)
      else
        parameters = handler.params

      // urlParse() is in each panel component (inheritance is your friend)
      // and can do some specific parameters name and/or value parsing
      // before injecting them into said component
      handler.handle.componentRef.instance.urlParse(parameters)
    }

    return handler.handle

  }

  // I'm not too sure about this part
  /// Should we load/retrieve other component: if path is different
  //  @todo /!\ if routeConfig is null, say "yes"
  shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {

    // @todo: strange case with null/null values
    return future.routeConfig === curr.routeConfig

  }

}

(Copy paste of github.)


问:
FB.ui and setting popup size
I am using FB.ui with the display parameter set to popup.

When the method is 'stream.publish', it autoresizes when the content is loaded. However, when using 'fbml.dialog' (in order to display a multi-friend selector) it shows a size that I'm not able to change (and the content is displayed cropped).

I have tried with the following approaches, with no luck:

```<code>FB.ui({
method: 'fbml.dialog',
size: {width: 800, height: 500},
...

FB.ui({
method: 'fbml.dialog',
width: 800,
height: 500,
...
</code>```

Also I've been looking at the API source code, and it declares the method this way:

Method declaration:

```<code>'fbml.dialog': {
    size : { width: 575, height: 300 },
    url : 'render_fbml.php',
    loggedOutIframe : true
}...
</code>```

Functions that executes the methods:

```<code>// the basic call data
var call = {
  cb : cb,
  id : id,
  size : method.size || {},
  url : FB._domain.www + method.url,
  params : params
};
</code>```

Any help would be much appreciated...

答:
Use </p>

```<code>FB.UIServer.Methods["fbml.dialog"].size = {width:640, height:400};
</code>```

Title: FB.ui and setting popup size

Body:
I am using FB.ui with the display parameter set to popup.

When the method is 'stream.publish', it autoresizes when the content is loaded. However, when using 'fbml.dialog' (in order to display a multi-friend selector) it shows a size that I'm not able to change (and the content is displayed cropped).

I have tried with the following approaches, with no luck:

FB.ui({
method: 'fbml.dialog',
size: {width: 800, height: 500},
...

FB.ui({
method: 'fbml.dialog',
width: 800,
height: 500,
...

Also I've been looking at the API source code, and it declares the method this way:

Method declaration:

'fbml.dialog': {
    size : { width: 575, height: 300 },
    url : 'render_fbml.php',
    loggedOutIframe : true
}...

Functions that executes the methods:

// the basic call data
var call = {
  cb : cb,
  id : id,
  size : method.size || {},
  url : FB._domain.www + method.url,
  params : params
};

Any help would be much appreciated...

Body:
Use

FB.UIServer.Methods["fbml.dialog"].size = {width:640, height:400};


问:
LifecycleObserver is not working
Observer methods are not being called. I tested ViewPagerCycler as in old school ways and working perfect. Thanks for help.

```<code>public final class ViewPagerCycler implements LifecycleObserver {

    private static final int PERIOD = 3000;

    private Timer mTimer;
    private TimerTask mTask;
    private Activity mActivity;
    private ViewPager mPager;

    public ViewPagerCycler(Activity activity, ViewPager pager) {
        mActivity = activity;
        mPager = pager;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) public void start() {
        int count = mPager
            .getAdapter()
            .getCount();

        mTimer = new Timer();
        mTask = new TimerTask() {
            @Override public void run() {
                mActivity.runOnUiThread(new TimerTask() {
                    @Override public void run() {
                        mPager.setCurrentItem((mPager.getCurrentItem() + 1) % count, true);
                    }
                });
            }
        };
        mTimer.schedule(mTask, PERIOD, PERIOD);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) public void stop() {
        mTask.cancel();
        mTimer.cancel();
        mTimer.purge();
    }
}
</code>```

Activity is just summarized. I didn't add findViewByIds.

```<code>public class SummariziedActivity extends Activity implements LifecycleOwner {
   private final LifecycleRegistry mRegistry = new LifecycleRegistry(this);

   @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);

       mRegistry.addObserver(new ViewPagerCycler(mPager));
   }
}
</code>```

In the build.gradle:

```<code>compile "android.arch.lifecycle:runtime:1.0.0-alpha2"
compile "android.arch.lifecycle:extensions:1.0.0-alpha2"
annotationProcessor "android.arch.lifecycle:compiler:1.0.0-alpha2"
</code>```

答:
Instead of extending ordinary Activity, you should extend from LifecycleActivity.

Otherwise, you can refer to "Implementing LifecycleOwner in custom activities and fragments":

Any custom fragment or activity can be turned into a LifecycleOwner by implementing the built-in LifecycleRegistryOwner interface (instead of extending LifecycleFragment or LifecycleActivity).

```
<code>
    public class MyFragment extends Fragment implements LifecycleRegistryOwner {
        LifecycleRegistry lifecycleRegistry = new LifecycleRegistry(this);

        @Override
        public LifecycleRegistry getLifecycle() {
            return lifecycleRegistry;
        }
    }
</code>
```

If you have a custom class that you would like to make a LifecycleOwner, you can use the LifecycleRegistry class, but you will need to forward events into that class. This forwarding is done automatically for fragments and activities if they implement the LifecycleRegistryOwner interface.

Title: LifecycleObserver is not working

Body:
Observer methods are not being called. I tested ViewPagerCycler as in old school ways and working perfect. Thanks for help.

public final class ViewPagerCycler implements LifecycleObserver {

    private static final int PERIOD = 3000;

    private Timer mTimer;
    private TimerTask mTask;
    private Activity mActivity;
    private ViewPager mPager;

    public ViewPagerCycler(Activity activity, ViewPager pager) {
        mActivity = activity;
        mPager = pager;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) public void start() {
        int count = mPager
            .getAdapter()
            .getCount();

        mTimer = new Timer();
        mTask = new TimerTask() {
            @Override public void run() {
                mActivity.runOnUiThread(new TimerTask() {
                    @Override public void run() {
                        mPager.setCurrentItem((mPager.getCurrentItem() + 1) % count, true);
                    }
                });
            }
        };
        mTimer.schedule(mTask, PERIOD, PERIOD);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) public void stop() {
        mTask.cancel();
        mTimer.cancel();
        mTimer.purge();
    }
}

Activity is just summarized. I didn't add findViewByIds.

public class SummariziedActivity extends Activity implements LifecycleOwner {
   private final LifecycleRegistry mRegistry = new LifecycleRegistry(this);

   @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);

       mRegistry.addObserver(new ViewPagerCycler(mPager));
   }
}

In the build.gradle:

compile "android.arch.lifecycle:runtime:1.0.0-alpha2"
compile "android.arch.lifecycle:extensions:1.0.0-alpha2"
annotationProcessor "android.arch.lifecycle:compiler:1.0.0-alpha2"

Body:
Instead of extending ordinary Activity, you should extend from LifecycleActivity.

Otherwise, you can refer to "Implementing LifecycleOwner in custom activities and fragments":

Any custom fragment or activity can be turned into a LifecycleOwner by implementing the built-in LifecycleRegistryOwner interface (instead of extending LifecycleFragment or LifecycleActivity).

    public class MyFragment extends Fragment implements LifecycleRegistryOwner {
        LifecycleRegistry lifecycleRegistry = new LifecycleRegistry(this);

        @Override
        public LifecycleRegistry getLifecycle() {
            return lifecycleRegistry;
        }
    }

If you have a custom class that you would like to make a LifecycleOwner, you can use the LifecycleRegistry class, but you will need to forward events into that class. This forwarding is done automatically for fragments and activities if they implement the LifecycleRegistryOwner interface.


问:
jquery validate check at least one checkbox with dynamicly id's
I want to validate that atleast one checkbox is selected. The checkboxes are added dynamicly so the exact ID's are unknown. All i know is that they start with the same ID name e.g.  "Sameid_xxx", "Sameid_xx1"
,"Sameid_xx2" etc..

here is what i have:

```<code>$cbx_group = $('input[Id^="Sameid"]');

$cbx_group.prop('required', true);
if ($cbx_group.is(":checked")) {
  $cbx_group.prop('required', false);
}
</code>```

the problem here is that this makes all checkboxes required. I also dont have form validator

答:
You can check the number of checkboxes checked using length</p>

```<code> if($cbx_group.is(":checked").length > 0))
 {
    $cbx_group.prop('required', false);
 }
</code>```

Body:
I want to validate that atleast one checkbox is selected. The checkboxes are added dynamicly so the exact ID's are unknown. All i know is that they start with the same ID name e.g.  "Sameid_xxx", "Sameid_xx1"
,"Sameid_xx2" etc..

here is what i have:

$cbx_group = $('input[Id^="Sameid"]');

$cbx_group.prop('required', true);
if ($cbx_group.is(":checked")) {
  $cbx_group.prop('required', false);
}

the problem here is that this makes all checkboxes required. I also dont have form validator

Body:
You can check the number of checkboxes checked using length

 if($cbx_group.is(":checked").length > 0))
 {
    $cbx_group.prop('required', false);
 }


问:
How to manage the "Virus Warning" alert page with WebView and WebClient for Android?
Since google Drive can not download a file of more than 25 MB, as it requests the authorization of the user from an HTML page, I thought that it was necessary for these files to display the page "virus warning"  in a webView in my App. So I created this small sample in Android studio to test. It is quite simple a MainActivity and an activity.xml containing a simple WebView:

```<code>public class MainActivity extends AppCompatActivity {
private static final int WRITE_SDCARD_REQUEST_CODE = 12;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // permission to write file on internal storage ....
    if (ContextCompat.checkSelfPermission(MainActivity.this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {

        if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    WRITE_SDCARD_REQUEST_CODE);

        } else {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    WRITE_SDCARD_REQUEST_CODE);

        }
    }
    else {
        // launch my webPage and webClient withe the given url of my file
        WebView myWebView = (WebView) findViewById(R.id.webview);
        myWebView.loadUrl("https://drive.google.com/uc?export=download&id=0B4fwFC8FCSQGGTZfbHYwczBXVjg");
        myWebView.setWebViewClient(new MyWebViewClient());
    }

}

private class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // return after valid with "Download anyway " button
        Log.i("URL",url);//<-- url result: https://drive.google.com/uc?export=download&confirm=LoXi&id=0B4fwFC8FCSQGGTZfbHYwczBXVjg
        //with "confirm=LoXi" Added to the original link

        // so i try to download this new confirmed url given by Google Drive warning page
        // But the link is not valid for download!!!!! Why????
        DownloadFileFromURL dFURL = new DownloadFileFromURL();
        dFURL.execute(url);
        // I obtain a wrong file .... 36 Ko...not good!
        return true;
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if (requestCode == WRITE_SDCARD_REQUEST_CODE)
    if (grantResults.length > 0
            && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        WebView myWebView = (WebView) findViewById(R.id.webview);
        // original link of file Google drive that i want to download
        myWebView.loadUrl("https://drive.google.com/uc?export=download&id=0B4fwFC8FCSQXbTZfbHYwczBXVjg");
        myWebView.setWebViewClient(new MyWebViewClient());
    }

}

class DownloadFileFromURL extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Bar Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    /**
     * Downloading file in background thread
     * */
    @Override
    protected String doInBackground(String... f_url) {
        int count;
        try {
            URL url = new URL(f_url[0]);
            URLConnection conection = url.openConnection();
            conection.connect();

            // this will be useful so that you can show a tipical 0-100%
            // progress bar
            int lenghtOfFile = conection.getContentLength();

            // download the file
            InputStream input = new BufferedInputStream(url.openStream(),
                    8192);

            // Output stream
            OutputStream output = new FileOutputStream(Environment
                    .getExternalStorageDirectory().toString()
                    + "/video.mp4");

            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                // After this onProgressUpdate will be called
                publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                // writing data to file
                output.write(data, 0, count);
            }

            // flushing output
            output.flush();

            // closing streams
            output.close();
            input.close();

        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }

        return null;
    }

    /**
     * Updating progress bar
     * */
    protected void onProgressUpdate(String... progress) {
        // setting progress percentage
        //pDialog.setProgress(Integer.parseInt(progress[0]));
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    @Override
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after the file was downloaded
        //dismissDialog(progress_bar_type);
    }

}
</code>```

}

From the download link of my file of more than 25 MB (here 90 Mo) I display well the page "Virus Warning" of drive. After clicking on the download button "download anyway" I am able to get a modified link back in my WebClient. But this link does not seem valid. If I try to copy / paste it in chrome I return to the same page of the "virus Warning" !!! Why??

When I right click on the "download anyway" button to copy the link, this link is the same form that I get by my WebClient but the part "confirm=XXXX" not, and it works and gives me access to the download!

Could you give me your opinions and suggestions?

Thank you.

答:
I finally solved the problem by managing the cookies in my WebViewClient and using DownloadManager:``

```<code>private class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // prevent other actions on page
        if (url.contains("export=download&confirm")){
            DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
            Uri source = Uri.parse(url);
            DownloadManager.Request request = new DownloadManager.Request(source);
            String cookie = CookieManager.getInstance().getCookie(url);
            request.addRequestHeader("Cookie", cookie);
            request.addRequestHeader("User-Agent", view.getSettings().getUserAgentString());
            request.addRequestHeader("Accept", "text/html, application/xhtml+xml, *" + "/" + "*");
            request.addRequestHeader("Accept-Language", "en-US,en;q=0.7,he;q=0.3");
            request.addRequestHeader("Referer", url);
            request.setDestinationInExternalPublicDir("/","video.mp4");
            manager.enqueue(request);
        }else {
            // a keyEvent back listener should be implemented
            myWebView.loadUrl(url);
        }

        return true;
    }
    @Override
    public void onPageFinished(WebView view, String url){

    }
}
</code>```

I hope it will help.

Body:
Since google Drive can not download a file of more than 25 MB, as it requests the authorization of the user from an HTML page, I thought that it was necessary for these files to display the page "virus warning"  in a webView in my App. So I created this small sample in Android studio to test. It is quite simple a MainActivity and an activity.xml containing a simple WebView:

public class MainActivity extends AppCompatActivity {
private static final int WRITE_SDCARD_REQUEST_CODE = 12;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // permission to write file on internal storage ....
    if (ContextCompat.checkSelfPermission(MainActivity.this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {

        if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    WRITE_SDCARD_REQUEST_CODE);

        } else {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    WRITE_SDCARD_REQUEST_CODE);

        }
    }
    else {
        // launch my webPage and webClient withe the given url of my file
        WebView myWebView = (WebView) findViewById(R.id.webview);
        myWebView.loadUrl("https://drive.google.com/uc?export=download&id=0B4fwFC8FCSQGGTZfbHYwczBXVjg");
        myWebView.setWebViewClient(new MyWebViewClient());
    }

}

private class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // return after valid with "Download anyway " button
        Log.i("URL",url);//<-- url result: https://drive.google.com/uc?export=download&confirm=LoXi&id=0B4fwFC8FCSQGGTZfbHYwczBXVjg
        //with "confirm=LoXi" Added to the original link

        // so i try to download this new confirmed url given by Google Drive warning page
        // But the link is not valid for download!!!!! Why????
        DownloadFileFromURL dFURL = new DownloadFileFromURL();
        dFURL.execute(url);
        // I obtain a wrong file .... 36 Ko...not good!
        return true;
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if (requestCode == WRITE_SDCARD_REQUEST_CODE)
    if (grantResults.length > 0
            && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        WebView myWebView = (WebView) findViewById(R.id.webview);
        // original link of file Google drive that i want to download
        myWebView.loadUrl("https://drive.google.com/uc?export=download&id=0B4fwFC8FCSQXbTZfbHYwczBXVjg");
        myWebView.setWebViewClient(new MyWebViewClient());
    }

}

class DownloadFileFromURL extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Bar Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    /**
     * Downloading file in background thread
     * */
    @Override
    protected String doInBackground(String... f_url) {
        int count;
        try {
            URL url = new URL(f_url[0]);
            URLConnection conection = url.openConnection();
            conection.connect();

            // this will be useful so that you can show a tipical 0-100%
            // progress bar
            int lenghtOfFile = conection.getContentLength();

            // download the file
            InputStream input = new BufferedInputStream(url.openStream(),
                    8192);

            // Output stream
            OutputStream output = new FileOutputStream(Environment
                    .getExternalStorageDirectory().toString()
                    + "/video.mp4");

            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                // After this onProgressUpdate will be called
                publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                // writing data to file
                output.write(data, 0, count);
            }

            // flushing output
            output.flush();

            // closing streams
            output.close();
            input.close();

        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }

        return null;
    }

    /**
     * Updating progress bar
     * */
    protected void onProgressUpdate(String... progress) {
        // setting progress percentage
        //pDialog.setProgress(Integer.parseInt(progress[0]));
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    @Override
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after the file was downloaded
        //dismissDialog(progress_bar_type);
    }

}

}

From the download link of my file of more than 25 MB (here 90 Mo) I display well the page "Virus Warning" of drive. After clicking on the download button "download anyway" I am able to get a modified link back in my WebClient. But this link does not seem valid. If I try to copy / paste it in chrome I return to the same page of the "virus Warning" !!! Why??

When I right click on the "download anyway" button to copy the link, this link is the same form that I get by my WebClient but the part "confirm=XXXX" not, and it works and gives me access to the download!

Could you give me your opinions and suggestions?

Thank you.

Body:
I finally solved the problem by managing the cookies in my WebViewClient and using DownloadManager:``

private class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // prevent other actions on page
        if (url.contains("export=download&confirm")){
            DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
            Uri source = Uri.parse(url);
            DownloadManager.Request request = new DownloadManager.Request(source);
            String cookie = CookieManager.getInstance().getCookie(url);
            request.addRequestHeader("Cookie", cookie);
            request.addRequestHeader("User-Agent", view.getSettings().getUserAgentString());
            request.addRequestHeader("Accept", "text/html, application/xhtml+xml, *" + "/" + "*");
            request.addRequestHeader("Accept-Language", "en-US,en;q=0.7,he;q=0.3");
            request.addRequestHeader("Referer", url);
            request.setDestinationInExternalPublicDir("/","video.mp4");
            manager.enqueue(request);
        }else {
            // a keyEvent back listener should be implemented
            myWebView.loadUrl(url);
        }

        return true;
    }
    @Override
    public void onPageFinished(WebView view, String url){

    }
}

I hope it will help.


答:
Use $cbx_group.is(":checked") like below:-

The below code will do two things:-

1.remove required from all check-boxes if any-one is checked.

2.Add required again back to all check-boxes when all check-boxes are un-checked.

Code:-

$cbx_group = $('input[Id^="Sameid"]');
$cbx_group.prop('required', true);
$cbx_group.on('click',function(){
  if($cbx_group.is(":checked")) {
    $cbx_group.prop('required', false);
  }else{
    $cbx_group.prop('required', true);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="Sameid_XXX">1<br>
<input type="checkbox" id="Sameid_XX1">2<br>
<input type="checkbox" id="Sameid_XX2">3<br>
<input type="checkbox" id="Sameid_XX3">4<br></code>```

Reference taken:- https://stackoverflow.com/a/39849541/4248328

Title: jquery validate check at least one checkbox with dynamicly id's

Body:
Use $cbx_group.is(":checked") like below:-

The below code will do two things:-

1.remove required from all check-boxes if any-one is checked.

2.Add required again back to all check-boxes when all check-boxes are un-checked.

Code:-

$cbx_group = $('input[Id^="Sameid"]');
$cbx_group.prop('required', true);
$cbx_group.on('click',function(){
  if($cbx_group.is(":checked")) {
    $cbx_group.prop('required', false);
  }else{
    $cbx_group.prop('required', true);
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="Sameid_XXX">1<br>
<input type="checkbox" id="Sameid_XX1">2<br>
<input type="checkbox" id="Sameid_XX2">3<br>
<input type="checkbox" id="Sameid_XX3">4<br>

Reference taken:- https://stackoverflow.com/a/39849541/4248328


问:
Any ideas on a WCF Interceptor for a REST WebGet request to change the Url/Querystring parameters
Does any one know of a way I can intercept a REST Get request inside WCF, so for example I could change the value of any of the querystring parameters.  So I need to have some code run, prior to WCF Evaluating the UriTemplate of the WebGet attribute and be able to edit it, before returning the value which it will use to continue processing the request.

Any help would be greatly appreciated

Andrew

答:
This little snippet shows you how you can change/alter the url:</p>

```<code>    /// <summary>
    /// Interface for communicating with twitter.com.
    /// </summary>
    [ServiceContract]
    public interface ITwitterClient
    {
        [OperationContract]
        [WebGet(UriTemplate = "statuses/user_timeline/{twitterName}.xml?count={numberOfTweets}",
            BodyStyle = WebMessageBodyStyle.Bare,
            RequestFormat = WebMessageFormat.Xml,
            ResponseFormat = WebMessageFormat.Xml)]
        Statuses PublicTimeline(string twitterName, int numberOfTweets);
    }
</code>```

Body:
This little snippet shows you how you can change/alter the url:

    /// <summary>
    /// Interface for communicating with twitter.com.
    /// </summary>
    [ServiceContract]
    public interface ITwitterClient
    {
        [OperationContract]
        [WebGet(UriTemplate = "statuses/user_timeline/{twitterName}.xml?count={numberOfTweets}",
            BodyStyle = WebMessageBodyStyle.Bare,
            RequestFormat = WebMessageFormat.Xml,
            ResponseFormat = WebMessageFormat.Xml)]
        Statuses PublicTimeline(string twitterName, int numberOfTweets);
    }


问:
AngularJs checkbox issue single variable
I'm new to angularjs v1. I want to know why I cannot assign a single variable scope into the md-checkbox. like

```<code><md-checkbox ng-click="checkAllBox();" ng-model="chkValue" aria-label="Checkbox" style="float:left;margin-left:-4px;" class="md-primary"></md-checkbox>
</code>```

;controller

```<code>$scope.chkValue = false;
</code>```

which doesn't work (the $scope.chkValue didn't associate with the UI checkbox correctly). But the below is ok. May I know why?

```<code><md-checkbox ng-click="checkAllBox();" ng-model="data.cb1" aria-label="Checkbox" style="float:left;margin-left:-4px;" class="md-primary"></md-checkbox>
</code>```

;controller

```<code>$scope.data.cb1 = false;
</code>```

答:
Because you are changing a variable from child scope the parent scope variable never changed.. Scope's has inheritance. You can get information from docs

Edit

To be more spesific. Controllers, some directives('ng-if', 'ng-include', vs.), isolate scopes creates its own scope.

If you want to referance a variable you need to use it with variables owner.

There is a live answer below. You can see controller has created its own scope and the parent scope cant detect changes because it has a different owner(this) now.

var app = angular.module("app",[]);
app.controller("ctrl", function($scope){
  $scope.checkData = false;
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  </head>
  <body  ng-app="app"  >
    parent1:<input ng-model="checkData" type="checkbox"/>

      <div class="child">
        <div class="child">
          <div class="innerChild">
            inner1:<input ng-model="checkData" type="checkbox"/>
          </div>
            <div class="innerChild">
              inner2:<input ng-model="checkData" type="checkbox"/>
          </div>
        </div>
      </div>
    Controller Scope -><br>
parent2:<input ng-model="checkData" type="checkbox"/>
    <div ng-controller="ctrl" >
      <div class="child">
        <div class="child">
          <div class="innerChild">
            inner1:<input ng-model="checkData" type="checkbox"/>
          </div>
            <div class="innerChild">
              inner2:<input ng-model="checkData" type="checkbox"/>
          </div>
        </div>
      </div>
      <div class="child">
        <div class="innerChild">
          inner3:<input ng-model="checkData" type="checkbox"/>
        </div>
      </div>
    </div>
  </body>
</html></code>```

Body:
I'm new to angularjs v1. I want to know why I cannot assign a single variable scope into the md-checkbox. like

<md-checkbox ng-click="checkAllBox();" ng-model="chkValue" aria-label="Checkbox" style="float:left;margin-left:-4px;" class="md-primary"></md-checkbox>

;controller

$scope.chkValue = false;

which doesn't work (the $scope.chkValue didn't associate with the UI checkbox correctly). But the below is ok. May I know why?

<md-checkbox ng-click="checkAllBox();" ng-model="data.cb1" aria-label="Checkbox" style="float:left;margin-left:-4px;" class="md-primary"></md-checkbox>

;controller

$scope.data.cb1 = false;

Body:
Because you are changing a variable from child scope the parent scope variable never changed.. Scope's has inheritance. You can get information from docs

Edit

To be more spesific. Controllers, some directives('ng-if', 'ng-include', vs.), isolate scopes creates its own scope.

If you want to referance a variable you need to use it with variables owner.

There is a live answer below. You can see controller has created its own scope and the parent scope cant detect changes because it has a different owner(this) now.

var app = angular.module("app",[]);
app.controller("ctrl", function($scope){
  $scope.checkData = false;
})

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  </head>
  <body  ng-app="app"  >
    parent1:<input ng-model="checkData" type="checkbox"/>

      <div class="child">
        <div class="child">
          <div class="innerChild">
            inner1:<input ng-model="checkData" type="checkbox"/>
          </div>
            <div class="innerChild">
              inner2:<input ng-model="checkData" type="checkbox"/>
          </div>
        </div>
      </div>
    Controller Scope -><br>
parent2:<input ng-model="checkData" type="checkbox"/>
    <div ng-controller="ctrl" >
      <div class="child">
        <div class="child">
          <div class="innerChild">
            inner1:<input ng-model="checkData" type="checkbox"/>
          </div>
            <div class="innerChild">
              inner2:<input ng-model="checkData" type="checkbox"/>
          </div>
        </div>
      </div>
      <div class="child">
        <div class="innerChild">
          inner3:<input ng-model="checkData" type="checkbox"/>
        </div>
      </div>
    </div>
  </body>
</html>


问:
Finding union of two columns based on the uniqueness of an unrelated column
I am trying to determine how each student will perform on a head to head basis with respect to the classes they have been in and projects they have completed.

scores.csv: https://pastebin.com/FxUCb4xT

```<code>import pandas as pd
df = pd.read_csv("Documents/scores.csv")

student_ids = df.student_id.unique()

for id in student_ids:
    to_analyse = pd.merge(df,df[df['student_id'] == id][['class_id','project_id']])
</code>```

I will end up doing my own thing to to_analyse but getting there in the first place is awfully slow using pd.merge especially if there's 10's of thousands of unique student ids.

Is there a more efficient way to do this? I have tried using pivot table but maybe  I'm barking up the wrong tree using that approach.

答:
I think a bit faster is use groupby:

```<code>def f(x):
    print (pd.merge(df, x[['class_id','project_id']]))

df = df.groupby('student_id').apply(f)
</code>```

Solution without merge with concatenating columns, isin and boolean indexing:

```<code>df['both'] = df['class_id'].astype(str)  + '_' + df['project_id'].astype(str)

def f(x):
    print (df[df['both'].isin(x['both'])])

df = df.groupby('student_id').apply(f).drop('both', axis=1)
</code>```

Body:
I am trying to determine how each student will perform on a head to head basis with respect to the classes they have been in and projects they have completed.

scores.csv: https://pastebin.com/FxUCb4xT

import pandas as pd
df = pd.read_csv("Documents/scores.csv")

student_ids = df.student_id.unique()

for id in student_ids:
    to_analyse = pd.merge(df,df[df['student_id'] == id][['class_id','project_id']])

I will end up doing my own thing to to_analyse but getting there in the first place is awfully slow using pd.merge especially if there's 10's of thousands of unique student ids.

Is there a more efficient way to do this? I have tried using pivot table but maybe  I'm barking up the wrong tree using that approach.

Body:
I think a bit faster is use groupby:

def f(x):
    print (pd.merge(df, x[['class_id','project_id']]))

df = df.groupby('student_id').apply(f)

Solution without merge with concatenating columns, isin and boolean indexing:

df['both'] = df['class_id'].astype(str)  + '_' + df['project_id'].astype(str)

def f(x):
    print (df[df['both'].isin(x['both'])])

df = df.groupby('student_id').apply(f).drop('both', axis=1)


问:
Loop to replicate values into an array
I’m in a situation where I need to reproduce something in VBA and a bit stuck given my lack of understanding of object oriented language and VBA in general.

Problem:

I need to produce an array or vector based on a 2 column table.

The first range (column) contains unit counts.

The second range (column) contains numeric values.

I need to replicate the value based on the number of units.

For example,

if the first row contains 3 units with a value of $100
   I need the array to contain $100, $100, $100.

   This will need to be looped thru each row containing units.

    So if row 2 contains 2 units with a value of $50

    I need to complete array to be $100, $100, $100, $50, $50, and so on.

I understand this situation will require ReDim the array based on the total values.  My struggle is I’ve been unable to figure out the nested for loops.

I get how to replicate the value based on the number of “units” like the below...

```<code>    ReDim arr(0 To x - 1)
    For i = 0 To x - 1
    arr(i) = rng.Offset(0, 1).Value
    Next
</code>```

What is the best way to loop thru each row and replicate the values for each row in the range based on the unit count?

If anyone is familiar with R, I'm essentially looking for something that achieves the rep() function (e.g., rep(df$b, df$a)) and return the values in a single array.

Any help is greatly appreciated.  Thanks

答:
Or a one liner which uses the REPT function as you would have used in r :)

This assumes your data is in A1:B10 - the length can be made variable

s = Split(Join(Application.Transpose(Evaluate("=INDEx(REPT(B1:B10&"","",A1:A10),,1)"))), ",")

An an example, to dump the new to array to C1

```<code>s = Split(Join(Application.Transpose(Evaluate("=INDEx(REPT(B1:B10&"","",A1:A10),,1)"))), ",")
[c1].Resize(UBound(s), 1) = Application.Transpose(s)
</code>```

Title: Loop to replicate values into an array

Body:
I’m in a situation where I need to reproduce something in VBA and a bit stuck given my lack of understanding of object oriented language and VBA in general.

Problem:

I need to produce an array or vector based on a 2 column table.

The first range (column) contains unit counts.

The second range (column) contains numeric values.

I need to replicate the value based on the number of units.

For example,

if the first row contains 3 units with a value of $100
   I need the array to contain $100, $100, $100.

   This will need to be looped thru each row containing units.

    So if row 2 contains 2 units with a value of $50

    I need to complete array to be $100, $100, $100, $50, $50, and so on.

I understand this situation will require ReDim the array based on the total values.  My struggle is I’ve been unable to figure out the nested for loops.

I get how to replicate the value based on the number of “units” like the below...

    ReDim arr(0 To x - 1)
    For i = 0 To x - 1
    arr(i) = rng.Offset(0, 1).Value
    Next

What is the best way to loop thru each row and replicate the values for each row in the range based on the unit count?

If anyone is familiar with R, I'm essentially looking for something that achieves the rep() function (e.g., rep(df$b, df$a)) and return the values in a single array.

Any help is greatly appreciated.  Thanks

Body:
Or a one liner which uses the REPT function as you would have used in r :)

This assumes your data is in A1:B10 - the length can be made variable

s = Split(Join(Application.Transpose(Evaluate("=INDEx(REPT(B1:B10&"","",A1:A10),,1)"))), ",")

An an example, to dump the new to array to C1

s = Split(Join(Application.Transpose(Evaluate("=INDEx(REPT(B1:B10&"","",A1:A10),,1)"))), ",")
[c1].Resize(UBound(s), 1) = Application.Transpose(s)