问:
In Fragment getActivity() sometimes return null
Android Studio 3.4

```<code>public class SubscribesFragment extends Fragment {

    @Override
    protected void initLogic() {
        IntentFilter intentFilterRefusePaperInvoice = new IntentFilter(ExistSubscribeWidget.ACTION_REFUSE_PAPER_INVOICE);
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mMessageReceiver,
                intentFilterRefusePaperInvoice);

        super.initLogic();
    }

    private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, final Intent intent) {
            String action = intent.getAction();
            if (action.equals(ExistSubscribeWidget.ACTION_REFUSE_PAPER_INVOICE)) {
                String providerGUID = intent.getStringExtra(ProviderWidget.EXTRA_PROVIDER_TAG);
                String notificationSubscribeOwnerKey = intent.getStringExtra(ExistSubscribeWidget.NOTIFICATION_SUBSCRIBE_OWNERkEY);
                showConfirmDialogRefusePaperInvoice(providerGUID, notificationSubscribeOwnerKey);
            }
        }
    };

    private void showConfirmDialogRefusePaperInvoice(final String providerGUID, final String notificationSubscribeOwnerKey) {
        Activity actitivty = getActivity(); // NULL
        AlertDialog.Builder builder = new AlertDialog.Builder(actitivty); // NPE
        builder.setTitle(R.string.refuse_paper_dialog_title);
        View customView = AndroidUtil.getLinearLayout(actitivty, R.layout.refuse_paper_dialog);
builder.setView(customView);

}
</code>```

But sometimes (not every time) in method showConfirmDialogRefusePaperInvoice the app crash with NPE:

```<code> FATAL EXCEPTION: main
 Process: com.myproject.app, PID: 19430
 java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
    at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:222)
    at android.app.AlertDialog$Builder.<init>(AlertDialog.java:452)
    at com.myproject.app.fragment.SubscribesFragment.showConfirmDialogRefusePaperInvoice(SubscribesFragment.java:67)
    at com.myproject.app.fragment.SubscribesFragment.access$000(SubscribesFragment.java:38)
    at com.myproject.app.fragment.SubscribesFragment$1.onReceive(SubscribesFragment.java:60)
    at android.support.v4.content.LocalBroadcastManager.executePendingBroadcasts(LocalBroadcastManager.java:313)
    at android.support.v4.content.LocalBroadcastManager$1.handleMessage(LocalBroadcastManager.java:121)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

答:
just put a context, this is a better approach inside fragment to getContext</p>

```<code>  AlertDialog.Builder builder = new AlertDialog.Builder(mInflatedView.getContext);

where, mInflatedView = inflater.inflate(R.layout.fragment, container, false);
</code>```

Body:
Android Studio 3.4

public class SubscribesFragment extends Fragment {

    @Override
    protected void initLogic() {
        IntentFilter intentFilterRefusePaperInvoice = new IntentFilter(ExistSubscribeWidget.ACTION_REFUSE_PAPER_INVOICE);
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mMessageReceiver,
                intentFilterRefusePaperInvoice);

        super.initLogic();
    }

    private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, final Intent intent) {
            String action = intent.getAction();
            if (action.equals(ExistSubscribeWidget.ACTION_REFUSE_PAPER_INVOICE)) {
                String providerGUID = intent.getStringExtra(ProviderWidget.EXTRA_PROVIDER_TAG);
                String notificationSubscribeOwnerKey = intent.getStringExtra(ExistSubscribeWidget.NOTIFICATION_SUBSCRIBE_OWNERkEY);
                showConfirmDialogRefusePaperInvoice(providerGUID, notificationSubscribeOwnerKey);
            }
        }
    };

    private void showConfirmDialogRefusePaperInvoice(final String providerGUID, final String notificationSubscribeOwnerKey) {
        Activity actitivty = getActivity(); // NULL
        AlertDialog.Builder builder = new AlertDialog.Builder(actitivty); // NPE
        builder.setTitle(R.string.refuse_paper_dialog_title);
        View customView = AndroidUtil.getLinearLayout(actitivty, R.layout.refuse_paper_dialog);
builder.setView(customView);

}

But sometimes (not every time) in method showConfirmDialogRefusePaperInvoice the app crash with NPE:

 FATAL EXCEPTION: main
 Process: com.myproject.app, PID: 19430
 java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
    at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:222)
    at android.app.AlertDialog$Builder.<init>(AlertDialog.java:452)
    at com.myproject.app.fragment.SubscribesFragment.showConfirmDialogRefusePaperInvoice(SubscribesFragment.java:67)
    at com.myproject.app.fragment.SubscribesFragment.access$000(SubscribesFragment.java:38)
    at com.myproject.app.fragment.SubscribesFragment$1.onReceive(SubscribesFragment.java:60)
    at android.support.v4.content.LocalBroadcastManager.executePendingBroadcasts(LocalBroadcastManager.java:313)
    at android.support.v4.content.LocalBroadcastManager$1.handleMessage(LocalBroadcastManager.java:121)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Body:
just put a context, this is a better approach inside fragment to getContext

  AlertDialog.Builder builder = new AlertDialog.Builder(mInflatedView.getContext);

where, mInflatedView = inflater.inflate(R.layout.fragment, container, false);


来源: stackexchange

问:
Pass a string to RGB Colour format
I have a dict like this:

```<code>colour_dict={'Red': '0xFF, 0x00, 0x00','Green':'0x00, 0xFF, 0x00','White':'0xFF, 0xFF, 0xFF','Yellow':'0xff, 0xff, 0x00'}
</code>```

I need to pass value of this dict to this code and it works right:

```<code>from pptx.dml.color import RGBColor
RGBColor(0xFF, 0x00, 0x00)
</code>```

When I do below to achieve the same:

```<code>RGBColor(colour_dict["Red"])
</code>```

It throws me an error as this is a string and this just want in straight number format.

I already tried converting this string to int format but nothing is working.

Overall  Problem:

How to pass the value to RGBColor using dict?

答:
colour_dict["Red"] is a string, not three numbers

you can do like this:

```<code>a = list(colour_dict["Red"])
RGBColor(int(a[0]), int(a[2]), int(a[4]))
</code>```

a:['0xFF', ',', '0x00', ',', '0x00'], has 5 characters in total

ContentLicense: CC BY-SA 4.0

Title: Pass a string to RGB Colour format

Body:
I have a dict like this:

colour_dict={'Red': '0xFF, 0x00, 0x00','Green':'0x00, 0xFF, 0x00','White':'0xFF, 0xFF, 0xFF','Yellow':'0xff, 0xff, 0x00'}

I need to pass value of this dict to this code and it works right:

from pptx.dml.color import RGBColor
RGBColor(0xFF, 0x00, 0x00)

When I do below to achieve the same:

RGBColor(colour_dict["Red"])

It throws me an error as this is a string and this just want in straight number format.

I already tried converting this string to int format but nothing is working.

Overall  Problem:

How to pass the value to RGBColor using dict?

Body:
colour_dict["Red"] is a string, not three numbers

you can do like this:

a = list(colour_dict["Red"])
RGBColor(int(a[0]), int(a[2]), int(a[4]))

a:['0xFF', ',', '0x00', ',', '0x00'], has 5 characters in total


问:
How to extract lower and upper bound in numeric format from a confidence interval string?
Suppose a vector including some confidence intervals as below

```<code>confint <- c("[0.741 ; 2.233]", "[263.917 ; 402.154]", "[12.788 ; 17.975]", "[0.680 ; 2.450]", "[0.650 ; 1.827]", "[0.719 ; 2.190]")
</code>```

I want to have two new vectors one including the lower Limits in numeric format as

```<code>lower <- c(0.741, 263.917, 12.788, 0.680, 0.650 , 0.719)
</code>```

and othe including the upper Limits in numeric format like

```<code>upper <- c(2.233, 402.154, 17.975, 2.450, 1.827, 2.190)
</code>```

答:
You can use functions from the stringr library.

You can split strings with str_split() according a specific character (; in your case), then remove character with str_remove() ([ and ] in your case) and you will obtain what you want.

```<code>str_remove(str_split_fixed(confint, ";", n = 2)[,1], '\\[') %>% as.numeric()
# [1]   0.741 263.917  12.788   0.680   0.650   0.719
</code>```

Body:
Suppose a vector including some confidence intervals as below

confint <- c("[0.741 ; 2.233]", "[263.917 ; 402.154]", "[12.788 ; 17.975]", "[0.680 ; 2.450]", "[0.650 ; 1.827]", "[0.719 ; 2.190]")

I want to have two new vectors one including the lower Limits in numeric format as

lower <- c(0.741, 263.917, 12.788, 0.680, 0.650 , 0.719)

and othe including the upper Limits in numeric format like

upper <- c(2.233, 402.154, 17.975, 2.450, 1.827, 2.190)

Body:
You can use functions from the stringr library.

You can split strings with str_split() according a specific character (; in your case), then remove character with str_remove() ([ and ] in your case) and you will obtain what you want.

str_remove(str_split_fixed(confint, ";", n = 2)[,1], '\\[') %>% as.numeric()
# [1]   0.741 263.917  12.788   0.680   0.650   0.719


问:
react native how to pass a state to all children
```<code>    import {
    ImageBackground
} from 'react-native';

export const CustomContext = React.createContext(1);
export default class MainBackGround extends React.Component {
    state ={
        lang:'en'
    }
    render() {
        return (
            <CustomContext.Provider value={this.state.lang}>
                <ImageBackground>
                    { this.props.children }
                </ImageBackground>
            </CustomContext.Provider>
        )
    }
}
</code>```

child component

```<code>import MainBackground, {CustomContext} from '../components/MainBackground';
export default class MyChildComponent extends React.Component {

    render() {
        return (
                <CustomContext.Consumer>
                { value => (
                <ScrollView >
                    <Text>{value}</Text>
                </ScrollView>
                )}
                </CustomContext.Consumer>
        );
    }
}
</code>```

How can I pass state a to all the children?

I just update the code closer to my real code

problem I'm getting value as 1 instead of en ( the  is showing 1 instead en)

答:
The context API might be what you're looking for. It's designed to share data between many, often deeply nested components. This provides an alternative to prop drilling.

This removes the need for you to drill down props, so in my example I have replaced your state field, with the creation of a react context.

Note that this does create coupling between components, thus can lead to the components being hard to reuse.

Untested example below.

```<code>import React from "react";

// Create a context, you'd probably place this in a /contexts
// folder, i.e. not in the component file itself.

//Note we're passing in a default value, I took 1 from your
// state field.
export const CustomContext = React.createContext(1);

export default class MainBackGround extends React.Component {

    render() {

        // All children can have access to the context variable,
        // by utilising CustomContext.Consumer.

        // Note, you can override the default value of 1
        // and pass a 'value' prop to the CustomContext.Provider
        // below, e.g. <CustomContext.Provider value={5}>
        return (
            <CustomContext.Provider>
                { this.props.children }
            </CustomContext.Provider>
        )
    }
}
</code>```

Then in one of your children

```<code>import React from "react";
import {Text} from "react-native";

// This is the context created in the above example.
import CustomContext from "./where you saved it.";

export default class SomeChildComponent extends React.Component {

    render () {
        // '1' will be rendered in the Text element
        // as 1 was given as the default value of the context.
        return (
            <CustomContext.Consumer>
                {value => (
                    <Text>
                        {value}
                    </Text>
                )}
            </CustomContext.Consumer>
        );
    }
}
</code>```

Note this is of course less expensive than the previous answer, which could be especially useful if you have many children. I.e. your are not cloning every child.

The example i've given is very barebones, it utilises the default value you provide to the context API. You can change the value defined in the Context Provider.

E.g.

```<code>export const CustomContext = React.createContext(1);

export default class MainBackGround extends React.Component {

    render() {
        return (
            <CustomContext.Provider value={5}>
                { this.props.children }
            </CustomContext.Provider>
        )
    }
}
</code>```

This would then print 5 in the child component in my original example, i.e. we are not relying on the default value given when creating the new context.

In short, first example omitted the 'value' prop you can pass to the Context.Provider element, as this is optional, the default value will be provided in this instance.

Alternative

As an alternative, I would advise a state management library like Redux.

Body:
    import {
    ImageBackground
} from 'react-native';

export const CustomContext = React.createContext(1);
export default class MainBackGround extends React.Component {
    state ={
        lang:'en'
    }
    render() {
        return (
            <CustomContext.Provider value={this.state.lang}>
                <ImageBackground>
                    { this.props.children }
                </ImageBackground>
            </CustomContext.Provider>
        )
    }
}

child component

import MainBackground, {CustomContext} from '../components/MainBackground';
export default class MyChildComponent extends React.Component {

    render() {
        return (
                <CustomContext.Consumer>
                { value => (
                <ScrollView >
                    <Text>{value}</Text>
                </ScrollView>
                )}
                </CustomContext.Consumer>
        );
    }
}

How can I pass state a to all the children?

I just update the code closer to my real code

problem I'm getting value as 1 instead of en ( the  is showing 1 instead en)

Body:
The context API might be what you're looking for. It's designed to share data between many, often deeply nested components. This provides an alternative to prop drilling.

This removes the need for you to drill down props, so in my example I have replaced your state field, with the creation of a react context.

Note that this does create coupling between components, thus can lead to the components being hard to reuse.

Untested example below.

import React from "react";

// Create a context, you'd probably place this in a /contexts
// folder, i.e. not in the component file itself.

//Note we're passing in a default value, I took 1 from your
// state field.
export const CustomContext = React.createContext(1);

export default class MainBackGround extends React.Component {

    render() {

        // All children can have access to the context variable,
        // by utilising CustomContext.Consumer.

        // Note, you can override the default value of 1
        // and pass a 'value' prop to the CustomContext.Provider
        // below, e.g. <CustomContext.Provider value={5}>
        return (
            <CustomContext.Provider>
                { this.props.children }
            </CustomContext.Provider>
        )
    }
}

Then in one of your children

import React from "react";
import {Text} from "react-native";

// This is the context created in the above example.
import CustomContext from "./where you saved it.";

export default class SomeChildComponent extends React.Component {

    render () {
        // '1' will be rendered in the Text element
        // as 1 was given as the default value of the context.
        return (
            <CustomContext.Consumer>
                {value => (
                    <Text>
                        {value}
                    </Text>
                )}
            </CustomContext.Consumer>
        );
    }
}

Note this is of course less expensive than the previous answer, which could be especially useful if you have many children. I.e. your are not cloning every child.

The example i've given is very barebones, it utilises the default value you provide to the context API. You can change the value defined in the Context Provider.

E.g.

export const CustomContext = React.createContext(1);

export default class MainBackGround extends React.Component {

    render() {
        return (
            <CustomContext.Provider value={5}>
                { this.props.children }
            </CustomContext.Provider>
        )
    }
}

This would then print 5 in the child component in my original example, i.e. we are not relying on the default value given when creating the new context.

In short, first example omitted the 'value' prop you can pass to the Context.Provider element, as this is optional, the default value will be provided in this instance.

Alternative

As an alternative, I would advise a state management library like Redux.


问:
CSS margin issue with DIV ids
In my below code, I am facing below problems div expenses_div. I have added margin-top:3%; for it, but somehow its not working.

Also, expenses_div is inside container_input. but expenses_div width is more than the one set for container_input (60% of page width). I am not able to understand the issue with expenses_div.

Can someone please guide me here

.expenses_wrapper
{
 width:100%;
 text-align:center;
 margin:auto;
 margin-top:50px;
}

.expenses_banner
{
 width:100% !important;
 background-color:black;
 position: relative;
 text-align:center;
 color:white;
 padding:5px;
 overflow:hidden !important;
 font-family: "Montserrat",sans-serif !important;
 font-size:20px;
 position:fixed;
 z-index: 105 !important;
}

.container_input
{
width:100%;
margin-top:5%;
text-align:center;
margin:auto;
}

.expenses_main_head
{
 width:60%;
 text-align:center;
 padding-top:80px;
 margin:auto;
}

.expenses_div
{
width:100% !important;
margin:auto;
margin-top:3%;
}

.expenses_div_left
{
height:40px;
line-height:40px;
background-color:black;
float:left;
display: inline-block;
text-align:left;
padding-left:12px;
color:white;
width:48%;
font-size: 14px !important;
font-family : "Montserrat",sans-serif !important;
}

.expenses_div_right
{
height: 40px !important;
line-height: 40px !important;
width:48%;
float:left;
display: inline-block;
cursor:pointer;
background:transparent !important;
position:relative;/*Added (Because :after should be relative to this not whole page! )*/
}

.expenses_div_right select
{
font-family : "Montserrat",sans-serif !important;
background:transparent !important;
appearance:none !important;
-moz-appearance:none !important;
-webkit-appearance:none !important;
box-sizing: border-box !important;
border: 1px solid black !important;
width:100%!important;
color:black !important;
height:40px;
text-align:left !important;
font-size: 14px !important;
outline: none;
position: relative !important;
cursor:pointer;
padding-left:12px;
z-index:2;
}

.expenses_div_right:after
{
content: '< >';
font: 16px "Consolas", monospace;
font-weight:bold;
color: white;
background-color:black;
display:inline-block;
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
position: absolute;/*Changed to absolute*/
top:0;/*Added*/
right:0;/*Added*/
width:40px;
height:40px;
text-align:center;
line-height:40px;
overflow:hidden !important;
cursor:pointer;
z-index :1 ;/*Added ( For Your 2nd Question )*/
}

.expenses_input
{
height:40px !important;
line-height: 40px !important;
border: 1px solid black !important;
font-family : "Montserrat",sans-serif !important;
outline: none !important;
width:100%!important;
text-align:right;
display: inline-block;
font-size: 14px !important;
cursor:pointer;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box !important;
-moz-appearance: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="expenses_wrapper" class="expenses_wrapper" >
<div id="expenses_banner" class="expenses_banner" >Tracker</div>

<div class="container_input" id="container_input"  >
 <div class="expenses_main_head">
  <div class="expenses_div_left" >How to Proceed</div>
  <div id="expenses_div_right" class="expenses_div_right" >
   <select name="expense_main_selection"  id="expense_main_selection" >
    <option selected value="">Select an option</option>
    <option value="new_data">New Data</option>
    <option value="analize_data">Analyze Data</option>
    <option value="refresh_data">Refresh Data</option>
   </select>
  </div>
 </div>

 <div id="expenses_input_date" class="expenses_div" >
  <div class="expenses_div_left" >Date</div>
  <div class="expenses_div_right" ><input type="text" class="expenses_input" id="expenses_input_date" name="expenses_input_date" autocomplete="off"></div>
 </div>

 <div id ="expenses_select_account" class="expenses_div" >
  <div class="expenses_div_left" >Select Account</div>
  <div id="expenses_div_right" class="expenses_div_right" >
   <select name="select_account" id="select_account_select">
    <option selected value="">Select Account</option>
    <option value="Opt1">Opt1</option>
    <option value="Opt2">Opt2</option>
   </select>
  </div>
 </div>

</div>

</div></code>```

答:
Add clear:both when you use float, Parent div is not taking height when you use float, so use clear:both to clear it.

The clear property is directly related to floats. If the element can fit horizontally in the space next to another element which is floated, it will. Unless you apply clear to that element in the same direction as the float. Then the element will move down below the floated element.

It's probably best practise to keep the names different of class and id purely for code readability, but there's no issue being same.

.expenses_wrapper
{
 width:100%;
 text-align:center;
 margin:auto;
 margin-top:50px;
}

.expenses_banner
{
 width:100% !important;
 background-color:black;
 position: relative;
 text-align:center;
 color:white;
 padding:5px;
 overflow:hidden !important;
 font-family: "Montserrat",sans-serif !important;
 font-size:20px;
 position:fixed;
 z-index: 105 !important;
}

.container_input
{
width:100%;
margin-top:5%;
text-align:center;
margin:auto;
}

.expenses_main_head
{
 width:60%;
 text-align:center;
 padding-top:80px;
 margin:auto;
}

.expenses_div
{
width:100% !important;
margin:auto;
margin-top:3%;
}

.expenses_div_left
{
height:40px;
line-height:40px;
background-color:black;
float:left;
display: inline-block;
text-align:left;
padding-left:12px;
color:white;
width:48%;
font-size: 14px !important;
font-family : "Montserrat",sans-serif !important;
}

.expenses_div_right
{
height: 40px !important;
line-height: 40px !important;
width:48%;
float:left;
display: inline-block;
cursor:pointer;
background:transparent !important;
position:relative;/*Added (Because :after should be relative to this not whole page! )*/
}

.expenses_div_right select
{
font-family : "Montserrat",sans-serif !important;
background:transparent !important;
appearance:none !important;
-moz-appearance:none !important;
-webkit-appearance:none !important;
box-sizing: border-box !important;
border: 1px solid black !important;
width:100%!important;
color:black !important;
height:40px;
text-align:left !important;
font-size: 14px !important;
outline: none;
position: relative !important;
cursor:pointer;
padding-left:12px;
z-index:2;
}

.expenses_div_right:after
{
content: '< >';
font: 16px "Consolas", monospace;
font-weight:bold;
color: white;
background-color:black;
display:inline-block;
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
position: absolute;/*Changed to absolute*/
top:0;/*Added*/
right:0;/*Added*/
width:40px;
height:40px;
text-align:center;
line-height:40px;
overflow:hidden !important;
cursor:pointer;
z-index :1 ;/*Added ( For Your 2nd Question )*/
}

.expenses_input
{
height:40px !important;
line-height: 40px !important;
border: 1px solid black !important;
font-family : "Montserrat",sans-serif !important;
outline: none !important;
width:100%!important;
text-align:right;
display: inline-block;
font-size: 14px !important;
cursor:pointer;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box !important;
-moz-appearance: none;
}

.clerafix{
  clear:both;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="expenses_wrapper" class="expenses_wrapper" >
<div id="expenses_banner" class="expenses_banner" >Tracker</div>

<div class="container_input" id="container_input"  >
 <div class="expenses_main_head">
  <div class="expenses_div_left" >How to Proceed</div>
  <div id="expenses_div_right" class="expenses_div_right" >
   <select name="expense_main_selection"  id="expense_main_selection" >
    <option selected value="">Select an option</option>
    <option value="new_data">New Data</option>
    <option value="analize_data">Analyze Data</option>
    <option value="refresh_data">Refresh Data</option>
   </select>
  </div>
    <div class="clerafix"></div>
 </div>

 <div id="expenses_input_date" class="expenses_div" >
  <div class="expenses_div_left" >Date</div>
  <div class="expenses_div_right" ><input type="text" class="expenses_input" id="expenses_input_date" name="expenses_input_date" autocomplete="off"></div>
    <div class="clerafix"></div>
 </div>

 <div id ="expenses_select_account" class="expenses_div" >
  <div class="expenses_div_left" >Select Account</div>
  <div id="expenses_div_right" class="expenses_div_right" >
   <select name="select_account" id="select_account_select">
    <option selected value="">Select Account</option>
    <option value="Opt1">Opt1</option>
    <option value="Opt2">Opt2</option>
   </select>
  </div>
    <div class="clerafix"></div>
 </div>

</div>

</div></code>```

Title: CSS margin issue with DIV ids

Body:
In my below code, I am facing below problems div expenses_div. I have added margin-top:3%; for it, but somehow its not working.

Also, expenses_div is inside container_input. but expenses_div width is more than the one set for container_input (60% of page width). I am not able to understand the issue with expenses_div.

Can someone please guide me here

.expenses_wrapper
{
 width:100%;
 text-align:center;
 margin:auto;
 margin-top:50px;
}

.expenses_banner
{
 width:100% !important;
 background-color:black;
 position: relative;
 text-align:center;
 color:white;
 padding:5px;
 overflow:hidden !important;
 font-family: "Montserrat",sans-serif !important;
 font-size:20px;
 position:fixed;
 z-index: 105 !important;
}

.container_input
{
width:100%;
margin-top:5%;
text-align:center;
margin:auto;
}

.expenses_main_head
{
 width:60%;
 text-align:center;
 padding-top:80px;
 margin:auto;
}

.expenses_div
{
width:100% !important;
margin:auto;
margin-top:3%;
}

.expenses_div_left
{
height:40px;
line-height:40px;
background-color:black;
float:left;
display: inline-block;
text-align:left;
padding-left:12px;
color:white;
width:48%;
font-size: 14px !important;
font-family : "Montserrat",sans-serif !important;
}

.expenses_div_right
{
height: 40px !important;
line-height: 40px !important;
width:48%;
float:left;
display: inline-block;
cursor:pointer;
background:transparent !important;
position:relative;/*Added (Because :after should be relative to this not whole page! )*/
}

.expenses_div_right select
{
font-family : "Montserrat",sans-serif !important;
background:transparent !important;
appearance:none !important;
-moz-appearance:none !important;
-webkit-appearance:none !important;
box-sizing: border-box !important;
border: 1px solid black !important;
width:100%!important;
color:black !important;
height:40px;
text-align:left !important;
font-size: 14px !important;
outline: none;
position: relative !important;
cursor:pointer;
padding-left:12px;
z-index:2;
}

.expenses_div_right:after
{
content: '< >';
font: 16px "Consolas", monospace;
font-weight:bold;
color: white;
background-color:black;
display:inline-block;
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
position: absolute;/*Changed to absolute*/
top:0;/*Added*/
right:0;/*Added*/
width:40px;
height:40px;
text-align:center;
line-height:40px;
overflow:hidden !important;
cursor:pointer;
z-index :1 ;/*Added ( For Your 2nd Question )*/
}

.expenses_input
{
height:40px !important;
line-height: 40px !important;
border: 1px solid black !important;
font-family : "Montserrat",sans-serif !important;
outline: none !important;
width:100%!important;
text-align:right;
display: inline-block;
font-size: 14px !important;
cursor:pointer;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box !important;
-moz-appearance: none;
}

Tracker

How to Proceed

   <select name="expense_main_selection"  id="expense_main_selection" >
    <option selected value="">Select an option</option>
    <option value="new_data">New Data</option>
    <option value="analize_data">Analyze Data</option>
    <option value="refresh_data">Refresh Data</option>
   </select>

Date

<input type="text" class="expenses_input" id="expenses_input_date" name="expenses_input_date" autocomplete="off">

Select Account

   <select name="select_account" id="select_account_select">
    <option selected value="">Select Account</option>
    <option value="Opt1">Opt1</option>
    <option value="Opt2">Opt2</option>
   </select>

Body:
Add clear:both when you use float, Parent div is not taking height when you use float, so use clear:both to clear it.

The clear property is directly related to floats. If the element can fit horizontally in the space next to another element which is floated, it will. Unless you apply clear to that element in the same direction as the float. Then the element will move down below the floated element.

It's probably best practise to keep the names different of class and id purely for code readability, but there's no issue being same.

.expenses_wrapper
{
 width:100%;
 text-align:center;
 margin:auto;
 margin-top:50px;
}

.expenses_banner
{
 width:100% !important;
 background-color:black;
 position: relative;
 text-align:center;
 color:white;
 padding:5px;
 overflow:hidden !important;
 font-family: "Montserrat",sans-serif !important;
 font-size:20px;
 position:fixed;
 z-index: 105 !important;
}

.container_input
{
width:100%;
margin-top:5%;
text-align:center;
margin:auto;
}

.expenses_main_head
{
 width:60%;
 text-align:center;
 padding-top:80px;
 margin:auto;
}

.expenses_div
{
width:100% !important;
margin:auto;
margin-top:3%;
}

.expenses_div_left
{
height:40px;
line-height:40px;
background-color:black;
float:left;
display: inline-block;
text-align:left;
padding-left:12px;
color:white;
width:48%;
font-size: 14px !important;
font-family : "Montserrat",sans-serif !important;
}

.expenses_div_right
{
height: 40px !important;
line-height: 40px !important;
width:48%;
float:left;
display: inline-block;
cursor:pointer;
background:transparent !important;
position:relative;/*Added (Because :after should be relative to this not whole page! )*/
}

.expenses_div_right select
{
font-family : "Montserrat",sans-serif !important;
background:transparent !important;
appearance:none !important;
-moz-appearance:none !important;
-webkit-appearance:none !important;
box-sizing: border-box !important;
border: 1px solid black !important;
width:100%!important;
color:black !important;
height:40px;
text-align:left !important;
font-size: 14px !important;
outline: none;
position: relative !important;
cursor:pointer;
padding-left:12px;
z-index:2;
}

.expenses_div_right:after
{
content: '< >';
font: 16px "Consolas", monospace;
font-weight:bold;
color: white;
background-color:black;
display:inline-block;
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
position: absolute;/*Changed to absolute*/
top:0;/*Added*/
right:0;/*Added*/
width:40px;
height:40px;
text-align:center;
line-height:40px;
overflow:hidden !important;
cursor:pointer;
z-index :1 ;/*Added ( For Your 2nd Question )*/
}

.expenses_input
{
height:40px !important;
line-height: 40px !important;
border: 1px solid black !important;
font-family : "Montserrat",sans-serif !important;
outline: none !important;
width:100%!important;
text-align:right;
display: inline-block;
font-size: 14px !important;
cursor:pointer;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box !important;
-moz-appearance: none;
}

.clerafix{
  clear:both;
}

<div id="expenses_wrapper" class="expenses_wrapper" >
<div id="expenses_banner" class="expenses_banner" >Tracker</div>

<div class="container_input" id="container_input"  >
 <div class="expenses_main_head">
  <div class="expenses_div_left" >How to Proceed</div>
  <div id="expenses_div_right" class="expenses_div_right" >
   <select name="expense_main_selection"  id="expense_main_selection" >
    <option selected value="">Select an option</option>
    <option value="new_data">New Data</option>
    <option value="analize_data">Analyze Data</option>
    <option value="refresh_data">Refresh Data</option>
   </select>
  </div>
    <div class="clerafix"></div>
 </div>

 <div id="expenses_input_date" class="expenses_div" >
  <div class="expenses_div_left" >Date</div>
  <div class="expenses_div_right" ><input type="text" class="expenses_input" id="expenses_input_date" name="expenses_input_date" autocomplete="off"></div>
    <div class="clerafix"></div>
 </div>

 <div id ="expenses_select_account" class="expenses_div" >
  <div class="expenses_div_left" >Select Account</div>
  <div id="expenses_div_right" class="expenses_div_right" >
   <select name="select_account" id="select_account_select">
    <option selected value="">Select Account</option>
    <option value="Opt1">Opt1</option>
    <option value="Opt2">Opt2</option>
   </select>
  </div>
    <div class="clerafix"></div>
 </div>

</div>

</div>


问:
Transparent background to a listbox without border
I'm trying to apply transparent background to a listbox but I get a strange rendering.

The listbox itself is transparant but the border is so transparent that it overrides the background!

Here is the screenshot that demonstrate the problem:
http://img10.imageshack.us/i/transparentborder.png/

I've tried the following without success:

On the ListBox

Background="{x:Null}"

BorderThickness="0"

BorderThickness="{x:Null}"

On the container and the scrollviewer the same properties but unsuccessful. I made other tests but always the same renderer ...

Thank you for any and all help!

EDIT : Sorry, it's not on the Windows Phone 7, it's on a desktop application

```<code>        <ListBox x:Name="ListBoxEntries" VerticalAlignment="Center"  HorizontalAlignment="Center" BorderThickness="{x:Null}"  Background="{x:Null}" SelectionChanged="ListBoxEntries_SelectionChanged" >
            <ListBox.ItemTemplate>
                itemtemplate code
            </ListBox.ItemTemplate>
        </ListBox>
</code>```

答:
I resolved my problem.
I used a template to make "zune like" application. And with the template i have the following code behind  :

```<code>protected override void OnInitialized(EventArgs e)
            {
                AllowsTransparency = false;
                ResizeMode = ResizeMode.NoResize;
                Height = 480;
                Width = 852;
                WindowStartupLocation = WindowStartupLocation.CenterScreen;
                WindowStyle = WindowStyle.None;

                SourceInitialized += HandleSourceInitialized;

                GotKeyboardFocus += HandleGotKeyboardFocus;
                LostKeyboardFocus += HandleLostKeyboardFocus;

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

I just change the propertie of AllowsTransparency to true and it resolve the problem.

Thanks for your answer.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to apply transparent background to a listbox but I get a strange rendering.

The listbox itself is transparant but the border is so transparent that it overrides the background!

Here is the screenshot that demonstrate the problem:
http://img10.imageshack.us/i/transparentborder.png/

I've tried the following without success:

On the ListBox

Background="{x:Null}"

BorderThickness="0"

BorderThickness="{x:Null}"

On the container and the scrollviewer the same properties but unsuccessful. I made other tests but always the same renderer ...

Thank you for any and all help!

EDIT : Sorry, it's not on the Windows Phone 7, it's on a desktop application

        <ListBox x:Name="ListBoxEntries" VerticalAlignment="Center"  HorizontalAlignment="Center" BorderThickness="{x:Null}"  Background="{x:Null}" SelectionChanged="ListBoxEntries_SelectionChanged" >
            <ListBox.ItemTemplate>
                itemtemplate code
            </ListBox.ItemTemplate>
        </ListBox>

Body:
I resolved my problem.
I used a template to make "zune like" application. And with the template i have the following code behind  :

protected override void OnInitialized(EventArgs e)
            {
                AllowsTransparency = false;
                ResizeMode = ResizeMode.NoResize;
                Height = 480;
                Width = 852;
                WindowStartupLocation = WindowStartupLocation.CenterScreen;
                WindowStyle = WindowStyle.None;

                SourceInitialized += HandleSourceInitialized;

                GotKeyboardFocus += HandleGotKeyboardFocus;
                LostKeyboardFocus += HandleLostKeyboardFocus;

                base.OnInitialized(e);
            }

I just change the propertie of AllowsTransparency to true and it resolve the problem.

Thanks for your answer.


问:
Delete .xlsx or .pdf after closing file
I'm trying to delete .xlsx or .pdf files after using them. When files are created I display them, but then users want automatic file deletion after closing them.

I've tried couple of things, but none of them seem to work properly. Issue:

When opened multiple files (.xlsx or .pdf) I can't terminate a single process, like just a single file. Instead what happens is that file get's deleted only when I close all same processes (Excel or PDF files). As I investigated this happens because Excel or PDF works as one instance only. However code works as expected when I have only one file opened...

This is what I have so far:

```<code> var process= Process.Start(file_path); //file_path is global variable
 Set_event(process);

 private void Set_event(Process process)
 {
        process.EnableRaisingEvents = true;
        process.Exited += new EventHandler(Delete_File);
 }

 public void Delete_File(object sender, EventArgs e)
 {
        //Delete file on close
        File.Delete(file_path);
 }
</code>```

I've also tried with DeleteOnClose method of FileOptions, but unfortunally that doesn't display file to user and doesn't quite delete file immediately after using them, only after my win app is closed. That isn't my desired output, but at least files are deleted, so If I could fix that I would be partially satisfied too. Here is my line for that:

```<code>   var open_file = new FileStream(file_path,FileMode.Open, FileAccess.ReadWrite,FileShare.ReadWrite, 512, FileOptions.DeleteOnClose);
</code>```

With all that said, are there any other options I missed ? Thanks for help in advance.

答:
I've tried almost everything I could find (different variations of Exited_Event for Process, monitoring with FileSystemWatcher, creating files with DeleteOnClose - even API), but none of them worked as expected.

Everything ends or fails with issue I described in first place - some apps, like Microsoft Excel or Adobe Acrobat uses one instance to open a file (.pdf or .xls/.xlsx), so you can't just reference a single file as object while you have opened more files. That means you either end up with an error when trying to assign Exited_event to single file, or no error but file gets deleted only when you close all files with same type...

BUT fortunate enough I figured out one thing: WHEN you have opened more than one file in question (.pdf or .xlsx) something happens in background of OS: If you loop through processes of same type at that time, you'll get a list of particular instance that is in use.

In other words, while you have 2 Excel files opened, loop through processes is showing you only a file which is currently active for "EXCEL" process.

So, that leaded me to a completely new approach that might solve this issue. In order to have a complete solution for this you have to:

1. Create a method to check whether file is no longer in use.

2. Set a Timer with a delay of 2 seconds, to make sure process really ends. Maybe this should be incremented for different purposes...

3. Set a Timer_tick event, where you loop processes to see whether particular file is listed as active, and If user has already closed this file.  As described by other users this method isn't quite accurate, but with setting delay for Timer I think there shouldn't be any problems anymore.

Here is a complete code for this (for .pdf and .xlsx - that is what I needed):

```<code>   //as global variable
   System.Windows.Forms.Timer delete_file = new System.Windows.Forms.Timer();

    Process.Start(file_path); //file_path is global variable

    delete_file.Tick += new EventHandler(timer_Tick);
    delete_file.Interval = (2000);
    delete_file.Enabled = true;
    delete_file.Start();

    private void timer_Tick(object sender, EventArgs e)
    {
        Boolean file_is_opened = false;

        // Loop processes and list active files in use
        foreach (var process in Process.GetProcesses())
        {
          if (process.MainWindowTitle.Contains(Path.GetFileName(file_path)))
          {
             file_is_opened = true;
          }
        }

         //If our file is not listed under active processes we check
         //whether user has already closed file - If so, we finally delete It
         if (file_is_opened==false)
         {
            if (!File_In_Use(new FileInfo(file_path)))
            {
                 File.Delete(file_path);
                 delete_file.Enabled = false;
                 delete_file.Stop();
                 return;
             }
          }
     }

     private bool File_In_Use(FileInfo file)
     {
         //Method to check whether file is in use

         FileStream stream = null;

         try
         {
              //If file doesn't exist
              if (!file.Exists)
              {
                     return false;
              }

              stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
         }
         catch (IOException)
         {
               //File is unavailable:
              //because someone writes to It, or It's being processed
              return true;
         }
         finally
         {
            if (stream!=null)
            {
              stream.Close();
            }
         }

             //File not locked
             return false;
      }
</code>```

This is how I did It. It might not be a perfect solution, but that works for me on Win 10 with no errors so far.

If someone has a suggestion to fix upper code, please let me know. Otherwise I hope this will help someone in future as I noticed there were already some questions about this in past, with no proper answer.

Title: Delete .xlsx or .pdf after closing file

Body:
I'm trying to delete .xlsx or .pdf files after using them. When files are created I display them, but then users want automatic file deletion after closing them.

I've tried couple of things, but none of them seem to work properly. Issue:

When opened multiple files (.xlsx or .pdf) I can't terminate a single process, like just a single file. Instead what happens is that file get's deleted only when I close all same processes (Excel or PDF files). As I investigated this happens because Excel or PDF works as one instance only. However code works as expected when I have only one file opened...

This is what I have so far:

 var process= Process.Start(file_path); //file_path is global variable
 Set_event(process);

 private void Set_event(Process process)
 {
        process.EnableRaisingEvents = true;
        process.Exited += new EventHandler(Delete_File);
 }

 public void Delete_File(object sender, EventArgs e)
 {
        //Delete file on close
        File.Delete(file_path);
 }

I've also tried with DeleteOnClose method of FileOptions, but unfortunally that doesn't display file to user and doesn't quite delete file immediately after using them, only after my win app is closed. That isn't my desired output, but at least files are deleted, so If I could fix that I would be partially satisfied too. Here is my line for that:

   var open_file = new FileStream(file_path,FileMode.Open, FileAccess.ReadWrite,FileShare.ReadWrite, 512, FileOptions.DeleteOnClose);

With all that said, are there any other options I missed ? Thanks for help in advance.

Body:
I've tried almost everything I could find (different variations of Exited_Event for Process, monitoring with FileSystemWatcher, creating files with DeleteOnClose - even API), but none of them worked as expected.

Everything ends or fails with issue I described in first place - some apps, like Microsoft Excel or Adobe Acrobat uses one instance to open a file (.pdf or .xls/.xlsx), so you can't just reference a single file as object while you have opened more files. That means you either end up with an error when trying to assign Exited_event to single file, or no error but file gets deleted only when you close all files with same type...

BUT fortunate enough I figured out one thing: WHEN you have opened more than one file in question (.pdf or .xlsx) something happens in background of OS: If you loop through processes of same type at that time, you'll get a list of particular instance that is in use.

In other words, while you have 2 Excel files opened, loop through processes is showing you only a file which is currently active for "EXCEL" process.

So, that leaded me to a completely new approach that might solve this issue. In order to have a complete solution for this you have to:

1. Create a method to check whether file is no longer in use.

2. Set a Timer with a delay of 2 seconds, to make sure process really ends. Maybe this should be incremented for different purposes...

3. Set a Timer_tick event, where you loop processes to see whether particular file is listed as active, and If user has already closed this file.  As described by other users this method isn't quite accurate, but with setting delay for Timer I think there shouldn't be any problems anymore.

Here is a complete code for this (for .pdf and .xlsx - that is what I needed):

   //as global variable
   System.Windows.Forms.Timer delete_file = new System.Windows.Forms.Timer();

    Process.Start(file_path); //file_path is global variable

    delete_file.Tick += new EventHandler(timer_Tick);
    delete_file.Interval = (2000);
    delete_file.Enabled = true;
    delete_file.Start();

    private void timer_Tick(object sender, EventArgs e)
    {
        Boolean file_is_opened = false;

        // Loop processes and list active files in use
        foreach (var process in Process.GetProcesses())
        {
          if (process.MainWindowTitle.Contains(Path.GetFileName(file_path)))
          {
             file_is_opened = true;
          }
        }

         //If our file is not listed under active processes we check
         //whether user has already closed file - If so, we finally delete It
         if (file_is_opened==false)
         {
            if (!File_In_Use(new FileInfo(file_path)))
            {
                 File.Delete(file_path);
                 delete_file.Enabled = false;
                 delete_file.Stop();
                 return;
             }
          }
     }

     private bool File_In_Use(FileInfo file)
     {
         //Method to check whether file is in use

         FileStream stream = null;

         try
         {
              //If file doesn't exist
              if (!file.Exists)
              {
                     return false;
              }

              stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
         }
         catch (IOException)
         {
               //File is unavailable:
              //because someone writes to It, or It's being processed
              return true;
         }
         finally
         {
            if (stream!=null)
            {
              stream.Close();
            }
         }

             //File not locked
             return false;
      }

This is how I did It. It might not be a perfect solution, but that works for me on Win 10 with no errors so far.

If someone has a suggestion to fix upper code, please let me know. Otherwise I hope this will help someone in future as I noticed there were already some questions about this in past, with no proper answer.


问:
JSON is not parsing properly even though it should be correct
I am currently working on my NEA for GCSE Computer Science and I am trying to incorporate JSON into my project for easier access to the data later on.

I have tried running other JSON which seems to work, but for some reason the JSON that I generate fails to parse into a python list.

with open('userProfiles.json', 'r+') as f: #Open up the json file for reading/writing.
    print(f.read()) # Debug message to check if f.read actually contains anything...
    currentProfiles = json.loads(f.read()) # Load the json into a useable list.
    print(currentProfiles) # Debug Message: So I can check if the list loads properly
    username = input("Enter username: ")
    password = hashlib.sha256((input("Enter Password: ")).encode('utf-8')).hexdigest() # Create an sha256 hash to be used later to authenticate users.
    newUser = json.dumps({'users':[{'username':username, 'password':password}]}, sort_keys=True, indent=4)
    f.write(newUser)
```

<p>Here is the JSON file it generates when I comment out the load code</p>

```{
    "users": [
        {
            "password": "8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918",
            "username": "Admin"
        }
    ]
}
```

<p>I want to load this JSON into a list so I can extend it with another user when I need to, but I can't due to the error message: </p>

```json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
```

When ever I attempt to parse the JSON, I have run the JSON through an online verifier that tells me it is valid JSON. I can not seem to find the problem here.

答:
Calling read() reads through the entire file and leaves the read cursor at the end of the file (with nothing more to read).

```<code>with open('userProfiles.json', 'r') as f: #Open up the json file for reading/writing.
    data = f.read()
    print(data) # Debug message to check if f.read actually contains anything...
    currentProfiles = json.loads(data) # Load the json into a useable list.
    print(currentProfiles) # Debug Message: So I can check if the list loads properly
    username = input("Enter username: ")
    password = hashlib.sha256((input("Enter Password: ")).encode('utf-8')).hexdigest() # Create an sha256 hash to be used later to authenticate users.
    newUser = json.dumps({'users':[{'username':username, 'password':password}]}, sort_keys=True, indent=4)

with open('userProfiles.json', 'a') as f:
    f.write(newUser)
</code>```

Body:
I am currently working on my NEA for GCSE Computer Science and I am trying to incorporate JSON into my project for easier access to the data later on.

I have tried running other JSON which seems to work, but for some reason the JSON that I generate fails to parse into a python list.

with open('userProfiles.json', 'r+') as f: #Open up the json file for reading/writing.
    print(f.read()) # Debug message to check if f.read actually contains anything...
    currentProfiles = json.loads(f.read()) # Load the json into a useable list.
    print(currentProfiles) # Debug Message: So I can check if the list loads properly
    username = input("Enter username: ")
    password = hashlib.sha256((input("Enter Password: ")).encode('utf-8')).hexdigest() # Create an sha256 hash to be used later to authenticate users.
    newUser = json.dumps({'users':[{'username':username, 'password':password}]}, sort_keys=True, indent=4)
    f.write(newUser)

Here is the JSON file it generates when I comment out the load code

{
    "users": [
        {
            "password": "8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918",
            "username": "Admin"
        }
    ]
}

I want to load this JSON into a list so I can extend it with another user when I need to, but I can't due to the error message:

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

When ever I attempt to parse the JSON, I have run the JSON through an online verifier that tells me it is valid JSON. I can not seem to find the problem here.

Body:
Calling read() reads through the entire file and leaves the read cursor at the end of the file (with nothing more to read).

with open('userProfiles.json', 'r') as f: #Open up the json file for reading/writing.
    data = f.read()
    print(data) # Debug message to check if f.read actually contains anything...
    currentProfiles = json.loads(data) # Load the json into a useable list.
    print(currentProfiles) # Debug Message: So I can check if the list loads properly
    username = input("Enter username: ")
    password = hashlib.sha256((input("Enter Password: ")).encode('utf-8')).hexdigest() # Create an sha256 hash to be used later to authenticate users.
    newUser = json.dumps({'users':[{'username':username, 'password':password}]}, sort_keys=True, indent=4)

with open('userProfiles.json', 'a') as f:
    f.write(newUser)


问:
BluetoothPairingStateProvider: getUuids() returns null for device
Context:

I am working on a FIDO-U2F bluetooth authenticator with a nRF52 BLE SoC. and want it to test with google example.

So far I have implemented the FIDO Bluetooth specification and I have a device that advertises as a FIDO-compatible device.

Thanks to nRF Connect I have ensured that all the services and characteristics are correctly exposed and that I can interact with it only when my device is securely paired (with LTK):

Problem:

When the app scans for eligible FIDO device, it does not find mine.

I am stuck on the screen that ask to press a button for 5s, which I don't need to since my device responds to pairing request without user interaction and is already paired with my SAMSUNG A8.

```<code>I/BluetoothDevicePreference: onDeviceAttributesChanged :: Device = (N) D8BE86, isBonded = 12 , mIsOnProgressAddVI = false
I/Fido: [BleScanner] startScan()
E/Fido: [BluetoothPairingStateProvider] getUuids() returns null for device: D8:BE:86:4A:E5:65
I/Fido: [PreferredTransportProvider] BLE enabled but no device is paired
I/Fido: [AuthenticateBaseChimeraActivity] User selected transport ble
I/Fido: [ViewController] Accepting proposed view {"viewName":"ble_instructions","anyU2fDevicesPaired":false}: outranks current (2 > 0)
I/Fido: [ViewPresenter] viewSelected(...) ble_instructions
I/Fido: [U2fRequestController] onResultReceived(null, ErrorResponseData{errorCode=5})
I/Fido: [BleScanner] stopScan()
</code>```

I tried to remove pairing data and all I have is:

```<code>I/BluetoothDevicePreference: onDeviceAttributesChanged :: Device = (N) D8BE86, isBonded = 10 , mIsOnProgressAddVI = false
</code>```

The advertising flags are currently set to "BR/EDR not supported", but I also tried "LE Limited Discoverable Mode" and "LE General Discoverable Mode" without success.

I looked into android-fido sources but the BLE scan seems imported from elsewhere, I cannot debug it in this project.

Any pointer is welcome

答:
Have you got to this screen?

We may need to add Service Data field (0x16) into advertising packet. This is mentioned in FIDO specification here

Android code snippet for advertising with Service Data field added:

```<code>AdvertiseData data = new AdvertiseData.Builder()
                        .addServiceUuid(new ParcelUuid(fido2GattService.getUuid()))
                        .setIncludeDeviceName(true)
                        .addServiceData(new ParcelUuid(fido2GattService.getUuid()), new byte[] {(byte)192, (byte)192, (byte)192})
                        .build();
</code>```

If you want to capture bluetooth packets to see what is your advertising packet, you can use PacketLogger (for MacOS)

Here is the screenshot of the advertising packet

The red box is Service Data

Body:
Context:

I am working on a FIDO-U2F bluetooth authenticator with a nRF52 BLE SoC. and want it to test with google example.

So far I have implemented the FIDO Bluetooth specification and I have a device that advertises as a FIDO-compatible device.

Thanks to nRF Connect I have ensured that all the services and characteristics are correctly exposed and that I can interact with it only when my device is securely paired (with LTK):

Problem:

When the app scans for eligible FIDO device, it does not find mine.

I am stuck on the screen that ask to press a button for 5s, which I don't need to since my device responds to pairing request without user interaction and is already paired with my SAMSUNG A8.

I/BluetoothDevicePreference: onDeviceAttributesChanged :: Device = (N) D8BE86, isBonded = 12 , mIsOnProgressAddVI = false
I/Fido: [BleScanner] startScan()
E/Fido: [BluetoothPairingStateProvider] getUuids() returns null for device: D8:BE:86:4A:E5:65
I/Fido: [PreferredTransportProvider] BLE enabled but no device is paired
I/Fido: [AuthenticateBaseChimeraActivity] User selected transport ble
I/Fido: [ViewController] Accepting proposed view {"viewName":"ble_instructions","anyU2fDevicesPaired":false}: outranks current (2 > 0)
I/Fido: [ViewPresenter] viewSelected(...) ble_instructions
I/Fido: [U2fRequestController] onResultReceived(null, ErrorResponseData{errorCode=5})
I/Fido: [BleScanner] stopScan()

I tried to remove pairing data and all I have is:

I/BluetoothDevicePreference: onDeviceAttributesChanged :: Device = (N) D8BE86, isBonded = 10 , mIsOnProgressAddVI = false

The advertising flags are currently set to "BR/EDR not supported", but I also tried "LE Limited Discoverable Mode" and "LE General Discoverable Mode" without success.

I looked into android-fido sources but the BLE scan seems imported from elsewhere, I cannot debug it in this project.

Any pointer is welcome

Body:
Have you got to this screen?

We may need to add Service Data field (0x16) into advertising packet. This is mentioned in FIDO specification here

Android code snippet for advertising with Service Data field added:

AdvertiseData data = new AdvertiseData.Builder()
                        .addServiceUuid(new ParcelUuid(fido2GattService.getUuid()))
                        .setIncludeDeviceName(true)
                        .addServiceData(new ParcelUuid(fido2GattService.getUuid()), new byte[] {(byte)192, (byte)192, (byte)192})
                        .build();

If you want to capture bluetooth packets to see what is your advertising packet, you can use PacketLogger (for MacOS)

Here is the screenshot of the advertising packet

The red box is Service Data


问:
Is it possible to add custom field to Product?
I recently work with Commercetools and I have a question.

I've looked on CustomFields documentation https://docs.commercetools.com/http-api-projects-custom-fields#custom and it became interesting to me.

How can we add custom field to product level and to variant level? Is it possible? Or can we add CustomFields to ProductType?

答:
Thanks for the request.

Custom types are not needed on products as the product types define all the attributes required for a product.

see https://docs.commercetools.com/http-api-projects-productTypes#attributedefinition for a complete documentation of the attributes you can define.

Best Regards
Brian


问:
What is the difference between Jinja's defined vs if variable_name?
What is the difference between these two items? When do you use one vs the other?

```<code>{% if x is defined %}
   words
{% endif %}
</code>```

and

```<code>{% if x %}
   words
{% endif %}
</code>```

答: The second one enforces you to provide x as a variable. If you won't set x at all, then it'll be an error. The first item will be skipped if x wasn't provided</p>

Body:
What is the difference between these two items? When do you use one vs the other?

{% if x is defined %}
   words
{% endif %}

and

{% if x %}
   words
{% endif %}


问:
Android PeriodicWorkRequestBuilder how to avoid double scheduling?
I'm using the new WorkManager, and was wondering, when I schedule a Periodic work, how can I avoid re-schedule it, is it automatically handled by OS?</p>

答:
If you need to check already running work manager just because you don't want duplicate works. You can simply use enqueueUniquePeriodicWork()

This method allows you to enqueue a uniquely-named
  PeriodicWorkRequest, where only one PeriodicWorkRequest of a
  particular name can be active at a time. For example, you may only
  want one sync operation to be active. If there is one pending, you can
  choose to let it run or replace it with your new work.

So you don't need to worry about duplicacy about works.

```<code> workmanager.enqueueUniquePeriodicWork(TAG, ExistingPeriodicWorkPolicy.KEEP , photoCheckWork);
</code>```

Where TAG is unique name by which work manager will check duplicacy.

You can choose between ExistingPeriodicWorkPolicy.KEEP and ExistingPeriodicWorkPolicy.REPLACE.

Body:
If you need to check already running work manager just because you don't want duplicate works. You can simply use enqueueUniquePeriodicWork()

This method allows you to enqueue a uniquely-named
  PeriodicWorkRequest, where only one PeriodicWorkRequest of a
  particular name can be active at a time. For example, you may only
  want one sync operation to be active. If there is one pending, you can
  choose to let it run or replace it with your new work.

So you don't need to worry about duplicacy about works.

 workmanager.enqueueUniquePeriodicWork(TAG, ExistingPeriodicWorkPolicy.KEEP , photoCheckWork);

Where TAG is unique name by which work manager will check duplicacy.

You can choose between ExistingPeriodicWorkPolicy.KEEP and ExistingPeriodicWorkPolicy.REPLACE.


问:
Why I'm unable to debug my code in TestNG
I am running automation tests using TestNG and Java.

Here is part of my code:

```<code>private void testConnection(String URL1) throws IOException {

    try {
        URL url = new URL(URL1);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        urlConn.connect();

        assertEquals(HttpURLConnection.HTTP_OK, urlConn.getResponseCode());
    } catch (IOException e) {
        ConsoleLogger.error("*******************************");
        ConsoleLogger.error("Could NOT connect to the server");
        ConsoleLogger.error("Entire test is aborted!!!");
        ConsoleLogger.error("Please check port and IP again!");
        ConsoleLogger.error("*******************************");
        throw e;
    }
}
</code>```

Now, my test fails because I am getting an exception from the URL.
I can see in the console the error message/s.
This method is being called in a method with the annotation @BeforeSuite.

Why can’t I debug this method (not the try block nor the catch block)?

答:
You've mentioned that your breakpoints are not being respected by IntelliJ and I can see from your code that there are references to a server. This might be happening if you are trying to do remote debugging:

To debug your code on a server you have to attach your debugger to its debug port. This means starting the server in debug mode, and creating a Remote debugging run configuration in IntelliJ attached to the correct port (which should be reported in your server initialisation logging).

For more information read the the original answer here.

If you are not remote debugging you can try do to the following:

Clear your cache with File -> Invalidate Caches/Restart.

Delete your whole project folder and import it again.

Reinstall your IDE and delete all configurations.

I was assuming you are working in IntelliJ for some reason but all of these points should work for other programs as well.

Body:
I am running automation tests using TestNG and Java.

Here is part of my code:

private void testConnection(String URL1) throws IOException {

    try {
        URL url = new URL(URL1);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        urlConn.connect();

        assertEquals(HttpURLConnection.HTTP_OK, urlConn.getResponseCode());
    } catch (IOException e) {
        ConsoleLogger.error("*******************************");
        ConsoleLogger.error("Could NOT connect to the server");
        ConsoleLogger.error("Entire test is aborted!!!");
        ConsoleLogger.error("Please check port and IP again!");
        ConsoleLogger.error("*******************************");
        throw e;
    }
}

Now, my test fails because I am getting an exception from the URL.
I can see in the console the error message/s.
This method is being called in a method with the annotation @BeforeSuite.

Why can’t I debug this method (not the try block nor the catch block)?


问:
How to speed up Inline SVG changes
In my hybrid Android app I use inline SVG to display images that are large (of the order of 2Mb) and complex (several hundred SVG elements per image).  When I need to change the image I do the following

```<code> var puzzle = document.createElementNS(SVGNS,'svg'),
 kutu = document.getElementById('kutu');

 puzzle.id = 'puzzle';
 puzzle.setAttribute('preserveAspectRatio','none');
 puzzle.setAttribute('width','100vw');
 puzzle.setAttribute('height','85.5vh');
 puzzle.setAttribute('xmlns',SVGNS);
 puzzle.setAttribute('xmlns:xlink',XLINK);
 puzzle.setAttribute('fill-rule','evenodd');
 puzzle.setAttribute('clip-rule','evenodd');
 puzzle.setAttribute('stroke-linejoin','round');
 puzzle.setAttribute('stroke-miterlimit','1.414');
 puzzle.setAttribute('viewBox','0 0 1600 770');
 puzzle.innerHTML = SVG;
 //SVG here is the SVG image content shorn off the outer <svg>..</svg>

 if (0 < kutu.children.length) kutu.children[0].remove();
 //remove old image, iff any
 kutu.appendChild(puzzle);
 //append the new image
</code>```

While this is working the process of displaying the new image is slow.  I suspect it is because of the innerHTML assignment above.  Recreating through a sequence of createElementNS, puzzle.àppendChild would require me to first parse the incoming raw SVG content etc.   Is that the way to go or would there be a faster way to display the content.

Once again for clarity - SVG here is the content of the new SVG image to be displayed shorn of its outer <svg>...</svg> wrrapper.

答:
Just a side note it would probably be better to use setAttributeNS in place of setAttribute for consistency purpose since createElementNS is used, though it might not make a difference in speeding up the SVG image change.

In the case of a native app, a tool like the Android Profiler if using Android Studio 3.0 and higher can be used to analyze performance bottleneck. However since your app is a hybrid app, some sort of performance profiler that's applicable to the hybrid app (Whether it's Ionic or Cordova, etc.) can help to pinpoint where your performance bottleneck is.

Since your app is a hybrid, without knowing the resource capacity of your android app session, the guess is it seems to be a possible cause that it calls something like .setAttribute to set session-level attributes on the fly during the change of the image and the session resource might not be enough, and also the DOM has to perform .innerHTML and appendChild, which are dynamic operations. DOM manipulation is known to be slow.

Conversion of attributes of all the SVGs and store the result in some sort of storage or cache, and when needed, call it from the persistent storage or cache might be helpful.

Or consider using AngularJS to do the SVG change beforehand and preload the SVG images, refer to easily preload images in your Angular app. Here is another similar code to yours except it's using AngularJS to add SVG for starters.

Another simpler way, without changing your code, if you could minify the incoming SVGs beforehand, is to use SVG Optimizer or SVGO, a node.js open source project to compress your SVGs. Quoted from the SVGO link it says:

"SVG files, especially those exported from various editors, usually contain a lot of redundant and useless information. This can include editor metadata, comments, hidden elements, default or non-optimal values and other stuff that can be safely removed or converted without affecting the SVG rendering result." Although the performance gain might not be obvious going this route.

Title: How to speed up Inline SVG changes

Body:
In my hybrid Android app I use inline SVG to display images that are large (of the order of 2Mb) and complex (several hundred SVG elements per image).  When I need to change the image I do the following

 var puzzle = document.createElementNS(SVGNS,'svg'),
 kutu = document.getElementById('kutu');

 puzzle.id = 'puzzle';
 puzzle.setAttribute('preserveAspectRatio','none');
 puzzle.setAttribute('width','100vw');
 puzzle.setAttribute('height','85.5vh');
 puzzle.setAttribute('xmlns',SVGNS);
 puzzle.setAttribute('xmlns:xlink',XLINK);
 puzzle.setAttribute('fill-rule','evenodd');
 puzzle.setAttribute('clip-rule','evenodd');
 puzzle.setAttribute('stroke-linejoin','round');
 puzzle.setAttribute('stroke-miterlimit','1.414');
 puzzle.setAttribute('viewBox','0 0 1600 770');
 puzzle.innerHTML = SVG;
 //SVG here is the SVG image content shorn off the outer <svg>..</svg>

 if (0 < kutu.children.length) kutu.children[0].remove();
 //remove old image, iff any
 kutu.appendChild(puzzle);
 //append the new image

While this is working the process of displaying the new image is slow.  I suspect it is because of the innerHTML assignment above.  Recreating through a sequence of createElementNS, puzzle.àppendChild would require me to first parse the incoming raw SVG content etc.   Is that the way to go or would there be a faster way to display the content.

Once again for clarity - SVG here is the content of the new SVG image to be displayed shorn of its outer <svg>...</svg> wrrapper.


问:
How to change default flask logger output to an json logging handler
i need to change flask default logging handler to a custom JSON logging text, i can change handler before app.run() but flask set a default handler when I don't a standard handler (clear() logging handlers)</p>

答:
```<code>import logging
from pythonjsonlogger.jsonlogger import JsonFormatter

def get_logger(module_name):
    """Generate a logger."""
    logger = logging.getLogger(module_name)
    # logger.setLevel(logging.CRITICAL)
    logger.setLevel(logging.DEBUG)
    logger.propagate = False    # reset handler to avoid duplicates
    logger.handlers = [get_json_handler()]
    return logger

def get_json_handler():
    """Generate a JsonFormatter"""
    formatter = JsonFormatter("(asctime) (levelname) (module) (funcName) (lineno) (message)")
    log_handler = logging.StreamHandler()
    log_handler.setFormatter(formatter)
    return log_handler

# Example:
log = get_logger()

flask_log = logging.getLogger('werkzeug')
flask_log.setLevel(logging.DEBUG)
flask_log.addHandler(log)
</code>```


问:
Is it possible to use all the CPUs of a node with Slurm?
I use a R function which is not parallelizable (it only uses one CPU of a node). I use several nodes to split the computations I need to do : so, the function is used on several nodes, but only one CPU is used. Each node has 32 CPUs. For the moment, if I use 10 nodes, I would like to know if it could be possible to split these 10 jobs on only one node, and each job will use 1 CPU?

I mean : from 10 jobs on 10 nodes with 1 CPU/node, change this strategy to get these 10 jobs on one node, with 10 CPUs used?

Thanks

答:
A script similar to this should work (assuming here that you use bash):

```<code>#!/bin/bash
#SBATCH -J JOB_NAME # job name
#SBATCH -N 1  # 1 Node cores/node)
#SBATCH -n 10 # 10 tasks

./job1 &
./job2 &
./job3 &
# ...
</code>```

This will reserve 1 node with 10 tasks and run the jobs in parallel. Depending on the environment you're working on, you may need to call some wrapper tool to run the binaries (and set affinity, if required).

Body:
A script similar to this should work (assuming here that you use bash):

#!/bin/bash
#SBATCH -J JOB_NAME # job name
#SBATCH -N 1  # 1 Node cores/node)
#SBATCH -n 10 # 10 tasks

./job1 &
./job2 &
./job3 &
# ...

This will reserve 1 node with 10 tasks and run the jobs in parallel. Depending on the environment you're working on, you may need to call some wrapper tool to run the binaries (and set affinity, if required).


问:
Replacing duplicate list elements with NaN
I would like to replace all duplicates of elements in arrays with NaN.
For example:

```<code>a = [1, 1, 2, 3, 1, 8, 5, 6, 7, 5, 5]
</code>```

Goal:

```<code>a = [NaN, NaN, 2, 3, NaN, 8, NaN, 6, 7, NaN, NaN]
</code>```

答:
you can use:

Python List count() Method

The count() method returns the number of elements with the specified
  value.

Syntax

```<code>list.count(value)
</code>```

```<code>a = [1, 1, 2, 3, 1, 8, 5, 6, 7, 5, 5]

result = ([x if a.count(x) == 1 else None for x in a ])

print (result)
</code>```

output:

```<code>[None, None, 2, 3, None, 8, None, 6, 7, None, None]
</code>```

what is equivalent to:

```<code>a = [1, 1, 2, 3, 1, 8, 5, 6, 7, 5, 5]

result = []
for x in a:
    # For each item, check how many times it will appear in the list
    if a.count(x) == 1:  # if item only appears once, append it to the list
        result.append(x)
    else: # if item appears more than once, append None to the list
        result.append(None)

print (result)
</code>```

output:

```<code>[None, None, 2, 3, None, 8, None, 6, 7, None, None]
</code>```

Body:
I would like to replace all duplicates of elements in arrays with NaN.
For example:

a = [1, 1, 2, 3, 1, 8, 5, 6, 7, 5, 5]

Goal:

a = [NaN, NaN, 2, 3, NaN, 8, NaN, 6, 7, NaN, NaN]

Body:
you can use:

Python List count() Method

The count() method returns the number of elements with the specified
  value.

Syntax

list.count(value)

a = [1, 1, 2, 3, 1, 8, 5, 6, 7, 5, 5]

result = ([x if a.count(x) == 1 else None for x in a ])

print (result)

output:

[None, None, 2, 3, None, 8, None, 6, 7, None, None]

what is equivalent to:

a = [1, 1, 2, 3, 1, 8, 5, 6, 7, 5, 5]

result = []
for x in a:
    # For each item, check how many times it will appear in the list
    if a.count(x) == 1:  # if item only appears once, append it to the list
        result.append(x)
    else: # if item appears more than once, append None to the list
        result.append(None)

print (result)

output:

[None, None, 2, 3, None, 8, None, 6, 7, None, None]


问:
How to resolve possible scheduling error with async ReactiveCommand?
I'm relatively new to ReactiveUI and I'm trying to asynchronously execute a database query from a ReactiveCommand. From what I can tell, the problem isn't with executing the async query, but when I try to load the results into a ReactiveList in my view model. I believe that this is a scheduling issue but I'm not familiar enough with RxUI to come up with the correct approach.

I've tried subscribing to the command in the view model using ObserveOn with both RxApp.TaskPoolScheduler and RxApp.MainThreadScheduler but neither seems to help.

My view model:

```<code>   public class UsersViewModel : ReactiveObject, IRoutableViewModel
   {
      ReactiveList<LisUser> _users;
      IUserManagementService UsersService { get; }

      public IScreen HostScreen { get; }

      public ReactiveCommand<Unit, IEnumerable<LisUser>> LoadUsers { get; }

      public String UrlPathSegment => "users";

      public ReactiveList<LisUser> Users
      {
         get => _users;
         set => this.RaiseAndSetIfChanged(ref _users, value);
      }

      public UsersSubPageViewModel(
         IScreen screen,
         IUserManagementService usersService)
      {
         HostScreen = screen ?? throw new ArgumentNullException(nameof(screen));
         UsersService =
            usersService ?? throw new ArgumentNullException(nameof(usersService));

         Users = new ReactiveList<LisUser>();
         LoadUsers = ReactiveCommand.CreateFromTask(async () =>
         {
            return await UsersService.GetUsersAsync().ConfigureAwait(false);
         });
         LoadUsers
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(list =>
            {
               Users.Clear();
               foreach (var u in list)
               {
                  Users.Add(u);
               }
            });
      }
   }
</code>```

My view:

```<code>   public partial class UsersView : ReactiveUserControl<UsersViewModel>
   {
      public UsersPageView()
      {
         InitializeComponent();

         this.WhenActivated(disposables =>
         {
            this.WhenAnyValue(x => x.ViewModel.LoadUsers)
               .SelectMany(x => x.Execute())
               .Subscribe()
               .DisposeWith(disposables);
         });
      }
   }
</code>```

What I want to occur is when the UsersView is activated, the GetUsers method of the UsersService executes asynchronously and loads the returned list of users into the Users ReactiveList. Instead, I see a new tab in VS with a title of "Source Not Found" and a message saying that "RxApp.cs not found". The actual exception is a System.Exception with a message stating "Cannot obtain value of the local variable or argument because it is not available at this instruction pointer, possibly because it has been optimized away."

So, my first question is "is this actually a scheduling issue?" And the second question is "how do I resolve it?"

答:
. First as stated in my comment reactivelist is deprecated.

There is a problem with the way the LoadUsers command is invoked.

One is you can do WhenActivated in your view model. You derive your view model from ISupportsActivation, your view will call the WhenActivated block inside your view when it's WhenActivated is called. See https://reactiveui.net/docs/handbook/when-activated/#viewmodels for ideas.

Second way is to use

this.WhenAnyValue(x => x.ViewModel.LoadUsers)
               .Select(x => x.Execute())
               .Switch()
               .Subscribe()
               .DisposeWith(disposables);
```

So the above says get the LoadUsers command, get the Execute() which is a observable, Switch() means only subscribe to the newest first, and dispose the old execute when a new value comes in, subscribe to that we will run the command, and dispose to stop potentially.

Body:
I'm relatively new to ReactiveUI and I'm trying to asynchronously execute a database query from a ReactiveCommand. From what I can tell, the problem isn't with executing the async query, but when I try to load the results into a ReactiveList in my view model. I believe that this is a scheduling issue but I'm not familiar enough with RxUI to come up with the correct approach.

I've tried subscribing to the command in the view model using ObserveOn with both RxApp.TaskPoolScheduler and RxApp.MainThreadScheduler but neither seems to help.

My view model:

   public class UsersViewModel : ReactiveObject, IRoutableViewModel
   {
      ReactiveList<LisUser> _users;
      IUserManagementService UsersService { get; }

      public IScreen HostScreen { get; }

      public ReactiveCommand<Unit, IEnumerable<LisUser>> LoadUsers { get; }

      public String UrlPathSegment => "users";

      public ReactiveList<LisUser> Users
      {
         get => _users;
         set => this.RaiseAndSetIfChanged(ref _users, value);
      }

      public UsersSubPageViewModel(
         IScreen screen,
         IUserManagementService usersService)
      {
         HostScreen = screen ?? throw new ArgumentNullException(nameof(screen));
         UsersService =
            usersService ?? throw new ArgumentNullException(nameof(usersService));

         Users = new ReactiveList<LisUser>();
         LoadUsers = ReactiveCommand.CreateFromTask(async () =>
         {
            return await UsersService.GetUsersAsync().ConfigureAwait(false);
         });
         LoadUsers
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(list =>
            {
               Users.Clear();
               foreach (var u in list)
               {
                  Users.Add(u);
               }
            });
      }
   }

My view:

   public partial class UsersView : ReactiveUserControl<UsersViewModel>
   {
      public UsersPageView()
      {
         InitializeComponent();

         this.WhenActivated(disposables =>
         {
            this.WhenAnyValue(x => x.ViewModel.LoadUsers)
               .SelectMany(x => x.Execute())
               .Subscribe()
               .DisposeWith(disposables);
         });
      }
   }

What I want to occur is when the UsersView is activated, the GetUsers method of the UsersService executes asynchronously and loads the returned list of users into the Users ReactiveList. Instead, I see a new tab in VS with a title of "Source Not Found" and a message saying that "RxApp.cs not found". The actual exception is a System.Exception with a message stating "Cannot obtain value of the local variable or argument because it is not available at this instruction pointer, possibly because it has been optimized away."

So, my first question is "is this actually a scheduling issue?" And the second question is "how do I resolve it?"

Body:
. First as stated in my comment reactivelist is deprecated.

There is a problem with the way the LoadUsers command is invoked.

One is you can do WhenActivated in your view model. You derive your view model from ISupportsActivation, your view will call the WhenActivated block inside your view when it's WhenActivated is called. See https://reactiveui.net/docs/handbook/when-activated/#viewmodels for ideas.

Second way is to use

this.WhenAnyValue(x => x.ViewModel.LoadUsers)
               .Select(x => x.Execute())
               .Switch()
               .Subscribe()
               .DisposeWith(disposables);

So the above says get the LoadUsers command, get the Execute() which is a observable, Switch() means only subscribe to the newest first, and dispose the old execute when a new value comes in, subscribe to that we will run the command, and dispose to stop potentially.


问:
How can I select files from PC in the file explorer using robot framework?
I have a button for Import which when clicked opens the windows file explorer from which we should select an excel file, which will then be imported. I cannot use seleniumlibrary since it has windows automation as well. I have the autoIT library, but how can i use it on a web page already brought open by selenium2library?</p>

答:
Try "Choose File" Keyword in SeleniumLibrary.

You can find the details in below link
http://robotframework.org/SeleniumLibrary/SeleniumLibrary.html#Choose%20File


问:
Hashing types at compile-time in C++17/C++2a
Consider the following code:

```<code>#include <iostream>
#include <type_traits>

template <class T>
constexpr std::size_t type_hash(T) noexcept
{
    // Compute a hash for the type
    // DO SOMETHING SMART HERE
}

int main(int argc, char* argv[])
{
    auto x = []{};
    auto y = []{};
    auto z = x;
    std::cout << std::is_same_v<decltype(x), decltype(y)> << std::endl; // 0
    std::cout << std::is_same_v<decltype(x), decltype(z)> << std::endl; // 1
    constexpr std::size_t xhash = type_hash(x);
    constexpr std::size_t yhash = type_hash(y);
    constexpr std::size_t zhash = type_hash(z);
    std::cout << (xhash == yhash) << std::endl; // should be 0
    std::cout << (yhash == zhash) << std::endl; // should be 1
    return 0;
}
</code>```

I would like the type_hash function to return a hash key unique to the type, at compile-time. Is there a way to do that in C++17, or in C++2a (ideally only relying on the standard and without relying compiler intrinsics)?

答:
Based on HolyBlackCat  answer, a constexpr template variable which is a (naive) implementation of the hash of a type:

```<code>template <typename T>
constexpr std::size_t Hash()
{
    std::size_t result{};

#ifdef _MSC_VER
#define F __FUNCSIG__
#else
#define F __PRETTY_FUNCTION__
#endif

    for (const auto &c : F)
        (result ^= c) <<= 1;

    return result;
}

template <typename T>
constexpr std::size_t constexpr_hash = Hash<T>();
</code>```

Can be used as shown below:

```<code>constexpr auto f = constexpr_hash<float>;
constexpr auto i = constexpr_hash<int>;
</code>```

Check on godbolt that the values are indeed, computed at compile time.

Body:
Consider the following code:

#include <iostream>
#include <type_traits>

template <class T>
constexpr std::size_t type_hash(T) noexcept
{
    // Compute a hash for the type
    // DO SOMETHING SMART HERE
}

int main(int argc, char* argv[])
{
    auto x = []{};
    auto y = []{};
    auto z = x;
    std::cout << std::is_same_v<decltype(x), decltype(y)> << std::endl; // 0
    std::cout << std::is_same_v<decltype(x), decltype(z)> << std::endl; // 1
    constexpr std::size_t xhash = type_hash(x);
    constexpr std::size_t yhash = type_hash(y);
    constexpr std::size_t zhash = type_hash(z);
    std::cout << (xhash == yhash) << std::endl; // should be 0
    std::cout << (yhash == zhash) << std::endl; // should be 1
    return 0;
}

I would like the type_hash function to return a hash key unique to the type, at compile-time. Is there a way to do that in C++17, or in C++2a (ideally only relying on the standard and without relying compiler intrinsics)?

Body:
Based on HolyBlackCat  answer, a constexpr template variable which is a (naive) implementation of the hash of a type:

template <typename T>
constexpr std::size_t Hash()
{
    std::size_t result{};

#ifdef _MSC_VER
#define F __FUNCSIG__
#else
#define F __PRETTY_FUNCTION__
#endif

    for (const auto &c : F)
        (result ^= c) <<= 1;

    return result;
}

template <typename T>
constexpr std::size_t constexpr_hash = Hash<T>();

Can be used as shown below:

constexpr auto f = constexpr_hash<float>;
constexpr auto i = constexpr_hash<int>;

Check on godbolt that the values are indeed, computed at compile time.


问:
Compress Data in JavaScript and send it to Flask Server
So my team has made a small tool to perform Image Annotation and Labeling. And we were trying to optimize our code.
We were able to compress data from the server, but we have been trying to perform compression on data that is being sent from client to server.
What data you may ask, its just text file around 2 - 3mb.
Is there any way we can perform compression?
We are using JavaScirpt and want to send to FLASK.

This is the first question i am posting on here :)

答:
You can try with this lib: Paco-zlib

```<code>var binaryString = pako.deflate("2-3mb text content", { to: 'string' });
// Here you can do base64 encode, make xhr requests and so on.
</code>```

But at server side, responding page will receive compressed data. You shoud decompress it using something like zlib.decompress(compressedData)

Body:
You can try with this lib: Paco-zlib

var binaryString = pako.deflate("2-3mb text content", { to: 'string' });
// Here you can do base64 encode, make xhr requests and so on.

But at server side, responding page will receive compressed data. You shoud decompress it using something like zlib.decompress(compressedData)


问:
How to rank variables in SAS by summarising another variable
For example:

```<code>Groupvar    Value
A           5
A           1
B           0
B           9
B           8
C           2
C           2
</code>```

I want to rank by the Groupvar summarising on Value. So in this example sum(A) = 6, sum(B) = 17, sum(C) = 4. So Rank 1 = B, rank 2 = A, rank 3 = 6.

Ideal output:

```<code>Groupvar    Value    Rank
A           5         2
A           1         2
B           0         1
B           9         1
B           8         1
C           2         3
C           2         3
</code>```

Any ideas how this can be done? I can create a proc summary > then rank> then merge the rank back on. But I'm wondering if there's a better way to do it.

答:
You might be able to use the variable created by the LEVELS options plus ORDER=FREQ. For example.

```<code>data have;
   input Groupvar:$1. Value;
   cards;
A           5
A           1
B           0
B           9
B           8
C           2
C           2
;;;;
   run;
proc summary nway order=freq missing;
   class groupvar;
   freq value;
   output out=test(drop=_type_ index=(groupvar)) / levels;
   run;
proc print;
   run;
data want;
   merge have test;
   by groupvar;
   run;
proc print;
   run;
</code>```

Body:
For example:

Groupvar    Value
A           5
A           1
B           0
B           9
B           8
C           2
C           2

I want to rank by the Groupvar summarising on Value. So in this example sum(A) = 6, sum(B) = 17, sum(C) = 4. So Rank 1 = B, rank 2 = A, rank 3 = 6.

Ideal output:

Groupvar    Value    Rank
A           5         2
A           1         2
B           0         1
B           9         1
B           8         1
C           2         3
C           2         3

Any ideas how this can be done? I can create a proc summary > then rank> then merge the rank back on. But I'm wondering if there's a better way to do it.

Body:
You might be able to use the variable created by the LEVELS options plus ORDER=FREQ. For example.

data have;
   input Groupvar:$1. Value;
   cards;
A           5
A           1
B           0
B           9
B           8
C           2
C           2
;;;;
   run;
proc summary nway order=freq missing;
   class groupvar;
   freq value;
   output out=test(drop=_type_ index=(groupvar)) / levels;
   run;
proc print;
   run;
data want;
   merge have test;
   by groupvar;
   run;
proc print;
   run;