问:
Disable/Enable "save-button" using JavaScript
I´ve set the attribute "disable" to my save-button and my goal is it to enable it, when the user fill out all input fields from the form.

For now it works, cause i set the onkeyup="checkForm(this)" in the last input field, but thats not a smart way to fix my problem.

Heres my html code from my form:

```<code>div class="page" id="create__book__formular">

        <div class="page__formular">

            <h3 id="formualer__name">Formular</h3>

            <label>Name:
                <input type="text" placeholder="Name" id="title" >
                </label>
            <label>Autor:
                <input type="text" placeholder="Autor" id="autor">
            </label>
            <label>ISBN:
                <input type="text" placeholder="ISBN" id="isbn">
            </label>
            <label>Anazhl:
                <input type="text" placeholder="Anazhl" id="number">
            </label>
            <label>Verlag:
                <input type="text" onkeyup="checkForm(this)" placeholder="Verlag" id="publishing">
            </label>

            <button type="button" class="btn btn-success create__book__formular" id="save--button" disabled="disabled">
                    save
            </button>
            <button type=" button " class="btn btn-light create__book__formular" id="back--button">
                back
            </button>
        </div>

    </div>
</code>```

Heres my JavaScript code:

```<code>function checkForm(create__book__formular) {
var bt = document.getElementById('save--button');
if (create__book__formular.value != '') {
    bt.disabled = false;
} else {
    bt.disabled = true;
}
</code>```

}

Thanks for your help!

答:
I've found the following post asking something similar.

They provide the following code:

```<code>(function() {
    $('form > input').keyup(function() {

        var empty = false;
        $('form > input').each(function() {
            if ($(this).val() == '') {
                empty = true;
            }
        });

        if (empty) {
            $('#register').attr('disabled', 'disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
        } else {
            $('#register').removeAttr('disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
        }
    });
})()
</code>```

This code should keep the submit button disabled if there is at least 1 field empty.

Body:
I´ve set the attribute "disable" to my save-button and my goal is it to enable it, when the user fill out all input fields from the form.

For now it works, cause i set the onkeyup="checkForm(this)" in the last input field, but thats not a smart way to fix my problem.

Heres my html code from my form:

div class="page" id="create__book__formular">

Formular

            Name:
                <input type="text" placeholder="Name" id="title" >

            Autor:
                <input type="text" placeholder="Autor" id="autor">

            ISBN:
                <input type="text" placeholder="ISBN" id="isbn">

            Anazhl:
                <input type="text" placeholder="Anazhl" id="number">

            Verlag:
                <input type="text" onkeyup="checkForm(this)" placeholder="Verlag" id="publishing">

            <button type="button" class="btn btn-success create__book__formular" id="save--button" disabled="disabled">
                    save
            </button>
            <button type=" button " class="btn btn-light create__book__formular" id="back--button">
                back
            </button>

Heres my JavaScript code:

function checkForm(create__book__formular) {
var bt = document.getElementById('save--button');
if (create__book__formular.value != '') {
    bt.disabled = false;
} else {
    bt.disabled = true;
}

}

Thanks for your help!

Body:
I've found the following post asking something similar.

They provide the following code:

(function() {
    $('form > input').keyup(function() {

        var empty = false;
        $('form > input').each(function() {
            if ($(this).val() == '') {
                empty = true;
            }
        });

        if (empty) {
            $('#register').attr('disabled', 'disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
        } else {
            $('#register').removeAttr('disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
        }
    });
})()

This code should keep the submit button disabled if there is at least 1 field empty.


来源: stackexchange

问:
Can't deserialize JSON object using custom deserializer
I have a JSON file like this:

```<code>{
  "Properties": {
    "String": "one-string-value",
    "Number": 123,
    "LiteralList": [
      "first-value",
      "second-value"
    ],
    "Boolean": true,
    "ReferenceForOneValue": {
      "Ref": "MyLogicalResourceName"
    }
  }
}
</code>```

I want to use Jackson to deserialize it into a proper Map<String,Property>. For this i'm using TypeReference like so:

```<code>public class Template {

    @JsonProperty("Properties")
    @JsonDeserialize(using = PropertyDeserializer.class)
    public Map<String, Object> propertyList;
}

public class PropertyDeserializer extends JsonDeserializer<Map<String, Property>> {
    public Map<String, Property> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
            throws IOException, JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        Map<String,Property> result =
                mapper.readValue(jsonParser, new TypeReference<Map<String,Property>>() {});

        return result;
    }
}
</code>```

Each Property can only take some values: strings, ints, booleans, a list of strings, or another object which has one key "Ref". So I wrote this:

```<code>public class Property {

    private Object value;

    public Property(String value) {
        this.value = value;
    }

    public Property(int value) {
        this.value = value;
    }

    public Property(List<String> values) {
        this.value = values;
    }
    public Property(boolean value) {
        this.value = value;
    }

    public Property(Ref reference) {
        this.value = reference;
    }

}

public class Ref {

    private String reference;

    @JsonCreator
    public Ref(@JsonProperty("Ref")  String reference) {
        this.reference = reference;
    }
}
</code>```

However, this doesn't work:

For the LiteralList property, I get the error Cannot deserialize instance of Property out of START_ARRAY token

For the ReferenceForOneValue property, I get the error Cannot construct instance of Property (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)

I have uploaded all the source code here.

Can someone help me write a deserializer for this?

答:
Here is my solution, it uses Java reflection to match property constructor to json data type. I had to modify the property constructors a bit to match Jackson deserialization (use wrapper types instead of primitives). Also, reference type is built from Map (Reference class is stripped of all Jackson annotations)

Property class:

```<code>import java.util.List;
import java.util.Map;

public class Property {

    private Object value;

    public Property(String value) {
        this.value = value;
    }

    public Property(Integer value) {
        this.value = value;
    }

    public Property(List<String> values) {
        this.value = values;
    }

    public Property(Boolean value) {
        this.value = value;
    }

    public Property(Ref reference) {  // not used
        this.value = reference;
    }

    // reference is received as map
    public Property(Map<String, String> map) {
        if (map.containsKey("Ref")) {
            this.value = new Ref(map.get("Ref"));
        } else {
            throw new IllegalArgumentException("invalid reference property");
        }
    }

    @Override
    public String toString() {
        return value.toString();
    }
}
</code>```

Template class

```<code>import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class Template {

    @JsonIgnore
    public Map<String, Property> propertyList = new HashMap<>();

    // map of data type from json to property constructor
    private static Map<Class<?>, Constructor<Property>> propertyConstructors;

    // build propertyConstructors map
    static {
        propertyConstructors = new HashMap<>();
        @SuppressWarnings("unchecked")
        Constructor<Property>[] constructors = (Constructor<Property>[])Property.class.getConstructors();
        for (Constructor<Property> ctor : constructors) {
            if (ctor.getParameterCount() == 1) {
                propertyConstructors.put(ctor.getParameterTypes()[0], ctor);
            }
        }
    }

    @JsonProperty("Properties")
    public void setProperties(Map<String, Object> jsonProperties) {
        if (jsonProperties == null  ||  jsonProperties.isEmpty()) return;
        for (Map.Entry<String, Object> property : jsonProperties.entrySet()) {
            Optional<Constructor<Property>> optionalCtor =
                propertyConstructors.keySet().stream()
                    .filter(argType -> argType.isAssignableFrom(property.getValue().getClass()))
                    .map(argType -> propertyConstructors.get(argType))
                    .findFirst();
            if (optionalCtor.isPresent()) {
                try {
                    propertyList.put(property.getKey(), optionalCtor.get().newInstance(property.getValue()));
                } catch (ReflectiveOperationException e) {
                    throw new IllegalArgumentException("invalid property " + property.getKey());
                }
            }
        }
    }
}
</code>```

the deserialization is straightforward:

```<code>Template t = mapper.readValue(in, Template.class);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a JSON file like this:

{
  "Properties": {
    "String": "one-string-value",
    "Number": 123,
    "LiteralList": [
      "first-value",
      "second-value"
    ],
    "Boolean": true,
    "ReferenceForOneValue": {
      "Ref": "MyLogicalResourceName"
    }
  }
}

I want to use Jackson to deserialize it into a proper Map<String,Property>. For this i'm using TypeReference like so:

public class Template {

    @JsonProperty("Properties")
    @JsonDeserialize(using = PropertyDeserializer.class)
    public Map<String, Object> propertyList;
}

public class PropertyDeserializer extends JsonDeserializer<Map<String, Property>> {
    public Map<String, Property> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
            throws IOException, JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        Map<String,Property> result =
                mapper.readValue(jsonParser, new TypeReference<Map<String,Property>>() {});

        return result;
    }
}

Each Property can only take some values: strings, ints, booleans, a list of strings, or another object which has one key "Ref". So I wrote this:

public class Property {

    private Object value;

    public Property(String value) {
        this.value = value;
    }

    public Property(int value) {
        this.value = value;
    }

    public Property(List<String> values) {
        this.value = values;
    }
    public Property(boolean value) {
        this.value = value;
    }

    public Property(Ref reference) {
        this.value = reference;
    }

}

public class Ref {

    private String reference;

    @JsonCreator
    public Ref(@JsonProperty("Ref")  String reference) {
        this.reference = reference;
    }
}

However, this doesn't work:

For the LiteralList property, I get the error Cannot deserialize instance of Property out of START_ARRAY token

For the ReferenceForOneValue property, I get the error Cannot construct instance of Property (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)

I have uploaded all the source code here.

Can someone help me write a deserializer for this?

Body:
Here is my solution, it uses Java reflection to match property constructor to json data type. I had to modify the property constructors a bit to match Jackson deserialization (use wrapper types instead of primitives). Also, reference type is built from Map (Reference class is stripped of all Jackson annotations)

Property class:

import java.util.List;
import java.util.Map;

public class Property {

    private Object value;

    public Property(String value) {
        this.value = value;
    }

    public Property(Integer value) {
        this.value = value;
    }

    public Property(List<String> values) {
        this.value = values;
    }

    public Property(Boolean value) {
        this.value = value;
    }

    public Property(Ref reference) {  // not used
        this.value = reference;
    }

    // reference is received as map
    public Property(Map<String, String> map) {
        if (map.containsKey("Ref")) {
            this.value = new Ref(map.get("Ref"));
        } else {
            throw new IllegalArgumentException("invalid reference property");
        }
    }

    @Override
    public String toString() {
        return value.toString();
    }
}

Template class

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class Template {

    @JsonIgnore
    public Map<String, Property> propertyList = new HashMap<>();

    // map of data type from json to property constructor
    private static Map<Class<?>, Constructor<Property>> propertyConstructors;

    // build propertyConstructors map
    static {
        propertyConstructors = new HashMap<>();
        @SuppressWarnings("unchecked")
        Constructor<Property>[] constructors = (Constructor<Property>[])Property.class.getConstructors();
        for (Constructor<Property> ctor : constructors) {
            if (ctor.getParameterCount() == 1) {
                propertyConstructors.put(ctor.getParameterTypes()[0], ctor);
            }
        }
    }

    @JsonProperty("Properties")
    public void setProperties(Map<String, Object> jsonProperties) {
        if (jsonProperties == null  ||  jsonProperties.isEmpty()) return;
        for (Map.Entry<String, Object> property : jsonProperties.entrySet()) {
            Optional<Constructor<Property>> optionalCtor =
                propertyConstructors.keySet().stream()
                    .filter(argType -> argType.isAssignableFrom(property.getValue().getClass()))
                    .map(argType -> propertyConstructors.get(argType))
                    .findFirst();
            if (optionalCtor.isPresent()) {
                try {
                    propertyList.put(property.getKey(), optionalCtor.get().newInstance(property.getValue()));
                } catch (ReflectiveOperationException e) {
                    throw new IllegalArgumentException("invalid property " + property.getKey());
                }
            }
        }
    }
}

the deserialization is straightforward:

Template t = mapper.readValue(in, Template.class);


问:
RabbitMQ Web Management Console Access Denied for Non-guest User with Valid Credentials
I had finished installing RabbitMQ (my first time dealing with it) on a CentOS 7 installation
and was trying to log into the web management console but to no avail.

I had created an admin user and set administrator tags for the user
since it seemed that it was highly discouraged to use the guest user
for logging into the web management console remotely.

I knew the credentials were correct but the login page kept telling me
"Login Failed"
while the logs showed:

```<code>2020-02-19 09:56:27.069 [warning] <0.622.0> HTTP access denied: user 'rbt_admn' - invalid credentials
</code>```

Googling only seemed to give results for people facing similar problems but who were mostly trying to login with guest or had incompatibility issues but I was sure none of those were the problem for me.

After a sleepless night of troubleshooting, I was able to solve it. So I'll post my solution below in case this is of use to someone in the future.

答:
I came accross the command
rabbitmqctl authenticate_user.

So I tried it with the user account:

```<code>rabbitmqctl authenticate_user rbt_admn
</code>```

Entered the correct password only for it to report

```<code>Error: failed to authenticate user "rbt_admn"
</code>```

I tried it a couple of more times just to be sure and then it occurred to me.
My password had dollar signs. As in something like (but not) "P4$$w0rd"
So I deleted the user

```<code>rabbitmqctl delete_user rbt_admn
</code>```

Recreated the user again with a different password and mercifully it worked.

I'm not sure why this happened but I think the dollar signs caused bash
(maybe? I am not well versed in shell scripting)
to feed and have rabbitmqctl store something different from my intended password.

If someone can explain why this happened they are more than welcome to do so.

Body:
I had finished installing RabbitMQ (my first time dealing with it) on a CentOS 7 installation
and was trying to log into the web management console but to no avail.

I had created an admin user and set administrator tags for the user
since it seemed that it was highly discouraged to use the guest user
for logging into the web management console remotely.

I knew the credentials were correct but the login page kept telling me
"Login Failed"
while the logs showed:

2020-02-19 09:56:27.069 [warning] <0.622.0> HTTP access denied: user 'rbt_admn' - invalid credentials

Googling only seemed to give results for people facing similar problems but who were mostly trying to login with guest or had incompatibility issues but I was sure none of those were the problem for me.

After a sleepless night of troubleshooting, I was able to solve it. So I'll post my solution below in case this is of use to someone in the future.

Body:
I came accross the command
rabbitmqctl authenticate_user.

So I tried it with the user account:

rabbitmqctl authenticate_user rbt_admn

Entered the correct password only for it to report

Error: failed to authenticate user "rbt_admn"

I tried it a couple of more times just to be sure and then it occurred to me.
My password had dollar signs. As in something like (but not) "P4$$w0rd"
So I deleted the user

rabbitmqctl delete_user rbt_admn

Recreated the user again with a different password and mercifully it worked.

I'm not sure why this happened but I think the dollar signs caused bash
(maybe? I am not well versed in shell scripting)
to feed and have rabbitmqctl store something different from my intended password.

If someone can explain why this happened they are more than welcome to do so.


问:
Prevent selecting more than X elements
I'm using jQuery to allow a user to select 3 time blocks and no more.

Once they've selected the 3 blocks, I'd like to prevent them from selecting more.

I am however, not having too much luck with it.

My current code can be found here : https://jsfiddle.net/1q8mzbwv/

I am trying an increment value of selected_num and adding a return false, but it's not preventing the selection.

I'd also like to try do this in reverse, where the user can click the selected item and the count changes too.

jQuery code :

```<code>var selected_num = 0;

$('.time-block').click(function()
{
var id = $(this).data('id');
var chosen_time = $(this).data('time');

$(this).addClass('-chosen');

$('.time-selected-block').eq(selected_num).html(chosen_time);

if(selected_num == "3")
{
    return false;
}
else
{
    selected_num++;
}

console.log(selected_num);
})
</code>```

Thanks

答:
You may try the following:

```<code>$('.time-block').click(function () {
    if ($('.-chosen').length < 3 || $(this).hasClass('-chosen')) {
        $(this).toggleClass('-chosen')
    }
})
</code>```

Here's the modified jsfiddle.

Title: Prevent selecting more than X elements

Body:
I'm using jQuery to allow a user to select 3 time blocks and no more.

Once they've selected the 3 blocks, I'd like to prevent them from selecting more.

I am however, not having too much luck with it.

My current code can be found here : https://jsfiddle.net/1q8mzbwv/

I am trying an increment value of selected_num and adding a return false, but it's not preventing the selection.

I'd also like to try do this in reverse, where the user can click the selected item and the count changes too.

jQuery code :

var selected_num = 0;

$('.time-block').click(function()
{
var id = $(this).data('id');
var chosen_time = $(this).data('time');

$(this).addClass('-chosen');

$('.time-selected-block').eq(selected_num).html(chosen_time);

if(selected_num == "3")
{
    return false;
}
else
{
    selected_num++;
}

console.log(selected_num);
})

Thanks

Body:
You may try the following:

$('.time-block').click(function () {
    if ($('.-chosen').length < 3 || $(this).hasClass('-chosen')) {
        $(this).toggleClass('-chosen')
    }
})

Here's the modified jsfiddle.


问:
Image Map Not displaying Clickable Links
Trying to get an image map to work and can't see where my coding is off!

```<code><img src="images/lazyweb/stores.png"  border="0" usemap="#storemap" />
<map name="storemap">
    <area shape="rect" coords="96,155,343,326"      href="https://www.etsy.com">
    <area shape="rect" coords="414,155,663,327"     href="https://www.amazon.co.uk">
    <area shape="rect" coords="743,153,986,326"     href="https://www.ebay.co.uk">
</map>
</code>```

I've used Dreamweaver to generate the co-ordinates, and that gives a visible template over the image, so I'm confident that the co-ordinates are ok (famous last words), but the displayed image just doesn't have any clickable links.

答:
I don't see anything wrong with your code. Some script or CSS rules might be messing with you.

If it doesn't work you can always try positioning links using CSS.
see example below

#img {
  position: relative;
  width: 1124px;
  height: 426px;
  background:url('https://lazycarrot.co.uk/images/lazyweb/stores.png');
}

#img a {
  position: absolute;
  display: block;
  border: 1px solid red;
}

#img a.etsy {
  top:140px;
  left:100px;
  width:220px;
  height:200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="https://lazycarrot.co.uk/images/lazyweb/stores.png"  border="0" usemap="#storemap" />
<map name="storemap">
    <area shape="rect" coords="96,155,343,326"      href="https://www.etsy.com">
    <area shape="rect" coords="414,155,663,327"     href="https://www.amazon.co.uk">
    <area shape="rect" coords="743,153,986,326"     href="https://www.ebay.co.uk">
</map>

<div id="img">

</div></code>```

Body:
Trying to get an image map to work and can't see where my coding is off!

<map name="storemap">
    <area shape="rect" coords="96,155,343,326"      href="https://www.etsy.com">
    <area shape="rect" coords="414,155,663,327"     href="https://www.amazon.co.uk">
    <area shape="rect" coords="743,153,986,326"     href="https://www.ebay.co.uk">
</map>

I've used Dreamweaver to generate the co-ordinates, and that gives a visible template over the image, so I'm confident that the co-ordinates are ok (famous last words), but the displayed image just doesn't have any clickable links.

Body:
I don't see anything wrong with your code. Some script or CSS rules might be messing with you.

If it doesn't work you can always try positioning links using CSS.
see example below

#img {
  position: relative;
  width: 1124px;
  height: 426px;
  background:url('https://lazycarrot.co.uk/images/lazyweb/stores.png');
}

#img a {
  position: absolute;
  display: block;
  border: 1px solid red;
}

#img a.etsy {
  top:140px;
  left:100px;
  width:220px;
  height:200px;
}

<img src="https://lazycarrot.co.uk/images/lazyweb/stores.png"  border="0" usemap="#storemap" />
<map name="storemap">
    <area shape="rect" coords="96,155,343,326"      href="https://www.etsy.com">
    <area shape="rect" coords="414,155,663,327"     href="https://www.amazon.co.uk">
    <area shape="rect" coords="743,153,986,326"     href="https://www.ebay.co.uk">
</map>

<div id="img">
  <a class="etsy"   href="https://www.etsy.com"></a>
  <a class="amazon" href="https://www.amazon.co.uk"></a>
  <a class="ebay"   href="https://www.ebay.co.uk"></a>
</div>


问:
Traverse from Child Node to Ancestor Node using XPath in Selenium WebDriver
I am trying to traverse to the ancestor node from a child node using xpath, but it does not want to work.

```<code>WebElement menuItemText = driver.findElement(By.xpath("//span[contains( text(), '" + itemTitle + "')]"));
menuItemText = menuItemText.findElement(By.xpath(".//parent::*[@attribute='onclick']"));
menuItemText.click();
</code>```

The nodes is:

        Text!

```

However, the function name is very complex and each node has strange unique IDs. Not that it should matter too much but I want to traverse up the DOM from the child node to the parent / ancestor node that includes an onclick attribute. I want to get the first onclick when traversing up the DOM. So, the onclick=myFunction() is what I want to get.

Is that possible? I tried doing a while() loop and it worked for once but not anymore.

答:
I hope any of the following will solve the issue. ie) it will select the first ancestor div that contains attribute on click.</p>

```<code>1: //span[contains(text(),\"Text\")]/ancestor::div[@onclick][1]
2: (//span[contains(text(),\"Text\")]/ancestor::div[@onclick])[1]
</code>```

Body:
I am trying to traverse to the ancestor node from a child node using xpath, but it does not want to work.

WebElement menuItemText = driver.findElement(By.xpath("//span[contains( text(), '" + itemTitle + "')]"));
menuItemText = menuItemText.findElement(By.xpath(".//parent::*[@attribute='onclick']"));
menuItemText.click();

The nodes is:

        Text!

However, the function name is very complex and each node has strange unique IDs. Not that it should matter too much but I want to traverse up the DOM from the child node to the parent / ancestor node that includes an onclick attribute. I want to get the first onclick when traversing up the DOM. So, the onclick=myFunction() is what I want to get.

Is that possible? I tried doing a while() loop and it worked for once but not anymore.

Body:
I hope any of the following will solve the issue. ie) it will select the first ancestor div that contains attribute on click.

1: //span[contains(text(),\"Text\")]/ancestor::div[@onclick][1]
2: (//span[contains(text(),\"Text\")]/ancestor::div[@onclick])[1]


问:
Flutter cannot install app on iPhone after upgrade to iOS 13.1 and Xcode 11
Today I had this great idea to update my iPhone to iOS 13 and Xcode to version 11... (why not go for a cup f tea instead?!?)

So now I am not anymore able to install my app developed in flutter in my iPhone. Here is the log

```<code>2019-09-27 14:10:46.945 ios-deploy[8xxx2:9xxx95] [ !! ] Error 0xe800007f: Device doesn't support wireless sync. AMDeviceStartService(device, CFSTR("com.apple.debugserver"), &gdbfd, NULL)
Could not install build/ios/iphoneos/Runner.app on f7xxx37xxxxb5299ef.
Try launching Xcode and selecting "Product > Run" to fix the problem:
  open ios/Runner.xcworkspace

Error launching application on xxx's iPhone.
</code>```

If I run the app using Xcode it works fine but flutter does not work

I have seen this page where I think they are talking about the same problem but I am unsure of what I need to do to resolve...

Is there any expert who can suggest what to do ?? Thanks

答:
Use a Non-Personal Team provisioning profile Instead of Personal Team.

Then run on a real iOS device running 13.3 or lower.

Reference: https://github.com/flutter/flutter/issues/48035

Body:
Today I had this great idea to update my iPhone to iOS 13 and Xcode to version 11... (why not go for a cup f tea instead?!?)

So now I am not anymore able to install my app developed in flutter in my iPhone. Here is the log

2019-09-27 14:10:46.945 ios-deploy[8xxx2:9xxx95] [ !! ] Error 0xe800007f: Device doesn't support wireless sync. AMDeviceStartService(device, CFSTR("com.apple.debugserver"), &gdbfd, NULL)
Could not install build/ios/iphoneos/Runner.app on f7xxx37xxxxb5299ef.
Try launching Xcode and selecting "Product > Run" to fix the problem:
  open ios/Runner.xcworkspace

Error launching application on xxx's iPhone.

If I run the app using Xcode it works fine but flutter does not work

I have seen this page where I think they are talking about the same problem but I am unsure of what I need to do to resolve...

Is there any expert who can suggest what to do ?? Thanks


问:
axios duplicates the url in the interceptor
I am using Axios for my HTTP request and this is my first time I got this problem.
the first request is passed and everything is good. but in my second request, I have a problem that Axios is duplicate my URL without reason.

the url that axios is trying to fetch at the end looks like this:

```<code>http://localhost:3001/http://localhost:3001/http://localhost:3001/user/5e4844f6451e0078e7dd398e
</code>```

this is the fetch action:

```<code>export const getUserDetailsById = async ({id}) => {
    return await axios.get(`user/${id}`).then(res => res.data);
};
</code>```

and the interceptor:

```<code>import axios from "axios";

export default () => {
    axios.interceptors.request.use(function (config) {
        const token = localStorage.getItem(process.env.REACT_APP_TOKEN_NAME);
        config.headers.common['authorization'] = `Bearer ${token}`;
        config.headers.common['Content-Type'] = 'application/json';
        config.url = `${process.env.REACT_APP_API_URL}/${config.url}`;

        const url = config.url;
        console.log(url);

        return config;
    },  function (error) {
        return Promise.reject(error);
    });

    axios.interceptors.response.use(function (response) {
        return response;
    }, function (error) {
        return Promise.reject(error);
    });
};
</code>```

答:
You can set baseURL when calling axios.create

```<code>import axios from 'axios';

var api = axios.create({
    baseURL: `${AppConfig.apiUrl}/services`,
});

export default api;
</code>```

then import api when ever you want to use axios.

Body:
I am using Axios for my HTTP request and this is my first time I got this problem.
the first request is passed and everything is good. but in my second request, I have a problem that Axios is duplicate my URL without reason.

the url that axios is trying to fetch at the end looks like this:

http://localhost:3001/http://localhost:3001/http://localhost:3001/user/5e4844f6451e0078e7dd398e

this is the fetch action:

export const getUserDetailsById = async ({id}) => {
    return await axios.get(`user/${id}`).then(res => res.data);
};

and the interceptor:

import axios from "axios";

export default () => {
    axios.interceptors.request.use(function (config) {
        const token = localStorage.getItem(process.env.REACT_APP_TOKEN_NAME);
        config.headers.common['authorization'] = `Bearer ${token}`;
        config.headers.common['Content-Type'] = 'application/json';
        config.url = `${process.env.REACT_APP_API_URL}/${config.url}`;

        const url = config.url;
        console.log(url);

        return config;
    },  function (error) {
        return Promise.reject(error);
    });

    axios.interceptors.response.use(function (response) {
        return response;
    }, function (error) {
        return Promise.reject(error);
    });
};

Body:
You can set baseURL when calling axios.create

import axios from 'axios';

var api = axios.create({
    baseURL: `${AppConfig.apiUrl}/services`,
});

export default api;

then import api when ever you want to use axios.


问:
Implement scraping of page in chunks in Scrapy Python
I am trying to scrape webpage in Scrapy but in chunks. The goal is just to read the title of the page, not the full page.

Ex. If I have a page size 150KB but I just wanted to read the title that must be in the upper part and under 10KB of page size so if I read the first part I am gonna find the title and just cancel the remaining page scraping.

Is it possible to implement something in Scrapy so read the page in chunks?

答:
Scrapy does not currently support stopping the reading of a response before it has finished.

You might want to monitor some of the related existing feature requests:

Provide DownloaderMiddleware an interface to read raw HTTP requests and responses

More possibilities to cancel downloads inside HTTP downloader handler

It may also make sense to create a new feature request that focuses on your scenario, since you want to stop reading a response but still get the data read so far in your callbacks, which I don’t think is covered in existing feature requests.


问:
MSAL Angular - NullInjectorError: No provider for InjectionToken MSAL_CONFIG
I'm trying to dynamically load the MSAL config file but I got an error:

NullInjectorError: No provider for InjectionToken MSAL_CONFIG!

Here is the code:

```<code>import { NgModule, Optional, SkipSelf, APP_INITIALIZER } from "@angular/core";
import { CommonModule } from "@angular/common";
import { HttpClientModule, HTTP_INTERCEPTORS } from "@angular/common/http";
import { MsalModule, MsalInterceptor, MsalConfig, MsalService } from "@azure/msal-angular";
import { ConfigService } from "./config/config.service";
import { MSAL_CONFIG } from "@azure/msal-angular/dist/msal.service";

export function initConfiguration(configService: ConfigService) {
    // This will load the json file and store it in a variable
    return () => configService.init();
}

export function msalConfigFactory(configService: ConfigService): MsalConfig {
    // get the config from the service
    return configService.get();
}

@NgModule({
    imports: [CommonModule, HttpClientModule, MsalModule],
    declarations: [],
    providers: [
        ConfigService,
        {
            provide: APP_INITIALIZER,
            useFactory: initConfiguration,
            deps: [ConfigService],
            multi: true
        },
        {
            provide: MSAL_CONFIG,
            useFactory: msalConfigFactory,
            deps: [ConfigService]
        },
        MsalService,
        {
            provide: HTTP_INTERCEPTORS,
            useClass: MsalInterceptor,
            multi: true
        }
    ]
})
export class CoreModule {
    constructor(
        @Optional()
        @SkipSelf()
        parentModule: CoreModule
    ) {
        if (parentModule) {
            throw new Error("CoreModule is already loaded. Import only in AppModule");
        }
    }
}
</code>```

Since I do provide the MSAL_CONFIG object, I don't understand why it is throwing that error.

I tried to move everything into the app.module but I got the same error. What am I missing here ?

答:
```<code>import { MsalModule } from "@azure/msal-angular";
import { MsalService, MsalConfig } from "@azure/msal-angular";
import { MSAL_CONFIG } from "@azure/msal-angular/dist/msal.service";
import { MsalInterceptor } from "@azure/msal-angular/dist/msal.interceptor";

export function getConfig() {
  var request = new XMLHttpRequest();
  request.open('GET', "/api/settings", false);  // request application settings synchronous
  request.send(null);
  const response = JSON.parse(request.responseText);
  return response as MsalConfig;
}

@NgModule({
 imports: [
MsalModule
],
 providers: [
    MsalService,
    {
      provide: MSAL_CONFIG,
      useValue: getConfig()
    },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: MsalInterceptor,
      multi: true
    },
] ,
bootstrap: [AppComponent]
})
</code>```

give it a try if you haven't found a solution =)

Body:
I'm trying to dynamically load the MSAL config file but I got an error:

NullInjectorError: No provider for InjectionToken MSAL_CONFIG!

Here is the code:

import { NgModule, Optional, SkipSelf, APP_INITIALIZER } from "@angular/core";
import { CommonModule } from "@angular/common";
import { HttpClientModule, HTTP_INTERCEPTORS } from "@angular/common/http";
import { MsalModule, MsalInterceptor, MsalConfig, MsalService } from "@azure/msal-angular";
import { ConfigService } from "./config/config.service";
import { MSAL_CONFIG } from "@azure/msal-angular/dist/msal.service";

export function initConfiguration(configService: ConfigService) {
    // This will load the json file and store it in a variable
    return () => configService.init();
}

export function msalConfigFactory(configService: ConfigService): MsalConfig {
    // get the config from the service
    return configService.get();
}

@NgModule({
    imports: [CommonModule, HttpClientModule, MsalModule],
    declarations: [],
    providers: [
        ConfigService,
        {
            provide: APP_INITIALIZER,
            useFactory: initConfiguration,
            deps: [ConfigService],
            multi: true
        },
        {
            provide: MSAL_CONFIG,
            useFactory: msalConfigFactory,
            deps: [ConfigService]
        },
        MsalService,
        {
            provide: HTTP_INTERCEPTORS,
            useClass: MsalInterceptor,
            multi: true
        }
    ]
})
export class CoreModule {
    constructor(
        @Optional()
        @SkipSelf()
        parentModule: CoreModule
    ) {
        if (parentModule) {
            throw new Error("CoreModule is already loaded. Import only in AppModule");
        }
    }
}

Since I do provide the MSAL_CONFIG object, I don't understand why it is throwing that error.

I tried to move everything into the app.module but I got the same error. What am I missing here ?

Body:
import { MsalModule } from "@azure/msal-angular";
import { MsalService, MsalConfig } from "@azure/msal-angular";
import { MSAL_CONFIG } from "@azure/msal-angular/dist/msal.service";
import { MsalInterceptor } from "@azure/msal-angular/dist/msal.interceptor";

export function getConfig() {
  var request = new XMLHttpRequest();
  request.open('GET', "/api/settings", false);  // request application settings synchronous
  request.send(null);
  const response = JSON.parse(request.responseText);
  return response as MsalConfig;
}

@NgModule({
 imports: [
MsalModule
],
 providers: [
    MsalService,
    {
      provide: MSAL_CONFIG,
      useValue: getConfig()
    },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: MsalInterceptor,
      multi: true
    },
] ,
bootstrap: [AppComponent]
})

give it a try if you haven't found a solution =)


问:
Remeshing of a triangular mesh for making high quality Delaunay triangulation?
I have a triangular mesh of the brain surface. I want to remesh it to a high-quality Delaunay triangulation. I'm seeking an easy and straightforward method. </p>

答:
You mean that you want to resample the mesh? I've had some success using the trimesh package: https://github.com/mikedh/trimesh

Check out trimesh.remesh in particular.


问:
How to enter the text in search bar using UIAutomation?
Could you please help me out in entering the text in search bar using UIAutomation scripts for IPhone Application.

Thanks in advance,
Madhu.

答:
Since through tap input method you communicate with the device, you can try user-like type of action: tapping.

To bring up the keyboard you just tap on the text input field:

```<code>someTextInputField.tap();
</code>```

But be aware of the fact that there is no keyboard object instance available for actions if you do not activate the keyboard itself by tapping on any text input field.

Once the keyboard is activated:

```<code>var App = UIATarget.localTarget().frontMostApp();
var Keyboard = App.keyboard();
var Keys = Keyboard.keys();
var AltKeys = Keyboard.buttons();
</code>```

Where AltKeys represent service buttons like Shift, Done, etc.
And Keys represent all other buttons.

P.S. Keep in mind that you have to switch between keyboard tabs to get access to either characters, numbers, special characters.

ContentLicense: CC BY-SA 3.0

Body:
Since through tap input method you communicate with the device, you can try user-like type of action: tapping.

To bring up the keyboard you just tap on the text input field:

someTextInputField.tap();

But be aware of the fact that there is no keyboard object instance available for actions if you do not activate the keyboard itself by tapping on any text input field.

Once the keyboard is activated:

var App = UIATarget.localTarget().frontMostApp();
var Keyboard = App.keyboard();
var Keys = Keyboard.keys();
var AltKeys = Keyboard.buttons();

Where AltKeys represent service buttons like Shift, Done, etc.
And Keys represent all other buttons.

P.S. Keep in mind that you have to switch between keyboard tabs to get access to either characters, numbers, special characters.


问:
Is it possible to use session from kernel console command in laravel?
I'm trying to fetch data from sessions when I run a command in my console, but session always returns an empty array!

```<code>php artisan command:mycommand
</code>```

Below is how I'm trying to get the session:

```<code>//returns empty array
$session = session()->all();
</code>```

Any ideas?

答: Session are used in the context of HTTP protocol. There is no such session using CLI. However, if your php artisan command is triggered in the context of an HTTP request, you could pass data to your command using arguments.</p>

Body:
I'm trying to fetch data from sessions when I run a command in my console, but session always returns an empty array!

php artisan command:mycommand

Below is how I'm trying to get the session:

//returns empty array
$session = session()->all();

Any ideas?


问:
Getters and setters in parent class
I have a quick question on best practice and if getters and setters are the best option in a specific case.  The case is when I have class 'A' instantiating classes 'B' and 'C'.  Class A contains public getters and setters for classes B and C to access so data is centralised.

Is this best practice or would it be best to pass the data to classes B and C through parameters?

Thanks

Chris

答:
The short answer: it depends

The long one: if you B and C classes encapsulate data and/or functionality that might be useful outside of the class A and A is "only" client of B and C, let them be instantiable independent of A and set into A with setters like setA/setB. This way other classes can possible use B and C for whatever reason. You could also take advantage of inheritance where instances with enhanced functionality get induced into class A during runtime (for example through Inversion of Control frameworks like JohnReeeves stated).

If they only make sense in the context of class A, encapsulate functionality that only A directly uses, hide them from the outside world and parametrize by means of class A methods/properties. This gives you the freedom to change implementation of B and C so that no code outside get upset. A is a public interface so to say, B and C are internal implementation.

And generally the more you can hide from your implementation the better, let the outside world know only as little as it neccessarily needs to know to function properly.

So think about the extact goal of A, B and C, their relationship to each other and to the outside world and make you decision.

Title: Getters and setters in parent class


问:
keras save the model weights to one file
i have a keras model which save weights of each epoch how can i make to one file

this is the line which saves the mode

and i have 50 epoch i will get 50 weights which i want only 1 save all of them inside one file

```<code>>     model.save_weights('checkpoint_epoch_{}.hdf5'.format(k))
</code>```

any idea what shall i do to save it in one file because i have to convert weights later to tensorflow model

desiered weights

```<code>checkpoint.h5
</code>```

答:
You don't need the weights in one file, you can save the whole model and use the TFLiteConverter to convert your tf.keras model or tf model to lite directly from a .h5 file.

```<code> import tensorflow as tf
 from tf.keras.models import load_model

 model=load_model("model.h5")

 # Convert the model.
 converter = tf.lite.TFLiteConverter.from_keras_model(model)
 tflite_model = converter.convert()
</code>```

If you have a Keras model built, you can save the model at each epoch while training using a callback called ModelCheckpoint.

A callback is a set of functions to be applied at given stages of the training procedure. You can use callbacks to get a view on internal states and statistics of the model during training. You can pass a list of callbacks (as the keyword argument callbacks) to the .fit() method of the Sequential or Model classes. The relevant methods of the callbacks will then be called at each stage of the training.

```<code>from keras.callbacks import ModelCheckpoint

'''
saves the model weights after each epoch
'''
checkpointer = ModelCheckpoint(filepath='model-{epoch:02d}-{val_loss:.2f}.h5', verbose=1)
model.fit(x_train, y_train, batch_size=batchsize, epochs=epochs, verbose=0, validation_data=(X_test, Y_test), callbacks=[checkpointer])
</code>```

Then the model will be saved with the epoch number and the validation loss in the filename

SO you can save a model and then later load it as described above.

Body:
i have a keras model which save weights of each epoch how can i make to one file

this is the line which saves the mode

and i have 50 epoch i will get 50 weights which i want only 1 save all of them inside one file

>     model.save_weights('checkpoint_epoch_{}.hdf5'.format(k))

any idea what shall i do to save it in one file because i have to convert weights later to tensorflow model

desiered weights

checkpoint.h5

Body:
You don't need the weights in one file, you can save the whole model and use the TFLiteConverter to convert your tf.keras model or tf model to lite directly from a .h5 file.

 import tensorflow as tf
 from tf.keras.models import load_model

 model=load_model("model.h5")

 # Convert the model.
 converter = tf.lite.TFLiteConverter.from_keras_model(model)
 tflite_model = converter.convert()

If you have a Keras model built, you can save the model at each epoch while training using a callback called ModelCheckpoint.

A callback is a set of functions to be applied at given stages of the training procedure. You can use callbacks to get a view on internal states and statistics of the model during training. You can pass a list of callbacks (as the keyword argument callbacks) to the .fit() method of the Sequential or Model classes. The relevant methods of the callbacks will then be called at each stage of the training.

from keras.callbacks import ModelCheckpoint

'''
saves the model weights after each epoch
'''
checkpointer = ModelCheckpoint(filepath='model-{epoch:02d}-{val_loss:.2f}.h5', verbose=1)
model.fit(x_train, y_train, batch_size=batchsize, epochs=epochs, verbose=0, validation_data=(X_test, Y_test), callbacks=[checkpointer])

Then the model will be saved with the epoch number and the validation loss in the filename

SO you can save a model and then later load it as described above.


问:
Authentication is null on the SecurityContextHolder.getContext();
I am trying to add Facebook authorization using Spring Security in Spring Boot app. Currently, my problem is extracting data from Principal.

Here is my security config:

```<code>public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure (HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .antMatcher("/**")
            .authorizeRequests()
                .antMatchers("/", "/login**").permitAll()
                .anyRequest().authenticated()
                .and()
            .logout()
                .deleteCookies("JSESSIONID")
                .clearAuthentication(true)
                .logoutSuccessUrl("/").permitAll();
    }

    @Bean
    public PrincipalExtractor facebookPrincipalExtractor(){
        return new FacebookPrincipalExtractor();
    }
}
</code>```

and principal extractor:

```<code>public class FacebookPrincipalExtractor implements PrincipalExtractor {

    @Autowired
    UserService userService;

    @Override
    public Object extractPrincipal(Map<String, Object> map) {
        String name = (String) map.get("name");
        String id = (String) map.get("id");
        User user = userService.findOne(id);
        if (user == null) {
            SecurityContext securityContext = SecurityContextHolder.getContext();
            Authentication authentication = securityContext.getAuthentication();
            String token = ((OAuth2AuthenticationDetails) authentication.getDetails()).getTokenValue();
            user = new User();

            FacebookClient facebookClient = new DefaultFacebookClient(token, Version.VERSION_2_10);

            JSONObject object = facebookClient.fetchObject("me", JSONObject.class);
//           userService.createUser(object);
        }
        return user;
    }
}
</code>```

After login, the Map<String, Object> map contains only the name and id. Call to securityContext.getAuthentication() returns null.

Moreover, if I create something similar to the endpoint and pass the Principal there as a parameter, then this will work. Example:

```<code>@RequestMapping("/user")
public Principal user(Principal principal) {
    return principal;
}
</code>```

The principal will contain all the necessary data.

In this regard, 2 questions:

Why security context does not contain authentication?

Where does the principal come from if it is passed as a parameter to a method?

This is what the debug looks like inside

答:
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
authentication.getPrincipal();

use nested call for getting authentication object and then getPrincipal(); will return current loggedin user details

Body:
I am trying to add Facebook authorization using Spring Security in Spring Boot app. Currently, my problem is extracting data from Principal.

Here is my security config:

public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure (HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .antMatcher("/**")
            .authorizeRequests()
                .antMatchers("/", "/login**").permitAll()
                .anyRequest().authenticated()
                .and()
            .logout()
                .deleteCookies("JSESSIONID")
                .clearAuthentication(true)
                .logoutSuccessUrl("/").permitAll();
    }

    @Bean
    public PrincipalExtractor facebookPrincipalExtractor(){
        return new FacebookPrincipalExtractor();
    }
}

and principal extractor:

public class FacebookPrincipalExtractor implements PrincipalExtractor {

    @Autowired
    UserService userService;

    @Override
    public Object extractPrincipal(Map<String, Object> map) {
        String name = (String) map.get("name");
        String id = (String) map.get("id");
        User user = userService.findOne(id);
        if (user == null) {
            SecurityContext securityContext = SecurityContextHolder.getContext();
            Authentication authentication = securityContext.getAuthentication();
            String token = ((OAuth2AuthenticationDetails) authentication.getDetails()).getTokenValue();
            user = new User();

            FacebookClient facebookClient = new DefaultFacebookClient(token, Version.VERSION_2_10);

            JSONObject object = facebookClient.fetchObject("me", JSONObject.class);
//           userService.createUser(object);
        }
        return user;
    }
}

After login, the Map<String, Object> map contains only the name and id. Call to securityContext.getAuthentication() returns null.

Moreover, if I create something similar to the endpoint and pass the Principal there as a parameter, then this will work. Example:

@RequestMapping("/user")
public Principal user(Principal principal) {
    return principal;
}

The principal will contain all the necessary data.

In this regard, 2 questions:

Why security context does not contain authentication?

Where does the principal come from if it is passed as a parameter to a method?

This is what the debug looks like inside


问:
What is the best way to put xml inside json?
Would you use...

Option 1)

Create object with field which contains xml.
Transform object to json using json library and let the library do the escaping.

Option 2)

Base64 encode xml and put base64 encoded string inside json.

Option 3)

Something else?

答:
Create object with field which contains xml. Transform object to json using json library and let the library do the escaping.

Yes. That is how you create JSON. (The other approach is to mash strings together, which is error prone).

Base64 encode xml and put base64 encoded string inside json.

No. XML is just text. There is no point in Base64 encoding it.


问:
how to append a tag inside an html using java
I have an HTML

```<code><h1><a>Hello I am html</a></h1>
</code>```

what I want to achieve -

```<code><h1><a>Hello I am <strong>html</strong></a></h1>
</code>```

my code:-

```<code>Document document = Jsoup.parse(HTML);

Element element = getElementUsingXpath(); // this is working fine

String originalText = element.text();

String changedText = originalText.substring(0, 6 + 1)
                    + "<strong>"
                    + originalText.substring(6 + 1) +"</strong>";

element.text(changedText)
</code>```

But I am getting this

```<code>Hello I am <strong>html</strong> //this is wrong
</code>```

I was expecting it to be

Hello I am html

答:
the problem got solved with the below code... suggested by @OHGODSPIDERS

```<code>Document document = Jsoup.parse(HTML);

Element element = getElementUsingXpath(); // this is working fine

String originalText = element.text();

String changedText = originalText.substring(0, 6 + 1)
                    + "<strong>"
                    + originalText.substring(6 + 1) +"</strong>";

</code>```

element.html(changedText)

Body:
I have an HTML

Hello I am html

what I want to achieve -

Hello I am html

my code:-

Document document = Jsoup.parse(HTML);

Element element = getElementUsingXpath(); // this is working fine

String originalText = element.text();

String changedText = originalText.substring(0, 6 + 1)
                    + ""
                    + originalText.substring(6 + 1) +"";

element.text(changedText)

But I am getting this

Hello I am html //this is wrong

I was expecting it to be

Hello I am html

Body:
the problem got solved with the below code... suggested by @OHGODSPIDERS

Document document = Jsoup.parse(HTML);

Element element = getElementUsingXpath(); // this is working fine

String originalText = element.text();

String changedText = originalText.substring(0, 6 + 1)
                    + "<strong>"
                    + originalText.substring(6 + 1) +"</strong>";

element.html(changedText)


问:
How to limit draggable scrollable sheet to take height according to its child height in flutter?
I am using draggableScrollableSheet. I am giving these parameters

```<code>DraggableScrollableSheet(initialChildSize: 0.4,maxChildSize: 1,minChildSize: 0.4,builder: (BuildContext context, ScrollController scrollController) {
            return SingleChildScrollView(controller: scrollController,
              child: Theme(
                data: Theme.of(context).copyWith(canvasColor: Colors.transparent),
                child: Opacity(
                  opacity: 1,
                  child: IntrinsicHeight(
                      child: Column(mainAxisSize: MainAxisSize.min,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: <Widget>[
                          SizedBox(height: 10,),
                          Container(
                            margin: EdgeInsets.only(right: 300),
                            decoration: BoxDecoration(
                              border: Border(
                                top: BorderSide(
                                    color: Colors.blue,
                                    width: 3,
                                    style: BorderStyle.solid),
                              ),
                            ),
                          ),
                          Card(
                            child: Row(
                              children: <Widget>[
                                Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: Column(
                                    crossAxisAlignment:
                                    CrossAxisAlignment.start,
                                    children: <Widget>[
                                      Text(
                                        S
                                            .of(context)
                                            .we_have_found_you_a_driver,
                                        style: TextStyle(
                                            color: Colors.black,
                                            fontWeight: FontWeight.bold),
                                      ),
                                      SizedBox(
                                        height: 10,
                                      ),
                                      Text(S
                                          .of(context)
                                          .driver_is_heading_towards +
                                          ' ${widget.order.foodOrders.first.food.restaurant.name}')
                                    ],
                                  ),
                                ),
                              ],
                            ),
                            elevation: 5,
                          ),
                          SizedBox(height: 10,),
                          Card(
                            elevation: 5,
                            child: Row(
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: <Widget>[
                                  CircleAvatar(
                                    radius: 50.0,
                                    backgroundColor: Colors.white,
                                    child:
                                    Image.asset(
                                        'assets/img/image_not_available.jpg'),
                                  ),
                                  Expanded(
                                    child: Column(mainAxisAlignment: MainAxisAlignment.start,
                                      children: <Widget>[
                                        Row(mainAxisAlignment: MainAxisAlignment.spaceAround,
                                          children: <Widget>[
                                            Expanded(
                                              child: Text('Test',
                                                  textAlign: TextAlign.start,
                                                  style: new TextStyle(
                                                    color: Colors.black,
                                                    fontSize: 16.0,
                                                  )),
                                            ),
                                            Icon(Icons.star, color: Colors.yellow.shade700,)
                                          ],
                                        ),
                                        SizedBox(height: 30,),
                                        Row(mainAxisAlignment: MainAxisAlignment.spaceAround,
                                          children: <Widget>[
                                            Expanded(
                                              child: Container(
                                                child: Text('Mobile number',
                                                    textAlign: TextAlign.start,
                                                    style: new TextStyle(
                                                      color: Colors.black,
                                                      fontSize: 16.0,
                                                    )),
                                              ),
                                            ),
                                            Icon(Icons.phone,),
                                            SizedBox(width: 10,),
                                            Icon(Icons.message),
                                          ],
                                        ),

                                      ],
                                    ),
                                  )
                                ]),
                          ),
                          SizedBox(height: 10,),
                          Card(
                            child: Align( alignment: Alignment(-1,1),
                              child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: <Widget>[
                                  Padding(
                                    padding: const EdgeInsets.all(8.0),
                                    child: Column(
                                      crossAxisAlignment:
                                      CrossAxisAlignment.start,
                                      children: <Widget>[
                                        Text(
                                          S
                                              .of(context)
                                              .you_ordered_from + ' ${widget.order.foodOrders.first.food.restaurant.name}',
                                          style: TextStyle(
                                            color: Colors.grey,
                                          ),
                                        ),
                                        SizedBox(
                                          height: 5,
                                        ),
                                        Column(children: List.generate(widget.order.foodOrders.length,(index) {
                                          return Text(
                                              '${widget.order.foodOrders[index].food.name}'
                                          );
                                        },),),
                                        Row(
                                          children: <Widget>[
                                            Column(crossAxisAlignment: CrossAxisAlignment.start,
                                              children: <Widget>[
                                                Text('See details', style: TextStyle(fontWeight: FontWeight.bold,color: Colors.blue),),

                                              ],
                                            ),

                                          ],
                                        ),

                                      ],
                                    ),
                                  ),
                                  Padding(
                                    padding: const EdgeInsets.all(8.0),
                                    child: Column(
                                      children: <Widget>[
                                        SizedBox(height: 40,),
                                        Row(
                                          children: <Widget>[
                                            Icon(Icons.monetization_on),
                                            Text(widget.order.foodOrders
                                                .first.price
                                                .toString()),
                                          ],
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            elevation: 5,
                          ),
                        ],
                      ),
                  ),
                ),
              ),
            )
</code>```

and I also used a single child scroll view and column so that I can show my cards in that column of draggableScrollableSheet. But I want draggableScrollableSheet to take height dynamically instead of defining size. Like now I want to show only 2 to 3 cards and that is taking full screen. But I want it to take the minimum height of the screen. How can we achieve this?

答:
the initialChildSize is the height of your ScrollView before its actually scrolled, so that means you can actually decide what it would look like.
here is an example![the draggable scrollsheet here has                     initialChildSize: 0.1,maxChildSize: 1,minChildSize: 0.1,
]1

Body:
I am using draggableScrollableSheet. I am giving these parameters

DraggableScrollableSheet(initialChildSize: 0.4,maxChildSize: 1,minChildSize: 0.4,builder: (BuildContext context, ScrollController scrollController) {
            return SingleChildScrollView(controller: scrollController,
              child: Theme(
                data: Theme.of(context).copyWith(canvasColor: Colors.transparent),
                child: Opacity(
                  opacity: 1,
                  child: IntrinsicHeight(
                      child: Column(mainAxisSize: MainAxisSize.min,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: <Widget>[
                          SizedBox(height: 10,),
                          Container(
                            margin: EdgeInsets.only(right: 300),
                            decoration: BoxDecoration(
                              border: Border(
                                top: BorderSide(
                                    color: Colors.blue,
                                    width: 3,
                                    style: BorderStyle.solid),
                              ),
                            ),
                          ),
                          Card(
                            child: Row(
                              children: <Widget>[
                                Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: Column(
                                    crossAxisAlignment:
                                    CrossAxisAlignment.start,
                                    children: <Widget>[
                                      Text(
                                        S
                                            .of(context)
                                            .we_have_found_you_a_driver,
                                        style: TextStyle(
                                            color: Colors.black,
                                            fontWeight: FontWeight.bold),
                                      ),
                                      SizedBox(
                                        height: 10,
                                      ),
                                      Text(S
                                          .of(context)
                                          .driver_is_heading_towards +
                                          ' ${widget.order.foodOrders.first.food.restaurant.name}')
                                    ],
                                  ),
                                ),
                              ],
                            ),
                            elevation: 5,
                          ),
                          SizedBox(height: 10,),
                          Card(
                            elevation: 5,
                            child: Row(
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: <Widget>[
                                  CircleAvatar(
                                    radius: 50.0,
                                    backgroundColor: Colors.white,
                                    child:
                                    Image.asset(
                                        'assets/img/image_not_available.jpg'),
                                  ),
                                  Expanded(
                                    child: Column(mainAxisAlignment: MainAxisAlignment.start,
                                      children: <Widget>[
                                        Row(mainAxisAlignment: MainAxisAlignment.spaceAround,
                                          children: <Widget>[
                                            Expanded(
                                              child: Text('Test',
                                                  textAlign: TextAlign.start,
                                                  style: new TextStyle(
                                                    color: Colors.black,
                                                    fontSize: 16.0,
                                                  )),
                                            ),
                                            Icon(Icons.star, color: Colors.yellow.shade700,)
                                          ],
                                        ),
                                        SizedBox(height: 30,),
                                        Row(mainAxisAlignment: MainAxisAlignment.spaceAround,
                                          children: <Widget>[
                                            Expanded(
                                              child: Container(
                                                child: Text('Mobile number',
                                                    textAlign: TextAlign.start,
                                                    style: new TextStyle(
                                                      color: Colors.black,
                                                      fontSize: 16.0,
                                                    )),
                                              ),
                                            ),
                                            Icon(Icons.phone,),
                                            SizedBox(width: 10,),
                                            Icon(Icons.message),
                                          ],
                                        ),

                                      ],
                                    ),
                                  )
                                ]),
                          ),
                          SizedBox(height: 10,),
                          Card(
                            child: Align( alignment: Alignment(-1,1),
                              child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: <Widget>[
                                  Padding(
                                    padding: const EdgeInsets.all(8.0),
                                    child: Column(
                                      crossAxisAlignment:
                                      CrossAxisAlignment.start,
                                      children: <Widget>[
                                        Text(
                                          S
                                              .of(context)
                                              .you_ordered_from + ' ${widget.order.foodOrders.first.food.restaurant.name}',
                                          style: TextStyle(
                                            color: Colors.grey,
                                          ),
                                        ),
                                        SizedBox(
                                          height: 5,
                                        ),
                                        Column(children: List.generate(widget.order.foodOrders.length,(index) {
                                          return Text(
                                              '${widget.order.foodOrders[index].food.name}'
                                          );
                                        },),),
                                        Row(
                                          children: <Widget>[
                                            Column(crossAxisAlignment: CrossAxisAlignment.start,
                                              children: <Widget>[
                                                Text('See details', style: TextStyle(fontWeight: FontWeight.bold,color: Colors.blue),),

                                              ],
                                            ),

                                          ],
                                        ),

                                      ],
                                    ),
                                  ),
                                  Padding(
                                    padding: const EdgeInsets.all(8.0),
                                    child: Column(
                                      children: <Widget>[
                                        SizedBox(height: 40,),
                                        Row(
                                          children: <Widget>[
                                            Icon(Icons.monetization_on),
                                            Text(widget.order.foodOrders
                                                .first.price
                                                .toString()),
                                          ],
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            elevation: 5,
                          ),
                        ],
                      ),
                  ),
                ),
              ),
            )

and I also used a single child scroll view and column so that I can show my cards in that column of draggableScrollableSheet. But I want draggableScrollableSheet to take height dynamically instead of defining size. Like now I want to show only 2 to 3 cards and that is taking full screen. But I want it to take the minimum height of the screen. How can we achieve this?


问:
Is there a Javascript support library for html5 file API and upload?
until now I was using flash based swfupload and its swfupload.js which provides users with callbacks from flash and a possibility to set it up.

I was wondering if there is anything like this for HTML5 File API. I'm asking before I make it from scratch myself. I don't want to reinvent a wheel when there might be a good library out there already.

答:
And another one ;-)

http://code.google.com/p/html5uploader/


问:
What is the best practice to save a quiz answers with different data types in MYSQL?
UPDATE: part 1- start:

We want to get our customers data, but which kind of data? they are not specified! actually we want to have a dynamic application that the admin can define new questions (he can set the answer's data type, length, and other rules) and he also can deactivate old questions!

(I don't want to use EAV schema design, but I can't find the alternative way)

UPDATE: part 1 - end:

so I decided to create a quiz application, admin can define questions which their answers data type can be different!

Example:

question ID 1 : what is you name?  answer: John (varchar)

question ID 2 : how old are you? answer: 25 (integer)

question ID 3 : how much is your salary per hour? answer: 30.65 (decimal)

question ID 4 : describe yourself? answer: I'm so kind ... (text)

UPDATE: part 2 - start:

to save the answers it comes to my mind 3 choices:

UPDATE: part 2 - end:

create a table like this (EAV schema design):

```<code>    Table profile_answers
    id int [pk, increment]
    question_id int
    profile_id int
    answer text
</code>```

as you see I've save all answers as text!
I know that it works, but is it the best way? actually this app is going to have millions of answers and we want to analyze the answers by machine (for example: getting customers average age, getting married customers, customers with salary > 30.52 and etc) so I want to implement the way with the best performance!

create a table like this (EAV schema design):

```<code>Table answers
id int [pk, increment]
question_id int
profile_id int
integer_value int
decimal_value decimal
varchar_value varchar
boolean_value boolean
longtext_value longtext
</code>```

now I can save data in the proper field and put NULL in the other fields (the answer's data type will be determined while defining it's question)

For example:

```<code>question ID 1 : what is you name? answer: John (varchar)

id 1
profile_question_id 1
profile_id 1
integer_value NULL
decimal_value NULL
varchar_value John
boolean_value NULL
longtext_value NULL

 ----------------
question ID 2 : how old are you? answer: 25 (integer)

id 2
profile_question_id 2
profile_id 1
integer_value 25
decimal_value NULL
varchar_value NULL
boolean_value NULL
longtext_value NULL

 ----------------
question ID 3 : how much is your salary per hour? answer: 30.65 (decimal)

id 3
profile_question_id 3
profile_id 1
integer_value NULL
decimal_value 30.65
varchar_value NULL
boolean_value NULL
longtext_value NULL

</code>```

UPDATE: part 3 - start:

when admin adds a new question, I can add a column to answers table (change table's schema) like this

UPDATE: part 3 - end:

It's all about performance! what's the best way?
If none of them is not the best one and I should redesign the database what is the correct database design?

答:
According to the official MySQL documentation about String Type Storage Requirements a TEXT data type requires L + 2 bytes, where L is the length of the string. So, if the answer given is the numeric value 100 it will use 5 bytes.

Whereas, according to the docs entry about Numeric Type Storage Requirements the same numeric value (100) would only take a single byte when using the TINYINT datatype (max 255) or 2 bytes when using SMALLINT type (max 65535)

So, if you are storing a large number of rows in your table, the storage can be upto 5 times greater for values less than 256 when saved as TEXT.

For higher values the storage different becomes much greater:

60000 as TEXT = 7 bytes
60000 as SMALLINT = 2 bytes

I would recommend that you restructure your data model so that the data is stored with the correct type. This will also ensure indexing is more performant, String/Numeric functions work correctly and App level abstraction layer components such as Doctrine, will map to the correct language type in PHP, etc.

Here is a good article about optimizing MySQL data model design.

Body:
UPDATE: part 1- start:

We want to get our customers data, but which kind of data? they are not specified! actually we want to have a dynamic application that the admin can define new questions (he can set the answer's data type, length, and other rules) and he also can deactivate old questions!

(I don't want to use EAV schema design, but I can't find the alternative way)

UPDATE: part 1 - end:

so I decided to create a quiz application, admin can define questions which their answers data type can be different!

Example:

question ID 1 : what is you name?  answer: John (varchar)

question ID 2 : how old are you? answer: 25 (integer)

question ID 3 : how much is your salary per hour? answer: 30.65 (decimal)

question ID 4 : describe yourself? answer: I'm so kind ... (text)

UPDATE: part 2 - start:

to save the answers it comes to my mind 3 choices:

UPDATE: part 2 - end:

create a table like this (EAV schema design):

    Table profile_answers
    id int [pk, increment]
    question_id int
    profile_id int
    answer text

as you see I've save all answers as text!
I know that it works, but is it the best way? actually this app is going to have millions of answers and we want to analyze the answers by machine (for example: getting customers average age, getting married customers, customers with salary > 30.52 and etc) so I want to implement the way with the best performance!

create a table like this (EAV schema design):

Table answers
id int [pk, increment]
question_id int
profile_id int
integer_value int
decimal_value decimal
varchar_value varchar
boolean_value boolean
longtext_value longtext

now I can save data in the proper field and put NULL in the other fields (the answer's data type will be determined while defining it's question)

For example:

question ID 1 : what is you name? answer: John (varchar)

id 1
profile_question_id 1
profile_id 1
integer_value NULL
decimal_value NULL
varchar_value John
boolean_value NULL
longtext_value NULL

 ----------------
question ID 2 : how old are you? answer: 25 (integer)

id 2
profile_question_id 2
profile_id 1
integer_value 25
decimal_value NULL
varchar_value NULL
boolean_value NULL
longtext_value NULL

 ----------------
question ID 3 : how much is your salary per hour? answer: 30.65 (decimal)

id 3
profile_question_id 3
profile_id 1
integer_value NULL
decimal_value 30.65
varchar_value NULL
boolean_value NULL
longtext_value NULL

UPDATE: part 3 - start:

when admin adds a new question, I can add a column to answers table (change table's schema) like this

UPDATE: part 3 - end:

It's all about performance! what's the best way?
If none of them is not the best one and I should redesign the database what is the correct database design?


问:
In C, why swapping x with y is faster then swapping y with x?
In a problem minimum-swaps-2 ,  arr is unsorted array, arr_count is number of array elements, we need to return minimum number of swaps to sort the array,

i tried:

```<code>int minimumSwaps(int arr_count, int* arr) {
    int swap = 0;
    for(int i  = 0; i < arr_count;){
        if(arr[i] != (i + 1)){
            int temp = arr[i];
            arr[i] = arr[arr[i] - 1];
            arr[arr[i] - 1] = temp;
            swap++;
        } else {
            i++;
        }
    }
    return swap;
}
</code>```

but it didn't work. It shows time out error. i.e. it took more time to run!
Then i tried the below code, it worked!

```<code>        int temp = arr[arr[i] - 1];
        arr[arr[i] - 1] = arr[i];
        arr[i] = temp;
        swap++;
</code>```

The only difference between both is swapping x with y or y with x. What difference does it make?

答:
After arr[i] = arr[arr[i] - 1]; the value arr[i] was changed and  arr[arr[i] - 1] doesn't point at same storage anymore, arr[arr[i] - 1] = temp; writes to wrong storage.

So you actually do not swap two values. It could be obvious if you represented it as pointer arithmetic.

```<code>        int temp = *(arr + i);
        *(arr + i) = *(arr + temp - 1);
        *(arr + *(arr + i) - 1) = temp;
</code>```

Last line equals to  *(arr + *(arr + temp - 1) - 1) with values present at moment before line 2 execution, which IS wrong by definition of task.

In fact it gives obvious solution:

```<code>        int temp = *(arr + i);
        *(arr + i) = *(arr + temp - 1);
        *(arr + temp - 1) = temp;
</code>```

or

```<code>        int temp = arr[i];
        arr[i] = arr[temp - 1];
        arr[temp - 1] = temp;
</code>```

Which yields result of 5 returned from minimumSwaps.

Essentially you time-outed because first variant unable to reach solution.

Body:
In a problem minimum-swaps-2 ,  arr is unsorted array, arr_count is number of array elements, we need to return minimum number of swaps to sort the array,

i tried:

int minimumSwaps(int arr_count, int* arr) {
    int swap = 0;
    for(int i  = 0; i < arr_count;){
        if(arr[i] != (i + 1)){
            int temp = arr[i];
            arr[i] = arr[arr[i] - 1];
            arr[arr[i] - 1] = temp;
            swap++;
        } else {
            i++;
        }
    }
    return swap;
}

but it didn't work. It shows time out error. i.e. it took more time to run!
Then i tried the below code, it worked!

        int temp = arr[arr[i] - 1];
        arr[arr[i] - 1] = arr[i];
        arr[i] = temp;
        swap++;

The only difference between both is swapping x with y or y with x. What difference does it make?

Body:
After arr[i] = arr[arr[i] - 1]; the value arr[i] was changed and  arr[arr[i] - 1] doesn't point at same storage anymore, arr[arr[i] - 1] = temp; writes to wrong storage.

So you actually do not swap two values. It could be obvious if you represented it as pointer arithmetic.

        int temp = *(arr + i);
        *(arr + i) = *(arr + temp - 1);
        *(arr + *(arr + i) - 1) = temp;

Last line equals to  *(arr + *(arr + temp - 1) - 1) with values present at moment before line 2 execution, which IS wrong by definition of task.

In fact it gives obvious solution:

        int temp = *(arr + i);
        *(arr + i) = *(arr + temp - 1);
        *(arr + temp - 1) = temp;

or

        int temp = arr[i];
        arr[i] = arr[temp - 1];
        arr[temp - 1] = temp;

Which yields result of 5 returned from minimumSwaps.

Essentially you time-outed because first variant unable to reach solution.


问:
How can I create an observable like the one returned by defer using Observable.create?
I'm trying to create an observable with behavior similar to what is returned by defer, but using create method. So I try:

```<code>const obs = Observable.create(function(observer) {
   from(fetch('https://jsonplaceholder.typicode.com/todos/1').then(console.log('fetch done'))).subscribe(observer)
})

setTimeout(()=>obs.subscribe((resp)=>console.log(resp.statusText)), 5000)
</code>```

But when I run it in node It just prints "fetch done" (on subscription, after 5 seconds as expected) but waits forever there.

When I wrap the from(..) in setImmediate() or setTimeout(,0), then sometimes it prints both messages ("Fetch done", "OK") and exits and sometimes it only prints "fetch done" and waits forever.

code:

```<code>const obs = Observable.create(function(observer) {
    setTimeout(()=>from(fetch('https://jsonplaceholder.typicode.com/todos/1').then(console.log('fetch done'))).subscribe(observer), 0)
})

setTimeout(()=>obs.subscribe((resp)=>console.log(resp.statusText)), 5000)
</code>```

Why this happens? What am I doing wrong?

答:
First thing is that Observable.create is deprecated and you should use just new Observable():

When creating Observables like this you have access to observer object where you can call next() and complete() so in your case it would be like this:

```<code>new Observable(observer => {
  fetch('https://jsonplaceholder.typicode.com/todos/1').then(response => {
    observer.next(response);
    observer.complete();
  });
});
</code>```

I think this should work as well:

```<code>new Observable(observer => {
  const sub =  from(fetch('https://jsonplaceholder.typicode.com/todos/1')).subscribe(observer);
  // Return tear-down function so you can abort request.
  return () => sub.unsubscribe();
});
</code>```

Obviously, this is over complicated and if you just want to wrap a Promise with Observable you can use just from().

Body:
I'm trying to create an observable with behavior similar to what is returned by defer, but using create method. So I try:

const obs = Observable.create(function(observer) {
   from(fetch('https://jsonplaceholder.typicode.com/todos/1').then(console.log('fetch done'))).subscribe(observer)
})

setTimeout(()=>obs.subscribe((resp)=>console.log(resp.statusText)), 5000)

But when I run it in node It just prints "fetch done" (on subscription, after 5 seconds as expected) but waits forever there.

When I wrap the from(..) in setImmediate() or setTimeout(,0), then sometimes it prints both messages ("Fetch done", "OK") and exits and sometimes it only prints "fetch done" and waits forever.

code:

const obs = Observable.create(function(observer) {
    setTimeout(()=>from(fetch('https://jsonplaceholder.typicode.com/todos/1').then(console.log('fetch done'))).subscribe(observer), 0)
})

setTimeout(()=>obs.subscribe((resp)=>console.log(resp.statusText)), 5000)

Why this happens? What am I doing wrong?

Body:
First thing is that Observable.create is deprecated and you should use just new Observable():

When creating Observables like this you have access to observer object where you can call next() and complete() so in your case it would be like this:

new Observable(observer => {
  fetch('https://jsonplaceholder.typicode.com/todos/1').then(response => {
    observer.next(response);
    observer.complete();
  });
});

I think this should work as well:

new Observable(observer => {
  const sub =  from(fetch('https://jsonplaceholder.typicode.com/todos/1')).subscribe(observer);
  // Return tear-down function so you can abort request.
  return () => sub.unsubscribe();
});

Obviously, this is over complicated and if you just want to wrap a Promise with Observable you can use just from().


问:
Condition based dependency injection
I am using strategy design pattern and want to inject different dependencies based on some conditions.

```<code>public interface strategy {
    public void task();
}

public class concreteStrategyOne implements strategy {
    public void task() {
        //task strategy one
    }
}

public class concreteStrategyTwo implements strategy {
    public void task() {
        //task strategy two
    }
}

public class taskInHand {

    private Strategy strategyImpl;

    @Inject
    public taskInHand(Strategy strategyImpl){
        this.strategy = strategyImpl;
    }

    public void use(Object obj) {

      if(obj.get("something") == 1){
            strategyImpl.task();
            // I want to call task() implemented in concreteStrategyOne
      }
      else if(obj.get("something") == 2){
            strategtImpl.task()
            // I want to call task() implemented in concreteStrategyTwo
      }
}

}
</code>```

I know I can used @Named annotation in a constructor to bind specific classes while injecting but I want to inject different dependencies according the conditions mentioned above.

So, to elaborate.. if(object.get("something")) returns 1, then I would want to run task() implemented in concreteStrategyOne.

How can this be done?

答:
You can create a StrategyFactory

public Class StrategyFactory {
    @Inject
    // Strategy one impl here
    private Strategy strategyOne;

    @Inject
    // Strategy two impl here
    private Strategy strategyTwo;

    public Strategy getStrategy(String something) {
        if (something.equals("some condition")) {
            return strategyOne;
        } else {
            return strategytwo;
        }
    }
}
```

<p>Inject <code>StrategyFactory</code> in your <code>taskInHand</code> and pass on the attribute which decides the implementation to be used to <code>getStrategy()</code></p>

<pre class="lang-java prettyprint-override"><code>public void use(Object obj) {
    strategyFactory.getStrategy(obj.get("something")).task();
}
</code>```

Title: Condition based dependency injection

Body:
I am using strategy design pattern and want to inject different dependencies based on some conditions.

public interface strategy {
    public void task();
}

public class concreteStrategyOne implements strategy {
    public void task() {
        //task strategy one
    }
}

public class concreteStrategyTwo implements strategy {
    public void task() {
        //task strategy two
    }
}

public class taskInHand {

    private Strategy strategyImpl;

    @Inject
    public taskInHand(Strategy strategyImpl){
        this.strategy = strategyImpl;
    }

    public void use(Object obj) {

      if(obj.get("something") == 1){
            strategyImpl.task();
            // I want to call task() implemented in concreteStrategyOne
      }
      else if(obj.get("something") == 2){
            strategtImpl.task()
            // I want to call task() implemented in concreteStrategyTwo
      }
}

}

I know I can used @Named annotation in a constructor to bind specific classes while injecting but I want to inject different dependencies according the conditions mentioned above.

So, to elaborate.. if(object.get("something")) returns 1, then I would want to run task() implemented in concreteStrategyOne.

How can this be done?

Body:
You can create a StrategyFactory

public Class StrategyFactory {
    @Inject
    // Strategy one impl here
    private Strategy strategyOne;

    @Inject
    // Strategy two impl here
    private Strategy strategyTwo;

    public Strategy getStrategy(String something) {
        if (something.equals("some condition")) {
            return strategyOne;
        } else {
            return strategytwo;
        }
    }
}

Inject StrategyFactory in your taskInHand and pass on the attribute which decides the implementation to be used to getStrategy()

public void use(Object obj) {
    strategyFactory.getStrategy(obj.get("something")).task();
}