问:
Aligning different checkbox groups
For these checkboxgroups -
Unaligned checkboxes

I want to align them to look like these checkboxgroups - Aligned checkboxes

The following code is what I have got so far

```<code>{
        xtype: 'fieldset',
        title: 'Add to Descriptors',
        items: [
            {
                xtype: 'checkboxgroup',
                items: [
                    {boxLabel: '1.1', name: ''},
                    {boxLabel: '1.2', name: ''},
                    {boxLabel: '1.3', name: ''},
                    {boxLabel: '1.4', name: ''},
                    {boxLabel: '1.5', name: ''},
                    {boxLabel: '1.6', name: ''}
                ]
            },
            {
                xtype: 'checkboxgroup',
                items: [
                    {boxLabel: '2.1', name: ''},
                    {boxLabel: '2.2', name: ''},
                    {boxLabel: '2.3', name: ''},
                    {boxLabel: '2.4', name: ''},
                    {boxLabel: '2.5', name: ''},
                    {boxLabel: '2.6', name: ''}
                ]
            }
        ]
}
</code>```

What needs to be added?

答:
For achieving it, you need to give fixed width to all checkboxes and the layout should be hbox

Ext.application({
  name: 'Fiddle',
  launch: function() {
    Ext.create('Ext.form.Panel', {
      title: 'Checkbox Group',

      bodyPadding: 10,
      renderTo: Ext.getBody(),
      items: [{
        xtype: 'fieldset',
        title: 'Add to Descriptors',
        items: [{
            xtype: 'checkboxgroup',
            layout: 'hbox',
            defaults: { // defaults are applied to items, not the container
              width: 75
            },
            items: [{
                boxLabel: '1.1',
                name: ''
              },
              {
                boxLabel: '1.2',
                name: ''
              },
              {
                boxLabel: '1.3',
                name: ''
              },
              {
                boxLabel: '1.4',
                name: ''
              },
              {
                boxLabel: '1.5',
                name: ''
              },
              {
                boxLabel: '1.6',
                name: ''
              }
            ]
          },
          {
            xtype: 'checkboxgroup',
            layout: 'hbox',
            defaults: { // defaults are applied to items, not the container
              width: 75
            },
            items: [{
                boxLabel: '2.1',
                name: ''
              },
              {
                boxLabel: '2.2',
                name: ''
              },
              {
                boxLabel: '2.3',
                name: ''
              },
              {
                boxLabel: '2.4',
                name: ''
              },
              {
                boxLabel: '2.5',
                name: ''
              },
              {
                boxLabel: '2.6',
                name: ''
              }
            ]
          },

          {
            xtype: 'checkboxgroup',
            layout: 'hbox',
            defaults: { // defaults are applied to items, not the container
              width: 75
            },
            items: [{
                boxLabel: '3.1',
                name: ''
              },
              {
                boxLabel: '3.2',
                name: ''
              },
              {
                boxLabel: '3.3',
                name: ''
              },
              {
                boxLabel: '3.4',
                name: ''
              },
              {
                boxLabel: '3.5',
                name: ''
              },
              {
                boxLabel: '3.6',
                name: ''
              },
              {
                boxLabel: '3.7',
                name: ''
              }
            ]
          },
          {
            xtype: 'checkboxgroup',
            layout: 'hbox',
            defaults: { // defaults are applied to items, not the container
              width: 75
            },
            items: [{
                boxLabel: '4.1',
                name: ''
              },
              {
                boxLabel: '4.2',
                name: ''
              },
              {
                boxLabel: '4.3',
                name: ''
              },
              {
                boxLabel: '4.4',
                name: ''
              },
              {
                boxLabel: '4.5',
                name: ''
              },
              {
                boxLabel: '4.6',
                name: ''
              }
            ]
          },
          {
            xtype: 'checkboxgroup',
            layout: 'hbox',
            defaults: { // defaults are applied to items, not the container
              width: 75
            },
            items: [{
                boxLabel: '5.1',
                name: ''
              },
              {
                boxLabel: '5.2',
                name: ''
              },
              {
                boxLabel: '5.3',
                name: ''
              },
              {
                boxLabel: '5.4',
                name: ''
              },
              {
                boxLabel: '5.5',
                name: ''
              },
              {
                boxLabel: '5.6',
                name: ''
              }
            ]
          },
          {
            xtype: 'checkboxgroup',
            layout: 'hbox',
            defaults: { // defaults are applied to items, not the container
              width: 75
            },
            items: [{
                boxLabel: '6.1',
                name: ''
              },
              {
                boxLabel: '6.2',
                name: ''
              },
              {
                boxLabel: '6.3',
                name: ''
              },
              {
                boxLabel: '6.4',
                name: ''
              },
              {
                boxLabel: '6.5',
                name: ''
              },
            ]
          },
        ]
      }]
    });
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdn.sencha.com/ext/gpl/4.1.1/resources/css/ext-all.css">
<script type="text/javascript" src="https://cdn.sencha.com/ext/gpl/4.1.1/ext-all-debug.js"></script></code>```

Title: Aligning different checkbox groups

Body:
For these checkboxgroups -
Unaligned checkboxes

I want to align them to look like these checkboxgroups - Aligned checkboxes

The following code is what I have got so far

{
        xtype: 'fieldset',
        title: 'Add to Descriptors',
        items: [
            {
                xtype: 'checkboxgroup',
                items: [
                    {boxLabel: '1.1', name: ''},
                    {boxLabel: '1.2', name: ''},
                    {boxLabel: '1.3', name: ''},
                    {boxLabel: '1.4', name: ''},
                    {boxLabel: '1.5', name: ''},
                    {boxLabel: '1.6', name: ''}
                ]
            },
            {
                xtype: 'checkboxgroup',
                items: [
                    {boxLabel: '2.1', name: ''},
                    {boxLabel: '2.2', name: ''},
                    {boxLabel: '2.3', name: ''},
                    {boxLabel: '2.4', name: ''},
                    {boxLabel: '2.5', name: ''},
                    {boxLabel: '2.6', name: ''}
                ]
            }
        ]
}

What needs to be added?

Body:
For achieving it, you need to give fixed width to all checkboxes and the layout should be hbox

Ext.application({
  name: 'Fiddle',
  launch: function() {
    Ext.create('Ext.form.Panel', {
      title: 'Checkbox Group',

      bodyPadding: 10,
      renderTo: Ext.getBody(),
      items: [{
        xtype: 'fieldset',
        title: 'Add to Descriptors',
        items: [{
            xtype: 'checkboxgroup',
            layout: 'hbox',
            defaults: { // defaults are applied to items, not the container
              width: 75
            },
            items: [{
                boxLabel: '1.1',
                name: ''
              },
              {
                boxLabel: '1.2',
                name: ''
              },
              {
                boxLabel: '1.3',
                name: ''
              },
              {
                boxLabel: '1.4',
                name: ''
              },
              {
                boxLabel: '1.5',
                name: ''
              },
              {
                boxLabel: '1.6',
                name: ''
              }
            ]
          },
          {
            xtype: 'checkboxgroup',
            layout: 'hbox',
            defaults: { // defaults are applied to items, not the container
              width: 75
            },
            items: [{
                boxLabel: '2.1',
                name: ''
              },
              {
                boxLabel: '2.2',
                name: ''
              },
              {
                boxLabel: '2.3',
                name: ''
              },
              {
                boxLabel: '2.4',
                name: ''
              },
              {
                boxLabel: '2.5',
                name: ''
              },
              {
                boxLabel: '2.6',
                name: ''
              }
            ]
          },

          {
            xtype: 'checkboxgroup',
            layout: 'hbox',
            defaults: { // defaults are applied to items, not the container
              width: 75
            },
            items: [{
                boxLabel: '3.1',
                name: ''
              },
              {
                boxLabel: '3.2',
                name: ''
              },
              {
                boxLabel: '3.3',
                name: ''
              },
              {
                boxLabel: '3.4',
                name: ''
              },
              {
                boxLabel: '3.5',
                name: ''
              },
              {
                boxLabel: '3.6',
                name: ''
              },
              {
                boxLabel: '3.7',
                name: ''
              }
            ]
          },
          {
            xtype: 'checkboxgroup',
            layout: 'hbox',
            defaults: { // defaults are applied to items, not the container
              width: 75
            },
            items: [{
                boxLabel: '4.1',
                name: ''
              },
              {
                boxLabel: '4.2',
                name: ''
              },
              {
                boxLabel: '4.3',
                name: ''
              },
              {
                boxLabel: '4.4',
                name: ''
              },
              {
                boxLabel: '4.5',
                name: ''
              },
              {
                boxLabel: '4.6',
                name: ''
              }
            ]
          },
          {
            xtype: 'checkboxgroup',
            layout: 'hbox',
            defaults: { // defaults are applied to items, not the container
              width: 75
            },
            items: [{
                boxLabel: '5.1',
                name: ''
              },
              {
                boxLabel: '5.2',
                name: ''
              },
              {
                boxLabel: '5.3',
                name: ''
              },
              {
                boxLabel: '5.4',
                name: ''
              },
              {
                boxLabel: '5.5',
                name: ''
              },
              {
                boxLabel: '5.6',
                name: ''
              }
            ]
          },
          {
            xtype: 'checkboxgroup',
            layout: 'hbox',
            defaults: { // defaults are applied to items, not the container
              width: 75
            },
            items: [{
                boxLabel: '6.1',
                name: ''
              },
              {
                boxLabel: '6.2',
                name: ''
              },
              {
                boxLabel: '6.3',
                name: ''
              },
              {
                boxLabel: '6.4',
                name: ''
              },
              {
                boxLabel: '6.5',
                name: ''
              },
            ]
          },
        ]
      }]
    });
  }
});

<link rel="stylesheet" href="https://cdn.sencha.com/ext/gpl/4.1.1/resources/css/ext-all.css">
<script type="text/javascript" src="https://cdn.sencha.com/ext/gpl/4.1.1/ext-all-debug.js"></script>


来源: stackexchange

问:
Tensorflow in android: Linear regression
I have completed training a simple linear regression model on jupyter notebook using tensorflow, and I am able to save and restore the saved variables like so:

Now I'm trying to use the model on an android application.

Following the tutorial here, I am able to get to the stage where i import the tensorflow library like so:

Now I'm at the point where I want to give the model an input data and get a output value.(Refer to application flow below) However, they are using a .pb file(no clue what this is) in their application. In the 4 files:

that i got from saving my model, i do not have a .pb file which left me dumbfounded.

What the application does:
Predicts the SoC with a pre-trained tensorflow model using user's input value of height.
Whereby, the linear regression equation is used: y = Wx + b

y - SoC

W - weight

x - height

b - bias

All variables are float values.

Android application flow:

User inputs height value in textbox, and presses "Predict" button.

Application uses the weight, bias & height values of the saved model to predict SoC.

Application displays predicted SoC in textview.

So my question is: how do I import and use my model in Android application using android studios 2.3.1?

Here are my ipynb and csv data files.

答:
I may have misunderstood the question but:

Given that the model is pre-trained, the weight and bias are not going to change, you can simply use the W and b values calculated in the Jupyter notebook and hard code them in a simple expression

```<code><soc> = -56.0719*<height> + 98.3029
</code>```

there is no need to import a tensorflow model for this.

UPDATE
To ensure the question is answered, the *.pb file comes from freezing the checkpoint file with the graph - refer to the second code panel in the linked tutorial for how to do this.

In terms of what freezing is refer here

ContentLicense: CC BY-SA 3.0

Body:
I may have misunderstood the question but:

Given that the model is pre-trained, the weight and bias are not going to change, you can simply use the W and b values calculated in the Jupyter notebook and hard code them in a simple expression

<soc> = -56.0719*<height> + 98.3029

there is no need to import a tensorflow model for this.

UPDATE
To ensure the question is answered, the *.pb file comes from freezing the checkpoint file with the graph - refer to the second code panel in the linked tutorial for how to do this.

In terms of what freezing is refer here


问:
sapui5 - dynamically load fragment into XML-View
I want to dynamically load a fragment and have the following XML-View:

```<code><mvc:View
    xmlns:html="http://www.w3.org/1999/xhtml"
    xmlns:core="sap.ui.core"
    xmlns:mvc="sap.ui.core.mvc"
    xmlns:l="sap.ui.layout"
    xmlns="sap.m"
    controllerName="controller.App"
    visibleBlock="true">
    <App>
        <pages>
        ...
            <core:Fragment fragmentName="{= ${/BOOL_VALUE} === 'true' ? 'view.fragment1' : 'view.fragment2'}" type="XML" />
        ...
        </pages>
    </App>
</mvc:View>
</code>```

but somehow, when I load it, the expression inside of fragmentName does not get evaluated and the comparison gets treated like a filename:

```<code>Uncaught (in promise) Error: resource {= ${/BOOL_VALUE} === 'true' ? 'view/fragment1' : 'view/fragment2'}.fragment.xml could not be loaded from https://sapui5.hana.ondemand.com/1.44.14/resources/{= ${/BOOL_VALUE} === 'true' ? 'view/fragment1' : 'view/fragment2'}.fragment.xml. Check for 'file not found' or parse errors. Reason: NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'https://sapui5.hana.ondemand.com/1.44.14/resources/%7B=%20$%7B/BOOL_VALUE%7…'true'%20?%20%27view/fragment1%27%20:%20%27view/fragment2%27}.fragment.xml'.
at Object.error (jquery.sap.global-dbg.js:4573)
at p (jquery-dbg.js:3187)
at Object.fireWith [as rejectWith] (jquery-dbg.js:3317)
at h3 (jquery-dbg.js:8787)
at Function.ajax (jquery-dbg.js:8689)
at Object.q.sap.loadResource (jquery.sap.global-dbg.js:4564)
at Object.X.loadTemplate (XMLTemplateProcessor-dbg.js:64)
at constructor.init (Fragment-dbg.js:469)
at constructor.F._initCompositeSupport (Fragment-dbg.js:135)
at ManagedObject-dbg.js:427
</code>```

What am I doing wrong here?

答: I do no think you can use expression binding for property 'fragmentName',  just like you can't for  'id'  or  'class'  you should use a formatter function instead.</p>

Body:
I want to dynamically load a fragment and have the following XML-View:

<mvc:View
    xmlns:html="http://www.w3.org/1999/xhtml"
    xmlns:core="sap.ui.core"
    xmlns:mvc="sap.ui.core.mvc"
    xmlns:l="sap.ui.layout"
    xmlns="sap.m"
    controllerName="controller.App"
    visibleBlock="true">
    <App>
        <pages>
        ...
            <core:Fragment fragmentName="{= ${/BOOL_VALUE} === 'true' ? 'view.fragment1' : 'view.fragment2'}" type="XML" />
        ...
        </pages>
    </App>
</mvc:View>

but somehow, when I load it, the expression inside of fragmentName does not get evaluated and the comparison gets treated like a filename:

Uncaught (in promise) Error: resource {= ${/BOOL_VALUE} === 'true' ? 'view/fragment1' : 'view/fragment2'}.fragment.xml could not be loaded from https://sapui5.hana.ondemand.com/1.44.14/resources/{= ${/BOOL_VALUE} === 'true' ? 'view/fragment1' : 'view/fragment2'}.fragment.xml. Check for 'file not found' or parse errors. Reason: NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'https://sapui5.hana.ondemand.com/1.44.14/resources/%7B=%20$%7B/BOOL_VALUE%7…'true'%20?%20%27view/fragment1%27%20:%20%27view/fragment2%27}.fragment.xml'.
at Object.error (jquery.sap.global-dbg.js:4573)
at p (jquery-dbg.js:3187)
at Object.fireWith [as rejectWith] (jquery-dbg.js:3317)
at h3 (jquery-dbg.js:8787)
at Function.ajax (jquery-dbg.js:8689)
at Object.q.sap.loadResource (jquery.sap.global-dbg.js:4564)
at Object.X.loadTemplate (XMLTemplateProcessor-dbg.js:64)
at constructor.init (Fragment-dbg.js:469)
at constructor.F._initCompositeSupport (Fragment-dbg.js:135)
at ManagedObject-dbg.js:427

What am I doing wrong here?


问:
Adding and Updating a List object does not work in C#
Newbie with C# and Linq.

I am trying to add an object and update an object if exists in a List. The list is not getting updated or not getting added with new inputs.It is not throwing any exception. Kindly, help.

```<code>private IList<SettingsEntity> Settings = new List<SettingsEntity>();

public SettingsRepository() {
            Settings.Add(new SettingsEntity() { UserID = "alpha", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "bravo", ApplicationName = "view", SettingKey = "RefreshRate", SettingValue = "10", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "charlie", ApplicationName = "upload", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "foxtrot", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "lima", ApplicationName = "view", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "Julie", ApplicationName = "upload", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "tango", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "victor", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "yankee", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "zulu", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
        }

 public bool Save(SettingsEntity entity)
        {
            var flag = false;
            if (entity != null)
            {
                var existing = Settings.Where(se => se.UserID == entity.UserID && se.ApplicationName == entity.ApplicationName && se.SettingKey == entity.SettingKey).ToList();
                if (existing != null)
                {
                    existing.ForEach(f => f.SettingValue = entity.SettingValue);
                    flag = true;
                }
                else
                {
                    Settings.Add(entity);
                    flag = true;
                }
                return flag;
            }
            else {
                throw new ArgumentNullException();
            }

        }

 [HttpPost]
        public IActionResult Post([FromBody] SettingsEntity entity)
        {
            var result = _SettingsRepository.Save(entity);
            if (result == true)
            {
                return Ok();
            }
            else
            {
                return BadRequest();
            }
        }
</code>```

答:
Wouldn't this work for you? The List you tried to get will never be null (how could it? You got it from a valid IEnumerable) so what you can do is check the number of elements in the List.

Btw. you will always return true, so I removed that to make your code more readable.

```<code>public void Save(SettingsEntity entity)
{
    if (entity == null)
        throw new ArgumentNullException();

    var existing = Settings.Where(se => se.UserID == entity.UserID && se.ApplicationName == entity.ApplicationName && se.SettingKey == entity.SettingKey).ToList();
    if (existing.Count > 0)
        existing.ForEach(f => f.SettingValue = entity.SettingValue);
    else
        Settings.Add(entity);
}
</code>```

Body:
Newbie with C# and Linq.

I am trying to add an object and update an object if exists in a List. The list is not getting updated or not getting added with new inputs.It is not throwing any exception. Kindly, help.

private IList<SettingsEntity> Settings = new List<SettingsEntity>();

public SettingsRepository() {
            Settings.Add(new SettingsEntity() { UserID = "alpha", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "bravo", ApplicationName = "view", SettingKey = "RefreshRate", SettingValue = "10", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "charlie", ApplicationName = "upload", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "foxtrot", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "lima", ApplicationName = "view", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "Julie", ApplicationName = "upload", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "tango", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "victor", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "yankee", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
            Settings.Add(new SettingsEntity() { UserID = "zulu", ApplicationName = "protocol archive", SettingKey = "RefreshTime", SettingValue = "20", UpdatedOn = new DateTime().Date, SettingLabel = "RefreshInterval", IsActive = true });
        }

 public bool Save(SettingsEntity entity)
        {
            var flag = false;
            if (entity != null)
            {
                var existing = Settings.Where(se => se.UserID == entity.UserID && se.ApplicationName == entity.ApplicationName && se.SettingKey == entity.SettingKey).ToList();
                if (existing != null)
                {
                    existing.ForEach(f => f.SettingValue = entity.SettingValue);
                    flag = true;
                }
                else
                {
                    Settings.Add(entity);
                    flag = true;
                }
                return flag;
            }
            else {
                throw new ArgumentNullException();
            }

        }

 [HttpPost]
        public IActionResult Post([FromBody] SettingsEntity entity)
        {
            var result = _SettingsRepository.Save(entity);
            if (result == true)
            {
                return Ok();
            }
            else
            {
                return BadRequest();
            }
        }

Body:
Wouldn't this work for you? The List you tried to get will never be null (how could it? You got it from a valid IEnumerable) so what you can do is check the number of elements in the List.

Btw. you will always return true, so I removed that to make your code more readable.

public void Save(SettingsEntity entity)
{
    if (entity == null)
        throw new ArgumentNullException();

    var existing = Settings.Where(se => se.UserID == entity.UserID && se.ApplicationName == entity.ApplicationName && se.SettingKey == entity.SettingKey).ToList();
    if (existing.Count > 0)
        existing.ForEach(f => f.SettingValue = entity.SettingValue);
    else
        Settings.Add(entity);
}


问:
Is there an extension of Twitter Bootstrap for Retina-Display?
Its a lot headache trying to merge bootstrap CSS and CSS specific to retina-display.

So is there an easy way to do this. May be someone has built an extension about it.

答: In Bootstrap 3, there is the img-retina mixin.


问:
Identify empty string in Perl
There is probably an easy solution to this, but I can't figure it out. I am looking to:

take a CSV file into an array

loop through the array and split fields into variables

if the array field is empty then set the variable to "N/A"

Note: It is only setting the $variable to "N/A" that I cannot get working.

For example:

```<code>foreach $var (@list) {

($name,$date,$size, etc...)=split(/,\"/,$var);

}
</code>```

How would I set $date to "N/A" if the field in the array is empty?

so to produce:

```<code>$name = Jim
$date = N/A
$size = small
</code>```

I hope this makes sense and is easy to fix.
-Thanks

答:
Assuming the variable $date is undefined when "empty":

```<code>if (!defined($date)) {
  $date = 'N/A';
}
</code>```

Or more concisely:

```<code>$date //= 'N/A';
</code>```

Or if it really is an empty string, i.e. $date = ''; (this will also work in the case where $date is undefined, but you don't want to use this if you only want to identify the case where it is undefined):

```<code>if ($date eq '') {
  $date = 'N/A';
}
</code>```

Or more concisely (note that this will also set $date to N/A if $date is '0' due to Perl's weak typing):

```<code>$date ||= 'N/A';
</code>```

ContentLicense: CC BY-SA 2.5

Title: Identify empty string in Perl

Body:
There is probably an easy solution to this, but I can't figure it out. I am looking to:

take a CSV file into an array

loop through the array and split fields into variables

if the array field is empty then set the variable to "N/A"

Note: It is only setting the $variable to "N/A" that I cannot get working.

For example:

foreach $var (@list) {

($name,$date,$size, etc...)=split(/,\"/,$var);

}

How would I set $date to "N/A" if the field in the array is empty?

so to produce:

$name = Jim
$date = N/A
$size = small

I hope this makes sense and is easy to fix.
-Thanks

Body:
Assuming the variable $date is undefined when "empty":

if (!defined($date)) {
  $date = 'N/A';
}

Or more concisely:

$date //= 'N/A';

Or if it really is an empty string, i.e. $date = ''; (this will also work in the case where $date is undefined, but you don't want to use this if you only want to identify the case where it is undefined):

if ($date eq '') {
  $date = 'N/A';
}

Or more concisely (note that this will also set $date to N/A if $date is '0' due to Perl's weak typing):

$date ||= 'N/A';


问:
UWP Gridview binding to View Model
I'm using a GridView in a UserControl to display a five by four square of graphical buttons that allow selection of a Lesson.

This is in a Windows 8.1 Store App that I'm upgrading to Windows 10 UWP.

I previously used Tap and Right-Tap actions to select a Lesson or activate the CommandBar to perform related actions for a Lesson through the SelectionChanged event.  However, there have been changes to how Interactions now work under Windows 10, I have been unable to get the Gridview to work at all with binding the SelectedItem to the selected LessonButton in the view model, nor the SelectionChanged and ItemClick events for such purposes.  The Gridview selections behaviour doesn't work, as once an item is selected it is never deselected.  So finally, I've taken a different tack and am trying Tap and Right-Tap events for the Gridview Items.  However the issue is, that no matter which way I approach it, I can't get Binding to work correctly.

So I have an object called LessonButton:

```<code>public class LessonButton : INotifyPropertyChanged
{
    //public LessonButton() { }
    public LessonButton(SolidColorBrush inBackground, bool inComplete, double inHeight, int inNumber, bool inSelected, bool inStarted,
        Status inState, double inWidth)
    {
        ...
        Started = inStarted;
        ...
    }
    ...
    private bool _started;
    public bool Started
    {
        get { return _started; }
        set { if (_started != value) { _started = value; OnPropertyChanged(); } }
    }
    ...
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var handler = PropertyChanged;
        handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
</code>```

It is added to an observable collection in the View Model:

```<code>public class LessonsViewModel : INotifyPropertyChanged
{
    public ObservableCollection<LessonButton> Lessons { get; } = new ObservableCollection<LessonButton>();

    private LessonButton _selectedLessonButton;

    public LessonButton SelectedLessonButton
    {
        get { return _selectedLessonButton; }
        set { if (_selectedLessonButton != value) { _selectedLessonButton = value; OnPropertyChanged(); } }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var handler = PropertyChanged;
        handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
</code>```

In a user control I set the DataContext with:

```<code><UserControl.DataContext>
    <classes:LessonsViewModel/>
</UserControl.DataContext>
</code>```

..and I then have a GridView defined as:

```<code>        <GridView x:Name="LessonGridView" ItemContainerStyle="{StaticResource GridViewItemStyle}" ItemsSource="{Binding Lessons}"
              SelectionMode="Single" IsItemClickEnabled="False" SelectedItem="{Binding Path=SelectedLessonButton, Mode=TwoWay}">
        <GridView.ItemsPanel>
            <ItemsPanelTemplate>
                <VariableSizedWrapGrid HorizontalChildrenAlignment="Left" MaximumRowsOrColumns="5" Orientation="Horizontal" VerticalChildrenAlignment="Top"/>
            </ItemsPanelTemplate>
        </GridView.ItemsPanel>
    </GridView>
</code>```

With the GridView item format defined in a ControlTemplate as part of the GridViewItemStyle.

I've tried to access the LessonButton variables in various ways using Binding and xBind, but could only get the program to run with the ControlTemplate using this XAML:

```<code>    <Image Grid.Row="1" Grid.Column="1" Width="{StaticResource BadgeSize}"
    Height="{StaticResource BadgeSize}" HorizontalAlignment="Right" VerticalAlignment="Top"
    Opacity="{Binding Started, Converter={StaticResource OpacityConverterTrueValueIsVisible}}"
    Source="/Assets/SelectionButtonGroup/square310x310logobw.png" Stretch="Uniform"/>
</code>```

The Converter simply returns a 1 or 0 depending upon the value of the bool Started.

Although this code work, it is not correct somehow and Visual Studio reports an unknown error and states it cannot find the Started property.  In fact it can't find any of the properties of LessonButton and I've been unable to find the correct syntax for exposing them, even with x:Bind code such as:

```<code>{x:Bind LessonViewModel.Lessons.LessonButton.Selected}
</code>```

..or versions thereof, using casting etc.

I'm using Visual Studio 2017 Enterprise, which reports the aforementioned errors and displays wavy lines over the entire ControlTemplate with an error where it cannot find another Converter artefact that isn't even related to this code.. which in itself, I find extremely irritating.  Is it me or does the XAML Intellisence in VS seem very flaky, in that it gives up and reports false errors if it can't identify the root cause of a real one?

Ideally I'd like the Gridview SelectedItem to bind with the ViewModel.  But even trying actions via Tap events I can't get the binding to correctly expose LessonButton properties in the ControlTemplate XAML.

Any help would be greatly appreciated.

答:
You shouldn't be using the  ItemContainerStyle to Bind your LessonButton variables to. The ItemContainerStyle is used to style the Item with selection marks, its hover and pressed states etc.

You should instead use a DataTemplate stored inside your UserControl's resources like so:

```<code><Grid>
  <Grid.Resources>
    <DataTemplate x:Name="GridViewTemplate">
      <TextBlock Text="{Binding LessonName}">
    </DataTemplate>
  </StackPanel.Resources>
  <GridView x:Name="GridView"
            ItemsSource="{Binding Lessons}"
            ItemTemplate="{StaticResource GridViewTemplate}">
  </GridView>
</Grid>
</code>```

Then give your DataTemplate a name (above "GridViewTemplate") and set it as the ItemTemplate of your GridView.

Title: UWP Gridview binding to View Model

Body:
I'm using a GridView in a UserControl to display a five by four square of graphical buttons that allow selection of a Lesson.

This is in a Windows 8.1 Store App that I'm upgrading to Windows 10 UWP.

I previously used Tap and Right-Tap actions to select a Lesson or activate the CommandBar to perform related actions for a Lesson through the SelectionChanged event.  However, there have been changes to how Interactions now work under Windows 10, I have been unable to get the Gridview to work at all with binding the SelectedItem to the selected LessonButton in the view model, nor the SelectionChanged and ItemClick events for such purposes.  The Gridview selections behaviour doesn't work, as once an item is selected it is never deselected.  So finally, I've taken a different tack and am trying Tap and Right-Tap events for the Gridview Items.  However the issue is, that no matter which way I approach it, I can't get Binding to work correctly.

So I have an object called LessonButton:

public class LessonButton : INotifyPropertyChanged
{
    //public LessonButton() { }
    public LessonButton(SolidColorBrush inBackground, bool inComplete, double inHeight, int inNumber, bool inSelected, bool inStarted,
        Status inState, double inWidth)
    {
        ...
        Started = inStarted;
        ...
    }
    ...
    private bool _started;
    public bool Started
    {
        get { return _started; }
        set { if (_started != value) { _started = value; OnPropertyChanged(); } }
    }
    ...
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var handler = PropertyChanged;
        handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

It is added to an observable collection in the View Model:

public class LessonsViewModel : INotifyPropertyChanged
{
    public ObservableCollection<LessonButton> Lessons { get; } = new ObservableCollection<LessonButton>();

    private LessonButton _selectedLessonButton;

    public LessonButton SelectedLessonButton
    {
        get { return _selectedLessonButton; }
        set { if (_selectedLessonButton != value) { _selectedLessonButton = value; OnPropertyChanged(); } }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var handler = PropertyChanged;
        handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

In a user control I set the DataContext with:

<UserControl.DataContext>
    <classes:LessonsViewModel/>
</UserControl.DataContext>

..and I then have a GridView defined as:

        <GridView x:Name="LessonGridView" ItemContainerStyle="{StaticResource GridViewItemStyle}" ItemsSource="{Binding Lessons}"
              SelectionMode="Single" IsItemClickEnabled="False" SelectedItem="{Binding Path=SelectedLessonButton, Mode=TwoWay}">
        <GridView.ItemsPanel>
            <ItemsPanelTemplate>
                <VariableSizedWrapGrid HorizontalChildrenAlignment="Left" MaximumRowsOrColumns="5" Orientation="Horizontal" VerticalChildrenAlignment="Top"/>
            </ItemsPanelTemplate>
        </GridView.ItemsPanel>
    </GridView>

With the GridView item format defined in a ControlTemplate as part of the GridViewItemStyle.

I've tried to access the LessonButton variables in various ways using Binding and xBind, but could only get the program to run with the ControlTemplate using this XAML:

    <Image Grid.Row="1" Grid.Column="1" Width="{StaticResource BadgeSize}"
    Height="{StaticResource BadgeSize}" HorizontalAlignment="Right" VerticalAlignment="Top"
    Opacity="{Binding Started, Converter={StaticResource OpacityConverterTrueValueIsVisible}}"
    Source="/Assets/SelectionButtonGroup/square310x310logobw.png" Stretch="Uniform"/>

The Converter simply returns a 1 or 0 depending upon the value of the bool Started.

Although this code work, it is not correct somehow and Visual Studio reports an unknown error and states it cannot find the Started property.  In fact it can't find any of the properties of LessonButton and I've been unable to find the correct syntax for exposing them, even with x:Bind code such as:

{x:Bind LessonViewModel.Lessons.LessonButton.Selected}

..or versions thereof, using casting etc.

I'm using Visual Studio 2017 Enterprise, which reports the aforementioned errors and displays wavy lines over the entire ControlTemplate with an error where it cannot find another Converter artefact that isn't even related to this code.. which in itself, I find extremely irritating.  Is it me or does the XAML Intellisence in VS seem very flaky, in that it gives up and reports false errors if it can't identify the root cause of a real one?

Ideally I'd like the Gridview SelectedItem to bind with the ViewModel.  But even trying actions via Tap events I can't get the binding to correctly expose LessonButton properties in the ControlTemplate XAML.

Any help would be greatly appreciated.

Body:
You shouldn't be using the  ItemContainerStyle to Bind your LessonButton variables to. The ItemContainerStyle is used to style the Item with selection marks, its hover and pressed states etc.

You should instead use a DataTemplate stored inside your UserControl's resources like so:

<Grid>
  <Grid.Resources>
    <DataTemplate x:Name="GridViewTemplate">
      <TextBlock Text="{Binding LessonName}">
    </DataTemplate>
  </StackPanel.Resources>
  <GridView x:Name="GridView"
            ItemsSource="{Binding Lessons}"
            ItemTemplate="{StaticResource GridViewTemplate}">
  </GridView>
</Grid>

Then give your DataTemplate a name (above "GridViewTemplate") and set it as the ItemTemplate of your GridView.


问:
C# Winform Storing and Passing Variables?
So for 99% of my learning of C# it has been with console applications, now I'd like to try simple GUI i.e win form apps. But I have no idea on how to get the input from a text box, store it as an int or double and pass it to a method that will just do a simple task like converting it into pounds (lb).
Sorry for such a noob question but how do I do this? I know how to make the method just not how to get input and pass variables from a textbox...</p>

答:
I'd give a simple example.

Add two components to your form. 1) Textbox,  2) Button
Then OnClick of the button should read TextBox1.Text value as string and do whatever you want with it, I believe you are familiar with parsing and dealing with variables.


问:
Find shared sub-ranges defined by start and endpoints in pandas dataframe
I need to combine two dataframes that contain information about train track sections: while the "Line" identifies a track section, the two attributes "A" and "B" are given for subsections of the Line defined by start point and end point on the line; these subsections do not match between the two dataframes:

```<code>df1
Line    startpoint  endpoint    Attribute_A
100     2.506       2.809       B-70
100     2.809       2.924       B-91
100     2.924       4.065       B-84
100     4.065       4.21        B-70
100     4.21        4.224       B-91
...

df2
Line    startpoint  endpoint    Attribute_B
100     2.5         2.6         140
100     2.6         2.7         158
100     2.7         2.8         131
100     2.8         2.9         124
100     2.9         3.0         178

...
</code>```

What I would need is a merged dataframe that gives me the combination of Attributes A and B for the respective minimal subsections where they are shared:

```<code>df3
Line    startpoint  endpoint    Attribute_A Attribute_B
100     2.5         2.506       nan         140
100     2.506       2.6         B-70        140
100     2.6         2.7         B-70        158
100     2.7         2.8         B-70        131
100     2.8         2.809       B-70        124
100     2.809       2.9         B-91        124
100     2.9         2.924       B-91        178
100     2.924       3.0         B-84        178
...
</code>```

How can I do this best in python? I'm somewhate new to it and while I get around basic calculations between rows and columns, I'm at my wit's ends with this problem; the approach of merging and sorting the two dataframes and calculating the respective differences between start- / endpoints didn't get me very far and I can't seem to find applicable information on the forums. I'm grateful for any hint !

答:
Here is my solution, a bit long but it works:

First step is finding the intervals:

```<code>all_start_points = set(df1['startpoint'].values.tolist() + df2['startpoint'].values.tolist())
all_end_points = set(df1['endpoint'].values.tolist() + df2['endpoint'].values.tolist())

all_points = sorted(list(all_start_points.union(all_end_points)))

intervals = [(start, end) for start, end in zip(all_points[:-1], all_points[1:])]
</code>```

Then we need to find the relevant interval in each dataframe (if present):

```<code>import numpy as np
def find_interval(df, interval):
    return df[(df['startpoint']<=interval[0]) &
              (df['endpoint']>=interval[1])]

attr_A = [find_interval(df1, intv)['Attribute_A'] for intv in intervals]
attr_A = [el.iloc[0] if len(el)>0 else np.nan for el in attr_A]

attr_B = [find_interval(df2, intv)['Attribute_B'] for intv in intervals]
attr_B = [el.iloc[0] if len(el)>0 else np.nan for el in attr_B]
</code>```

Finally, we put everything together:

```<code>out = pd.DataFrame(intervals, columns = ['startpoint', 'endpoint'])
out = pd.concat([out, pd.Series(attr_A).to_frame('Attribute_A'), pd.Series(attr_B).to_frame('Attribute_B')], axis = 1)
out['Line'] = 100
</code>```

And I get the expected result:

```<code>out
Out[111]:
    startpoint  endpoint Attribute_A  Attribute_B  Line
0        2.500     2.506         NaN        140.0   100
1        2.506     2.600        B-70        140.0   100
2        2.600     2.700        B-70        158.0   100
3        2.700     2.800        B-70        131.0   100
4        2.800     2.809        B-70        124.0   100
5        2.809     2.900        B-91        124.0   100
6        2.900     2.924        B-91        178.0   100
7        2.924     3.000        B-84        178.0   100
8        3.000     4.065        B-84          NaN   100
9        4.065     4.210        B-70          NaN   100
10       4.210     4.224        B-91          NaN   100
</code>```

Body:
I need to combine two dataframes that contain information about train track sections: while the "Line" identifies a track section, the two attributes "A" and "B" are given for subsections of the Line defined by start point and end point on the line; these subsections do not match between the two dataframes:

df1
Line    startpoint  endpoint    Attribute_A
100     2.506       2.809       B-70
100     2.809       2.924       B-91
100     2.924       4.065       B-84
100     4.065       4.21        B-70
100     4.21        4.224       B-91
...

df2
Line    startpoint  endpoint    Attribute_B
100     2.5         2.6         140
100     2.6         2.7         158
100     2.7         2.8         131
100     2.8         2.9         124
100     2.9         3.0         178

...

What I would need is a merged dataframe that gives me the combination of Attributes A and B for the respective minimal subsections where they are shared:

df3
Line    startpoint  endpoint    Attribute_A Attribute_B
100     2.5         2.506       nan         140
100     2.506       2.6         B-70        140
100     2.6         2.7         B-70        158
100     2.7         2.8         B-70        131
100     2.8         2.809       B-70        124
100     2.809       2.9         B-91        124
100     2.9         2.924       B-91        178
100     2.924       3.0         B-84        178
...

How can I do this best in python? I'm somewhate new to it and while I get around basic calculations between rows and columns, I'm at my wit's ends with this problem; the approach of merging and sorting the two dataframes and calculating the respective differences between start- / endpoints didn't get me very far and I can't seem to find applicable information on the forums. I'm grateful for any hint !

Body:
Here is my solution, a bit long but it works:

First step is finding the intervals:

all_start_points = set(df1['startpoint'].values.tolist() + df2['startpoint'].values.tolist())
all_end_points = set(df1['endpoint'].values.tolist() + df2['endpoint'].values.tolist())

all_points = sorted(list(all_start_points.union(all_end_points)))

intervals = [(start, end) for start, end in zip(all_points[:-1], all_points[1:])]

Then we need to find the relevant interval in each dataframe (if present):

import numpy as np
def find_interval(df, interval):
    return df[(df['startpoint']<=interval[0]) &
              (df['endpoint']>=interval[1])]

attr_A = [find_interval(df1, intv)['Attribute_A'] for intv in intervals]
attr_A = [el.iloc[0] if len(el)>0 else np.nan for el in attr_A]

attr_B = [find_interval(df2, intv)['Attribute_B'] for intv in intervals]
attr_B = [el.iloc[0] if len(el)>0 else np.nan for el in attr_B]

Finally, we put everything together:

out = pd.DataFrame(intervals, columns = ['startpoint', 'endpoint'])
out = pd.concat([out, pd.Series(attr_A).to_frame('Attribute_A'), pd.Series(attr_B).to_frame('Attribute_B')], axis = 1)
out['Line'] = 100

And I get the expected result:

out
Out[111]:
    startpoint  endpoint Attribute_A  Attribute_B  Line
0        2.500     2.506         NaN        140.0   100
1        2.506     2.600        B-70        140.0   100
2        2.600     2.700        B-70        158.0   100
3        2.700     2.800        B-70        131.0   100
4        2.800     2.809        B-70        124.0   100
5        2.809     2.900        B-91        124.0   100
6        2.900     2.924        B-91        178.0   100
7        2.924     3.000        B-84        178.0   100
8        3.000     4.065        B-84          NaN   100
9        4.065     4.210        B-70          NaN   100
10       4.210     4.224        B-91          NaN   100


问:
How do I pause Macro until either print or back is selected in Application.CommandBars.ExecuteMso ("PrintPreviewAndPrint")
I have a user form that selects sheets to print and then prints them once a command button is clicked.

I want to open the "Backstage" PrintPreviewandPrint page to allow for simultaneous selection of printer properties and preview the selected sheet for printing. Once I have clicked print, or the back arrow, I want to PrintPreviewandPrint page to close and select "Home" screen.

When I use

Application.CommandBars.ExecuteMso ("PrintPreviewAndPrint")

the desired screen is displayed, but the macro continues to run and the print preview show the home screen. i.e. the macro does not wait for an input from the PrintPreviewandPrint page before continuing.

Code is

```<code>Private Sub PrintDoc()

Sheets("Doc").Select
Application.CommandBars.ExecuteMso ("PrintPreviewAndPrint")
Sheets("Home").Select
End Sub
</code>```

Any help will be much appreciated

答:
I found a slightly messy solution...

First I call the print preview with:

```<code>Sub Printdoc()

    Sheets("Doc").PrintPreview
    Sheets("Home").Select

End Sub
</code>```

Then I call the Print Dialogue if print is selected

```<code>Private Sub Workbook_BeforePrint(Cancel As Boolean)

    Application.Dialogs(xlDialogPrint).Show

End Sub
</code>```

Either way(Print or Cancel), the PrintDoc macro completes by displaying the "Home" screen

Body:
I have a user form that selects sheets to print and then prints them once a command button is clicked.

I want to open the "Backstage" PrintPreviewandPrint page to allow for simultaneous selection of printer properties and preview the selected sheet for printing. Once I have clicked print, or the back arrow, I want to PrintPreviewandPrint page to close and select "Home" screen.

When I use

Application.CommandBars.ExecuteMso ("PrintPreviewAndPrint")

the desired screen is displayed, but the macro continues to run and the print preview show the home screen. i.e. the macro does not wait for an input from the PrintPreviewandPrint page before continuing.

Code is

Private Sub PrintDoc()

Sheets("Doc").Select
Application.CommandBars.ExecuteMso ("PrintPreviewAndPrint")
Sheets("Home").Select
End Sub

Any help will be much appreciated

Body:
I found a slightly messy solution...

First I call the print preview with:

Sub Printdoc()

    Sheets("Doc").PrintPreview
    Sheets("Home").Select

End Sub

Then I call the Print Dialogue if print is selected

Private Sub Workbook_BeforePrint(Cancel As Boolean)

    Application.Dialogs(xlDialogPrint).Show

End Sub

Either way(Print or Cancel), the PrintDoc macro completes by displaying the "Home" screen


问:
How to map a Map of Sets in JPA
Is there a way in JPA to map an attribute with type Map<String, Set<Address>>

Given the following classes:

```<code>class Company {
  int id;
  Map<String, Set<Address>> addresses; // Key is the country of the Address
}

class Address {
  int id;
  String country;
}
</code>```

There are three tables:

```<code>tbl_company
  id INT

tbl_address
  id INT
  country VARCHAR(40)

tbl_company_address
  company_id INT
  address_id INT
</code>```

How can I map this scenario with JPA

答:
One of possible solutions is having an address-wrapping class, and insert Set into that class. In that case you will be able to use map (using @OneToMany, @MapKey annotations). E.g.

```<code>@OneToMany(mappedBy = ...)
@MapKey(name = "countryKey")
private Map<String, AddressWrapper> addressWrappers;
</code>```

.. and AddressWrapper would contain @OneToMany Set<Address> addresses;, along with String countryKey.

Title: How to map a Map of Sets in JPA

Body:
Is there a way in JPA to map an attribute with type Map<String, Set<Address>>

Given the following classes:

class Company {
  int id;
  Map<String, Set<Address>> addresses; // Key is the country of the Address
}

class Address {
  int id;
  String country;
}

There are three tables:

tbl_company
  id INT

tbl_address
  id INT
  country VARCHAR(40)

tbl_company_address
  company_id INT
  address_id INT

How can I map this scenario with JPA

Body:
One of possible solutions is having an address-wrapping class, and insert Set into that class. In that case you will be able to use map (using @OneToMany, @MapKey annotations). E.g.

@OneToMany(mappedBy = ...)
@MapKey(name = "countryKey")
private Map<String, AddressWrapper> addressWrappers;

.. and AddressWrapper would contain @OneToMany Set<Address> addresses;, along with String countryKey.


问:
React - Prevent focus going out of modal when tabbing
I have built a react modal on my own. When I press tab key while the modal is opened, the focus still goes to the background page. How to restrict the focus within the components inside the modal?

What should be the logic below?

```<code>onKeyPress (e) {
   if (e.keyCode === 9) {
       e.preventDefault();
      // logic here?
   }
}
</code>```

React Modal code:

```<code><ReactModal onKeyPress={this.onKeyPress} >
   <input type="text"/>
   <input type="text"/>
</ReactModal>
</code>```

答:
Well, you can do it using a focus trap. Check out this npm module for that. Merely wrap your  which contains modal with a focus-trap like this.

```<code>    <FocusTrap
              focusTrapOptions={{
                ...
              }}
            >
              <div className="trap">
                <p>
                  Here is a focus trap
                  {' '}
                  <a href="#">with</a>
                  {' '}
                  <a href="#">some</a>
                  {' '}
                  <a href="#">focusable</a>
                  {' '}
                  parts.
                </p>
                <p>
                  <button onClick={this.someCallback}>
                    Click Me
                  </button>
                </p>
              </div>

</FocusTrap>
</code>```

Instead of giving you advice on implementing this, I suggest that you just don’t implement it yourself. It is hard to get right considering accessibility.

Instead, I would suggest you to use an accessible off-the-shelf modal component such as react-modal. It is completely customizable, you can put anything you want inside of it, but it handles accessibility correctly so that blind people can still use your modal.

Body:
I have built a react modal on my own. When I press tab key while the modal is opened, the focus still goes to the background page. How to restrict the focus within the components inside the modal?

What should be the logic below?

onKeyPress (e) {
   if (e.keyCode === 9) {
       e.preventDefault();
      // logic here?
   }
}

React Modal code:

<ReactModal onKeyPress={this.onKeyPress} >
   <input type="text"/>
   <input type="text"/>
</ReactModal>

Body:
Well, you can do it using a focus trap. Check out this npm module for that. Merely wrap your  which contains modal with a focus-trap like this.

    <FocusTrap
              focusTrapOptions={{
                ...
              }}
            >
              <div className="trap">
                <p>
                  Here is a focus trap
                  {' '}
                  <a href="#">with</a>
                  {' '}
                  <a href="#">some</a>
                  {' '}
                  <a href="#">focusable</a>
                  {' '}
                  parts.
                </p>
                <p>
                  <button onClick={this.someCallback}>
                    Click Me
                  </button>
                </p>
              </div>

</FocusTrap>

Instead of giving you advice on implementing this, I suggest that you just don’t implement it yourself. It is hard to get right considering accessibility.

Instead, I would suggest you to use an accessible off-the-shelf modal component such as react-modal. It is completely customizable, you can put anything you want inside of it, but it handles accessibility correctly so that blind people can still use your modal.


问:
Mockito matchers, scala value class and NullPointerException
I'm using mockito with scalatest. I have following problem when using matcher with value class.

import org.scalatest.FlatSpec
import org.scalatest.mock.MockitoSugar
import org.mockito.BDDMockito._
import org.mockito.Matchers.any

case class FirstId(val value: String) extends AnyVal
case class SecondId(val value: String) extends AnyVal

trait MockedClass {
  def someMethods(firstId: FirstId, secondId: SecondId): Int
}

class ValueClassSpec() extends FlatSpec with MockitoSugar {

  val mockedClass = mock[MockedClass]
  val secondId = SecondId("secondId")

  "Matchers" should "work for value class" in {
    // given
    given(mockedClass.someMethods(any[FirstId], org.mockito.Matchers.eq(secondId))).willReturn(3)
    // when
    val result = mockedClass.someMethods(FirstId("firstId"), secondId)
    // then
    assert(result == 3)
  }

}
```

<p>and the result is:</p>

<pre class="lang-java prettyprint-override"><code>ValueClassSpec:
Matchers
- should work for value class *** FAILED ***
  java.lang.NullPointerException:
  at io.scalac.fow.party.ValueClassSpec$$anonfun$1.apply$mcV$sp(ValueClassSpec.scala:22)
  at io.scalac.fow.party.ValueClassSpec$$anonfun$1.apply(ValueClassSpec.scala:20)
  at io.scalac.fow.party.ValueClassSpec$$anonfun$1.apply(ValueClassSpec.scala:20)
  at org.scalatest.Transformer$$anonfun$apply$1.apply(Transformer.scala:22)
  at org.scalatest.Transformer$$anonfun$apply$1.apply(Transformer.scala:22)
  at org.scalatest.OutcomeOf$class.outcomeOf(OutcomeOf.scala:85)
  at org.scalatest.OutcomeOf$.outcomeOf(OutcomeOf.scala:104)
  at org.scalatest.Transformer.apply(Transformer.scala:22)
  at org.scalatest.Transformer.apply(Transformer.scala:20)
  at org.scalatest.FlatSpecLike$$anon$1.apply(FlatSpecLike.scala:1639)
  ...
</code>```

I found similar question (Scala Value classes and Mockito Matchers don't play together) but without any advice.

Is there any posibility to use mockito matchers with scala value class?

Lib versions: scala 2.11.2, mockito 1.10.8, scalatest 2.1.6

答:
If you have shapeless in your dependencies you could consider my little helper method: https://gist.github.com/Fristi/bbc9d0e04557278f8d19976188a0b733

Instead of writing

UserId(is(context.userId.value))

You can write

isAnyVal(context.userId)

Which is a bit more convenient :-)

Body:
I'm using mockito with scalatest. I have following problem when using matcher with value class.

import org.scalatest.FlatSpec
import org.scalatest.mock.MockitoSugar
import org.mockito.BDDMockito._
import org.mockito.Matchers.any

case class FirstId(val value: String) extends AnyVal
case class SecondId(val value: String) extends AnyVal

trait MockedClass {
  def someMethods(firstId: FirstId, secondId: SecondId): Int
}

class ValueClassSpec() extends FlatSpec with MockitoSugar {

  val mockedClass = mock[MockedClass]
  val secondId = SecondId("secondId")

  "Matchers" should "work for value class" in {
    // given
    given(mockedClass.someMethods(any[FirstId], org.mockito.Matchers.eq(secondId))).willReturn(3)
    // when
    val result = mockedClass.someMethods(FirstId("firstId"), secondId)
    // then
    assert(result == 3)
  }

}

and the result is:

ValueClassSpec:
Matchers
- should work for value class *** FAILED ***
  java.lang.NullPointerException:
  at io.scalac.fow.party.ValueClassSpec$$anonfun$1.apply$mcV$sp(ValueClassSpec.scala:22)
  at io.scalac.fow.party.ValueClassSpec$$anonfun$1.apply(ValueClassSpec.scala:20)
  at io.scalac.fow.party.ValueClassSpec$$anonfun$1.apply(ValueClassSpec.scala:20)
  at org.scalatest.Transformer$$anonfun$apply$1.apply(Transformer.scala:22)
  at org.scalatest.Transformer$$anonfun$apply$1.apply(Transformer.scala:22)
  at org.scalatest.OutcomeOf$class.outcomeOf(OutcomeOf.scala:85)
  at org.scalatest.OutcomeOf$.outcomeOf(OutcomeOf.scala:104)
  at org.scalatest.Transformer.apply(Transformer.scala:22)
  at org.scalatest.Transformer.apply(Transformer.scala:20)
  at org.scalatest.FlatSpecLike$$anon$1.apply(FlatSpecLike.scala:1639)
  ...

I found similar question (Scala Value classes and Mockito Matchers don't play together) but without any advice.

Is there any posibility to use mockito matchers with scala value class?

Lib versions: scala 2.11.2, mockito 1.10.8, scalatest 2.1.6


问:
Is there any easy way to determine what factors are contributing to the size of an HTML element?
For example I have a situation where I have something like this (contrived) example:

```<code><div id="outer" style="margin: auto>
    <div id="inner1" style="float: left">content</div>
    <div id="inner2" style="float: left">content</div>
    <div id="inner3" style="float: left">content</div>
    <br style="clear: both"/>
</div>
</code>```

where there are no widths set on any elements, and what I want is #inner1, #inner2 and #inner3 to appear next to each other horizontally inside #outer but what is happening is that #inner1 and #inner2 are appearing next to each other and then #inner3 is wrapping on to the next line.

In the actual page where this is happening there is a lot more going on, but I have inspected all of the elements very carefully with Firebug and do not understand why the #inner3 element is not appearing on the same line as #inner1 and #inner2 and causing #outer to get wider.

So, my question is: Is there any way to determine why the browser is sizing #outer the way it is, or why it is choosing to wrap #inner3 even though there is plenty of room to put it on the previous "line"?  Baring specific solutions to this problem, what tips or techniques do you hardcore HTML/CSS/Web UI guys have for a poor back end developer who has found himself working on the front end?

答:
In Firebug's CSS tab, you can see what style rules apply to a selected elements in the cascading order. This may or may not help you in your problem.

My guess would be that something about the content of #inner3 is causing it to wrap below the first line, and the #outer is just getting sized to accommodate the smaller needed space.

OwnerDisplayName: John

Body:
For example I have a situation where I have something like this (contrived) example:

content

content

content

where there are no widths set on any elements, and what I want is #inner1, #inner2 and #inner3 to appear next to each other horizontally inside #outer but what is happening is that #inner1 and #inner2 are appearing next to each other and then #inner3 is wrapping on to the next line.

In the actual page where this is happening there is a lot more going on, but I have inspected all of the elements very carefully with Firebug and do not understand why the #inner3 element is not appearing on the same line as #inner1 and #inner2 and causing #outer to get wider.

So, my question is: Is there any way to determine why the browser is sizing #outer the way it is, or why it is choosing to wrap #inner3 even though there is plenty of room to put it on the previous "line"?  Baring specific solutions to this problem, what tips or techniques do you hardcore HTML/CSS/Web UI guys have for a poor back end developer who has found himself working on the front end?

LastEditorDisplayName: Chris

OwnerDisplayName: levik


问:
How to create a trigger that wont hold the entire transaction till it complete?
There is a procedure which have insert operation in middle for a table. The table contain a trigger and because of that the entire transaction getting hold. Is there are anyway to make trigger run on separate session and after insert operation procedure runs without waiting for the trigger to complete.

Both procedure and the trigger are

```<code>PRAGMA AUTONOMOUS_TRANSACTION
</code>```

答:
You could try runnig the trigger part as dbms_job ... as follows:

```<code>CREATE OR REPLACE TRIGGER myrigger
AFTER INSERT
ON mytable
REFERENCING NEW AS New OLD AS Old
  FOR EACH ROW
  DECLARE
  l_job number;
  begin
    dbms_job.submit( l_job, 'MYPACKAGE.MYFUNCTION(''' || :new.myField || ''');' );
  END ;
/
</code>```

Body:
There is a procedure which have insert operation in middle for a table. The table contain a trigger and because of that the entire transaction getting hold. Is there are anyway to make trigger run on separate session and after insert operation procedure runs without waiting for the trigger to complete.

Both procedure and the trigger are

PRAGMA AUTONOMOUS_TRANSACTION

Body:
You could try runnig the trigger part as dbms_job ... as follows:

CREATE OR REPLACE TRIGGER myrigger
AFTER INSERT
ON mytable
REFERENCING NEW AS New OLD AS Old
  FOR EACH ROW
  DECLARE
  l_job number;
  begin
    dbms_job.submit( l_job, 'MYPACKAGE.MYFUNCTION(''' || :new.myField || ''');' );
  END ;
/


问:
click button in activity 1 and if the button clicked show textview ... in activity 3
The Title is just a example. In my first Activity i have 2 buttons. If u hit the first Button (Button1) you will visit activity 2.1. But when you hit the second Button(Button2) you will visit Activity 2.2. In activity 3 its neccessary to know which Button the user hitted (Buttonenter code here2 or 1) because they will be different TextViews to show. So how show this different TextViews?

This Code is in Activity 3.

```<code> public void Button1 (View view) {
    TextView txtView = (TextView)findViewById(R.id.nextText);
    if (txtView .getVisibility() == View.VISIBLE)
        txtView.setVisibility(View.VISIBLE);
    else
        txtView.setVisibility(View.VISIBLE);
}

public void Button2 (View view) {
    TextView txtView = (TextView)findViewById(R.id.nextText2);
    if (txtView .getVisibility() == View.VISIBLE)
        txtView.setVisibility(View.VISIBLE);
    else
        txtView.setVisibility(View.VISIBLE);
}
</code>```

答:
On first button click

```<code>Intent intent=new Intent(CurrentActivityName.this, CurrentActivityName3.class);
    intent.putExtra("button_name","button1");
    startActivity(intent);
</code>```

On Second button click

```<code>Intent intent=new Intent(CurrentActivityName.this, CurrentActivityName3.class);
    intent.putExtra("button_name","button2");
    startActivity(intent);
</code>```

In Third Activity:

```<code>try {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            if (bundle.containsKey("button_name")) {

                String button_name = bundle.getString("button_name");
                if(button_name.equalsIgnoreCase("button1")){
                  //do here for button 1 from activity 1

                 }
                  if(button_name.equalsIgnoreCase("button2")){
                 //do here for button 2 from Activity 2.2

                 }
            }
        }
    }catch (Exception e){e.printStackTrace();}
</code>```

Body:
The Title is just a example. In my first Activity i have 2 buttons. If u hit the first Button (Button1) you will visit activity 2.1. But when you hit the second Button(Button2) you will visit Activity 2.2. In activity 3 its neccessary to know which Button the user hitted (Buttonenter code here2 or 1) because they will be different TextViews to show. So how show this different TextViews?

This Code is in Activity 3.

 public void Button1 (View view) {
    TextView txtView = (TextView)findViewById(R.id.nextText);
    if (txtView .getVisibility() == View.VISIBLE)
        txtView.setVisibility(View.VISIBLE);
    else
        txtView.setVisibility(View.VISIBLE);
}

public void Button2 (View view) {
    TextView txtView = (TextView)findViewById(R.id.nextText2);
    if (txtView .getVisibility() == View.VISIBLE)
        txtView.setVisibility(View.VISIBLE);
    else
        txtView.setVisibility(View.VISIBLE);
}

Body:
On first button click

Intent intent=new Intent(CurrentActivityName.this, CurrentActivityName3.class);
    intent.putExtra("button_name","button1");
    startActivity(intent);

On Second button click

Intent intent=new Intent(CurrentActivityName.this, CurrentActivityName3.class);
    intent.putExtra("button_name","button2");
    startActivity(intent);

In Third Activity:

try {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            if (bundle.containsKey("button_name")) {

                String button_name = bundle.getString("button_name");
                if(button_name.equalsIgnoreCase("button1")){
                  //do here for button 1 from activity 1

                 }
                  if(button_name.equalsIgnoreCase("button2")){
                 //do here for button 2 from Activity 2.2

                 }
            }
        }
    }catch (Exception e){e.printStackTrace();}


问:
Python Error (ValueError: _getfullpathname: embedded null character)
I don't know How to fix it please help,  I have tried everything mentioned in the post Error on import matplotlib.pyplot (on Anaconda3 for Windows 10 Home 64-bit PC) but no luck. I'm a newbie to the python and am self learning specific details would greatly be appreciated.

Console:

```<code> Traceback (most recent call last):
     from matplotlib import pyplot
   File "C:\Users\...\lib\site-packages\matplotlib\pyplot.py", line 29, in <module>
     import matplotlib.colorbar
   File "C:\Users\...\lib\site-packages\matplotlib\colorbar.py", line 34, in <module>
     import matplotlib.collections as collections
   File "C:\Users\...\lib\site-packages\matplotlib\collections.py", line 27, in <module>
     import matplotlib.backend_bases as backend_bases
   File "C:\Users\...\lib\site-packages\matplotlib\backend_bases.py", line 62, in <module>
     import matplotlib.textpath as textpath
   File "C:\Users\...\lib\site-packages\matplotlib\textpath.py", line 15, in <module>
     import matplotlib.font_manager as font_manager
   File "C:\Users\...\lib\site-packages\matplotlib\font_manager.py", line 1421, in <module>
     _rebuild()
   File "C:\Users\...\lib\site-packages\matplotlib\font_manager.py", line 1406, in _rebuild
     fontManager = FontManager()
   File "C:\Users\...\lib\site-packages\matplotlib\font_manager.py", line 1044, in __init__
     self.ttffiles = findSystemFonts(paths) + findSystemFonts()
   File "C:\Users\...\lib\site-packages\matplotlib\font_manager.py", line 313, in findSystemFonts
     for f in win32InstalledFonts(fontdir):
   File "C:\Users\...\lib\site-packages\matplotlib\font_manager.py", line 231, in win32InstalledFonts
     direc = os.path.abspath(direc).lower()
   File "C:\Users\...\lib\ntpath.py", line 535, in abspath
     path = _getfullpathname(path)
 ValueError: _getfullpathname: embedded null character
</code>```

Python:

```<code>importing libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

#importing dataset
dataset = pd.read_csv('Position_Salaries.csv')
x = dataset.iloc[:,1:2].values
y = dataset.iloc[:,2].values

#Linear Regression
from sklearn.linear_model import LinearRegression
reg_lin = LinearRegression()
reg_lin = reg_lin.fit(x,y)

#ploynomial Linear Regression
from sklearn.preprocessing import PolynomialFeatures
reg_poly = PolynomialFeatures(degree = 3)
x_poly = reg_poly.fit_transform(x)
reg_poly.fit(x_poly,y)
lin_reg_2 = LinearRegression()
lin_reg_2.fit(x_poly,y)

#Visualizing Linear Regression results
plt.scatter(x,y,color = 'red')
plt.plot(x,reg_lin.predict(x), color = 'blue')
plt.title('Truth vs. Bluff (Linear Reg)')
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()

#Visualizing Polynomial Regression results
plt.scatter(x,y,color = 'red')
plt.plot(x,lin_reg_2.predict(reg_poly.fit_transform(x)), color = 'blue')
plt.title('Truth vs. Bluff (Linear Reg)')
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()
</code>```

答:
The actual cause of the issue appears to be in os.path.abspath(). A better solution might be to edit <python dir>\Lib\ntpaths.py as detailed in Error on import matplotlib.pyplot (on Anaconda3 for Windows 10 Home 64-bit PC)

Basically, add a ValueError: exception handler to the Windows version of the abspath() function. This is lower down on the call stack and could save you from encountering this issue in other places.

Body:
I don't know How to fix it please help,  I have tried everything mentioned in the post Error on import matplotlib.pyplot (on Anaconda3 for Windows 10 Home 64-bit PC) but no luck. I'm a newbie to the python and am self learning specific details would greatly be appreciated.

Console:

 Traceback (most recent call last):
     from matplotlib import pyplot
   File "C:\Users\...\lib\site-packages\matplotlib\pyplot.py", line 29, in <module>
     import matplotlib.colorbar
   File "C:\Users\...\lib\site-packages\matplotlib\colorbar.py", line 34, in <module>
     import matplotlib.collections as collections
   File "C:\Users\...\lib\site-packages\matplotlib\collections.py", line 27, in <module>
     import matplotlib.backend_bases as backend_bases
   File "C:\Users\...\lib\site-packages\matplotlib\backend_bases.py", line 62, in <module>
     import matplotlib.textpath as textpath
   File "C:\Users\...\lib\site-packages\matplotlib\textpath.py", line 15, in <module>
     import matplotlib.font_manager as font_manager
   File "C:\Users\...\lib\site-packages\matplotlib\font_manager.py", line 1421, in <module>
     _rebuild()
   File "C:\Users\...\lib\site-packages\matplotlib\font_manager.py", line 1406, in _rebuild
     fontManager = FontManager()
   File "C:\Users\...\lib\site-packages\matplotlib\font_manager.py", line 1044, in __init__
     self.ttffiles = findSystemFonts(paths) + findSystemFonts()
   File "C:\Users\...\lib\site-packages\matplotlib\font_manager.py", line 313, in findSystemFonts
     for f in win32InstalledFonts(fontdir):
   File "C:\Users\...\lib\site-packages\matplotlib\font_manager.py", line 231, in win32InstalledFonts
     direc = os.path.abspath(direc).lower()
   File "C:\Users\...\lib\ntpath.py", line 535, in abspath
     path = _getfullpathname(path)
 ValueError: _getfullpathname: embedded null character

Python:

importing libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

#importing dataset
dataset = pd.read_csv('Position_Salaries.csv')
x = dataset.iloc[:,1:2].values
y = dataset.iloc[:,2].values

#Linear Regression
from sklearn.linear_model import LinearRegression
reg_lin = LinearRegression()
reg_lin = reg_lin.fit(x,y)

#ploynomial Linear Regression
from sklearn.preprocessing import PolynomialFeatures
reg_poly = PolynomialFeatures(degree = 3)
x_poly = reg_poly.fit_transform(x)
reg_poly.fit(x_poly,y)
lin_reg_2 = LinearRegression()
lin_reg_2.fit(x_poly,y)

#Visualizing Linear Regression results
plt.scatter(x,y,color = 'red')
plt.plot(x,reg_lin.predict(x), color = 'blue')
plt.title('Truth vs. Bluff (Linear Reg)')
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()

#Visualizing Polynomial Regression results
plt.scatter(x,y,color = 'red')
plt.plot(x,lin_reg_2.predict(reg_poly.fit_transform(x)), color = 'blue')
plt.title('Truth vs. Bluff (Linear Reg)')
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()


问:
My values are not being inserted into database using this command
```<code>$sql="INSERT INTO prescription
      (username,phone,procedure,address,emailid,reviews,followups,nextappointment)
      VALUES
      ("$username","$phone","$procedure","$address","$emailid","$reviews",$followups,"$nextappointment")";
</code>```

答:
your inverted commas are wrong,
use single quote ('') in values,
you get error on your IDE. or if you just copy and run on DB.</p>

```<code>$sql = "INSERT INTO prescription(username,phone,procedure,address,emailid,reviews,followups,nextappointment)VALUES('$usernam','$phone','$procedure','$address','$emailid','$reviews','$followups','$nextappointment')";
</code>```

Body:
your inverted commas are wrong,
use single quote ('') in values,
you get error on your IDE. or if you just copy and run on DB.

$sql = "INSERT INTO prescription(username,phone,procedure,address,emailid,reviews,followups,nextappointment)VALUES('$usernam','$phone','$procedure','$address','$emailid','$reviews','$followups','$nextappointment')";


问:
SQL: How to return any Part that occurs more than Once
I have the following query which returns the following error:
An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.

SELECT Part from Parts Where count(Part) > 1

How could i rewrite it to return the part that appears more than once.

答:
try this:

select part from parts group by part having count(part) > 1


问:
Update state when user press back button in React Native
I use react-navigation for manage routes. This is my Home component:

```<code>class HomeScreen extends React.Component {
   constructor(props) {
      this.state = {
         userProfile: {
            firstname: 'John',
            avatar: 'john-profile.png',
            location: 'Canada',
         }
      }
   }

   componentDidMount() {
      AsyncStorage.getItem('userProfile', (errs, result) => {
         this.setState({userProfile: JSON.parse(result)});
      });
   }

   render() {
      return (
         <View>
            <Image src="{this.state.userProfile.avatar}" />
            <Text>Firstname: {this.state.userProfile.firstname}</Text>
            <Text>Location: {this.state.userProfile.location}</Text>
         </View>
      );
   }
}
</code>```

And this is the Profile screen:

```<code>class ProfileScreen extends React.Component {
   constructor(props) {
      this.state = {
         userProfile: null,
      }
   }

   componentDidMount() {
      AsyncStorage.getItem('userProfile', (errs, result) => {
         this.setState({userProfile: JSON.parse(result)});
      });
   }

   save() {

      var userSavedProfile = this.state.userProfile;

      userSavedProfile.firstname = "Peter";
      userSavedProfile.avatar = "peter-avatar.png";
      userSavedProfile.location = "EEUU";

      this.setState({userProfile: userSavedProfile});

      AsyncStorage.setItem('userProfile',     JSON.stringify(this.state.userProfile), () => {});

   }

   render() {
      return (
         <View>
            <Button title="Save" onPress={() => this.save()}  />
         </View>
      );
   }
}
</code>```

When I save the new user information and I press back button in header (react-navigation) the user profile is old, firstname = John, etc... How update state from Home when user press back button and refresh data?

答:
You can use BackHandler from react-native
https://facebook.github.io/react-native/docs/backhandler.html
You can change state inside function of backhandler

Body:
I use react-navigation for manage routes. This is my Home component:

class HomeScreen extends React.Component {
   constructor(props) {
      this.state = {
         userProfile: {
            firstname: 'John',
            avatar: 'john-profile.png',
            location: 'Canada',
         }
      }
   }

   componentDidMount() {
      AsyncStorage.getItem('userProfile', (errs, result) => {
         this.setState({userProfile: JSON.parse(result)});
      });
   }

   render() {
      return (
         <View>
            <Image src="{this.state.userProfile.avatar}" />
            <Text>Firstname: {this.state.userProfile.firstname}</Text>
            <Text>Location: {this.state.userProfile.location}</Text>
         </View>
      );
   }
}

And this is the Profile screen:

class ProfileScreen extends React.Component {
   constructor(props) {
      this.state = {
         userProfile: null,
      }
   }

   componentDidMount() {
      AsyncStorage.getItem('userProfile', (errs, result) => {
         this.setState({userProfile: JSON.parse(result)});
      });
   }

   save() {

      var userSavedProfile = this.state.userProfile;

      userSavedProfile.firstname = "Peter";
      userSavedProfile.avatar = "peter-avatar.png";
      userSavedProfile.location = "EEUU";

      this.setState({userProfile: userSavedProfile});

      AsyncStorage.setItem('userProfile',     JSON.stringify(this.state.userProfile), () => {});

   }

   render() {
      return (
         <View>
            <Button title="Save" onPress={() => this.save()}  />
         </View>
      );
   }
}

When I save the new user information and I press back button in header (react-navigation) the user profile is old, firstname = John, etc... How update state from Home when user press back button and refresh data?


问:
JavaScript classList not working while clicking a button
I am currently creating a dropdown menu so I want the menu to be displayed when clicked by adding class via Javascript but classList is not working at all. I tried lots of time but couldn't. Also if i add style.display = "block", then it works! I am unable to figure out! Please Help me!

document.getElementById('dbtn').addEventListener('click', function() {
  document.getElementById('d-content').classList.toggle('show');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#wrapper {
  position: relative;
  display: inline-block;
}

#dbtn {
  background-color: #F44336;
  font-size: 27px;
  font-family: 'Droid Sans', sans-serif;
  border: none;
  padding: 0.3em 0.6em;
  color: #FFFFFF;
  cursor: pointer;
  outline: none;
}

#d-content {
  position: absolute;
  display: none;
  background-color: #F44336;
  font-family: 'Droid Sans', sans-serif;
  font-size: 22px;
  border-top: 2px solid #FFFFFF;
  z-index: 1;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
}

#d-content a {
  color: #FFFFFF;
  text-decoration: none;
  display: block;
  padding: 0.3em 5em 0.3em 0.3em;
}

#d-content a:hover {
  background-color: darkorchid;
}

.show {
  display: block;
}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Dropdown Menu</title>

    <input type="button" id="dbtn" value="Select..." />

      USA
      Canada
      Europe

```

答:
Browser calculates css properties based on selectors order and selectors weight. In your case #id selector overrides your class selector.

```<code>.show {
    display: block !important;
}
</code>```

Or it's better not to use important at all:

```<code>#d-content.show{
    display: block ;
}
</code>```

You can read more about selectors weight here. Also you can alaways check those kind of things in dev console.

Body:
I am currently creating a dropdown menu so I want the menu to be displayed when clicked by adding class via Javascript but classList is not working at all. I tried lots of time but couldn't. Also if i add style.display = "block", then it works! I am unable to figure out! Please Help me!

document.getElementById('dbtn').addEventListener('click', function() {
  document.getElementById('d-content').classList.toggle('show');
});

#wrapper {
  position: relative;
  display: inline-block;
}

#dbtn {
  background-color: #F44336;
  font-size: 27px;
  font-family: 'Droid Sans', sans-serif;
  border: none;
  padding: 0.3em 0.6em;
  color: #FFFFFF;
  cursor: pointer;
  outline: none;
}

#d-content {
  position: absolute;
  display: none;
  background-color: #F44336;
  font-family: 'Droid Sans', sans-serif;
  font-size: 22px;
  border-top: 2px solid #FFFFFF;
  z-index: 1;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
}

#d-content a {
  color: #FFFFFF;
  text-decoration: none;
  display: block;
  padding: 0.3em 5em 0.3em 0.3em;
}

#d-content a:hover {
  background-color: darkorchid;
}

.show {
  display: block;
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Dropdown Menu</title>

    <input type="button" id="dbtn" value="Select..." />

      USA
      Canada
      Europe

Body:
Browser calculates css properties based on selectors order and selectors weight. In your case #id selector overrides your class selector.

.show {
    display: block !important;
}

Or it's better not to use important at all:

#d-content.show{
    display: block ;
}

You can read more about selectors weight here. Also you can alaways check those kind of things in dev console.


答:
Check Your Insert Into Query:

```<code>$sql = "INSERT INTO prescription (username,phone,procedure,address,emailid,reviews,followups,nextappointment)
                               VALUES('$username','$phone','$procedure','$address','$emailid','$reviews',$followups,'$nextappointment')";
</code>```

NOTE: Check THis :  https://www.w3schools.com/sql/sql_insert.asp

Title: My values are not being inserted into database using this command

Body:
$sql="INSERT INTO prescription
      (username,phone,procedure,address,emailid,reviews,followups,nextappointment)
      VALUES
      ("$username","$phone","$procedure","$address","$emailid","$reviews",$followups,"$nextappointment")";

Body:
Check Your Insert Into Query:

$sql = "INSERT INTO prescription (username,phone,procedure,address,emailid,reviews,followups,nextappointment)
                               VALUES('$username','$phone','$procedure','$address','$emailid','$reviews',$followups,'$nextappointment')";

NOTE: Check THis :  https://www.w3schools.com/sql/sql_insert.asp


答:
use a tag in textview android:Tag="1" for first button and android:Tag="2" for second .if user click on the button get the tag  using txtView.getTag() and , in third activity sent the tag using Intent intent=new Intent();
intent.putExtra("tag",tagHere);
startActivity(....);

and receive it there in third activity  using    String value = getIntent().getExtras().getString("tag");```

Title: click button in activity 1 and if the button clicked show textview ... in activity 3


问:
check in procedure in Visual Studio's Team System
In my team we're using Visual Studio's Team System as our source control.
I'd like to add some sort of a check in procedure, i.e., compiling the whole code before actually checking it in, and if the code does not compile, do not allow the check in.
I've googled the issue but probably used wrong keywords.
I'd appreciate your help.

Thanks

答: Team Foundation Server 2010 supports gated builds.  That means you can shelve your changes in TFS, and have the build process check them in only when a build succeeds including those changes.</p>


问:
How can I split WAV into smaller WAV files?
I have an android application, which records WAV files. This files can be up to 3 minutes long, but I need to split them by 30 seconds (This smaller WAV's must be playable too). I don't really care if it is splitted on a silent moment or not. Is there any way to do it?</p>

答:
You can use AudioInputStream and its AudioFileFormat member (which contains an AudioFormat instance) to know what to write (format, sample rate), you can use AudioSystem to write it.

Based on the sample rate of the format you can find out how many bytes of audio are 30 seconds, and go on a loop of reading that many bytes from the AudioInputStream, writing them to a new file.


问:
How to effectly implement AddRange() for a WPF ListView SelectedItems?
I have a ListView and I wanted to add some new items to its ListView.SelectedItems.
I was using a slow approach:

```<code>for (int i = beginIndex; i <= endIndex; i++)
{
    myListView.SelectedItems.Add(myObjectList[i]);
}
</code>```

If myListView is empty before add, I could use this answer to add selected items. But in case myListView already has some SelectedItems, and I want to add more, I cannot use ListView.SetSelectedItems().

How can I add selected items more effectively? Is there an AddRange() function or a similar method?

答:
Is there an AddRange() function or a similar method?

No.

The SelectedItems property of a ListView returns an instance of the internal type SelectedItemCollection and this one has no AddRange() method.

But even it there actually was an AddRange() method, what do you think it would do? It would certainly loop over the IEnumerable that you pass to it somehow.

There is no more efficient way of iterating through items.

Body:
I have a ListView and I wanted to add some new items to its ListView.SelectedItems.
I was using a slow approach:

for (int i = beginIndex; i <= endIndex; i++)
{
    myListView.SelectedItems.Add(myObjectList[i]);
}

If myListView is empty before add, I could use this answer to add selected items. But in case myListView already has some SelectedItems, and I want to add more, I cannot use ListView.SetSelectedItems().

How can I add selected items more effectively? Is there an AddRange() function or a similar method?


问:
SQL error: An expression of non-boolean type specified in a context where a condition is expected, near ')'
I'm new to SQL and can't get this to work:

```<code>select z.[zip] as [ZIP],
z.[city] as [City],
z.[state] as [State],
z.[county] as [County],
lp.[value] as [Geomarket Short],
lp2.[value] as [Geomarket Long]
from world.dbo.[zip] z
left outer join [lookup.prompt] lp on (lp.[index] = z.[zip]) and (lp.[key] =
'geomarket_zip')
left outer join [lookup.prompt] lp2 on (lp.[value] = lp2.[index]) and (lp2.
[key] = 'geomarket')
order by z.[zip]
</code>```

I get this error:

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.

When I remove the order by clause, I get this error:

An expression of non-boolean type specified in a context where a condition is expected, near ')'.

答:
```<code>SELECT  z.zip AS [ZIP] ,
        z.city AS [City] ,
        z.state AS [State] ,
        z.county AS [County] ,
        lp.value AS [Geomarket Short] ,
        lp2.value AS [Geomarket Long]
FROM    world.dbo.zip z
        LEFT OUTER JOIN [lookup.prompt] lp ON lp.index = z.zip
                                              AND lp.key = 'geomarket_zip'
        LEFT OUTER JOIN [lookup.prompt] lp2 ON lp.value = lp2.index
                                               AND lp2.key = 'geomarket'
ORDER BY z.zip;
</code>```

Body:
I'm new to SQL and can't get this to work:

select z.[zip] as [ZIP],
z.[city] as [City],
z.[state] as [State],
z.[county] as [County],
lp.[value] as [Geomarket Short],
lp2.[value] as [Geomarket Long]
from world.dbo.[zip] z
left outer join [lookup.prompt] lp on (lp.[index] = z.[zip]) and (lp.[key] =
'geomarket_zip')
left outer join [lookup.prompt] lp2 on (lp.[value] = lp2.[index]) and (lp2.
[key] = 'geomarket')
order by z.[zip]

I get this error:

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.

When I remove the order by clause, I get this error:

An expression of non-boolean type specified in a context where a condition is expected, near ')'.


答:
I think your problem is in the quotes, you have double quotes inside double quotes, you should escape the quotes or use single quotes.

The easy and simple thing is to use prepared statements.

I'm not sure which API you using PDO/MSQLI

if you in PDO :

```<code><?php

$sql =$databaseConnectionVar->prepare("INSERT INTO prescription(username,phone,procedure,address,emailid,reviews,followups,nextappointment)VALUES(?,?,?,?,?,?,?,?)")
        ->execute(array($username,$phone,$procedure,$address,$emailid,$reviews,$followups,$nextappointment));

if(!$sql){

    print_r($databaseConnectionVar->errorInfo());
}else{

    echo "data inserted";
}
?>
</code>```

if you are on mysqli then :

```<code><?php

$sql =$databaseConnectionVar->prepare("INSERT INTO prescription(username,phone,procedure,address,emailid,reviews,followups,nextappointment)VALUES(?,?,?,?,?,?,?,?)");
$sql->bind_Param("ssssssss",$username,$phone,$procedure,$address,$emailid,$reviews,$followups,$nextappointment);

if($sql->execute()){

    echo "data inserted";
}else{

    echo "Error : ". $databaseConnectionVar->error;
}
?>
</code>```

Then important links you need to look at :

How to get mysqli error in different environments?

When to use single quotes, double quotes, and backticks in MySQL

When should I use prepared statements?

Prepared Statements

Hope this will point you to the right path.

Body:
I think your problem is in the quotes, you have double quotes inside double quotes, you should escape the quotes or use single quotes.

The easy and simple thing is to use prepared statements.

I'm not sure which API you using PDO/MSQLI

if you in PDO :

<?php

$sql =$databaseConnectionVar->prepare("INSERT INTO prescription(username,phone,procedure,address,emailid,reviews,followups,nextappointment)VALUES(?,?,?,?,?,?,?,?)")
        ->execute(array($username,$phone,$procedure,$address,$emailid,$reviews,$followups,$nextappointment));

if(!$sql){

    print_r($databaseConnectionVar->errorInfo());
}else{

    echo "data inserted";
}
?>

if you are on mysqli then :

<?php

$sql =$databaseConnectionVar->prepare("INSERT INTO prescription(username,phone,procedure,address,emailid,reviews,followups,nextappointment)VALUES(?,?,?,?,?,?,?,?)");
$sql->bind_Param("ssssssss",$username,$phone,$procedure,$address,$emailid,$reviews,$followups,$nextappointment);

if($sql->execute()){

    echo "data inserted";
}else{

    echo "Error : ". $databaseConnectionVar->error;
}
?>

Then important links you need to look at :

How to get mysqli error in different environments?

When to use single quotes, double quotes, and backticks in MySQL

When should I use prepared statements?

Prepared Statements

Hope this will point you to the right path.


问:
Select first letter from firstname only
I have been battling with this for a while now can anyone offer a solution to this.
I want to only show results where the first letter of firstname is "blah".

```<code>$n=$_GET['n'];

("SELECT * FROM my_list
                    WHERE setid = '16-17'
                    and firstname like '$n%'
                    order by studentid asc")
</code>```

The above is what is have so far but shows no results at all.

thanks all

答:
```<code>    $n = $_GET['n'];

    $value = $n[0]; // will give first letter

    ("SELECT * FROM my_list WHERE setid = '16-17'and
firstname like '". $value ."%' order by studentid asc")
</code>```

Title: Select first letter from firstname only

Body:
I have been battling with this for a while now can anyone offer a solution to this.
I want to only show results where the first letter of firstname is "blah".

$n=$_GET['n'];

("SELECT * FROM my_list
                    WHERE setid = '16-17'
                    and firstname like '$n%'
                    order by studentid asc")

The above is what is have so far but shows no results at all.

thanks all