问:
locking only when modifying vs entire method
When should locks be used? Only when modifying data or when accessing it as well?

```<code>public class Test {
    static Dictionary<string, object> someList = new Dictionary<string, object>();

    static object syncLock = new object();

    public static object GetValue(string name) {
        if (someList.ContainsKey(name)) {
            return someList[name];
        } else {
            lock(syncLock) {
                object someValue = GetValueFromSomeWhere(name);
                someList.Add(name, someValue);
            }
        }
    }
}
</code>```

Should there be a lock around the the entire block or is it ok to just add it to the actual modification? My understanding is that there still could be some race condition where one call might not have found it and started to add it while another call right after might have also run into the same situation - but I'm not sure. Locking is still so confusing. I haven't run into any issues with the above similar code but I could just be lucky so far. Any help above would be appriciated as well as any good resources for how/when to lock objects.

答:
If a resource can only be accessed by multiple threads, you do not need any locks.

If a resource can be accessed by multiple threads and can be modified, then all accesses/modifications need to be synchronized. In your example, if GetValueFromSomeWhere takes a long time to return, it is possible for a second call to be made with the same value in name, but the value has not been stored in the Dictionary.

Body:
When should locks be used? Only when modifying data or when accessing it as well?

public class Test {
    static Dictionary<string, object> someList = new Dictionary<string, object>();

    static object syncLock = new object();

    public static object GetValue(string name) {
        if (someList.ContainsKey(name)) {
            return someList[name];
        } else {
            lock(syncLock) {
                object someValue = GetValueFromSomeWhere(name);
                someList.Add(name, someValue);
            }
        }
    }
}

Should there be a lock around the the entire block or is it ok to just add it to the actual modification? My understanding is that there still could be some race condition where one call might not have found it and started to add it while another call right after might have also run into the same situation - but I'm not sure. Locking is still so confusing. I haven't run into any issues with the above similar code but I could just be lucky so far. Any help above would be appriciated as well as any good resources for how/when to lock objects.


来源: stackexchange

ContentLicense: CC BY-SA 3.0

Title: how to divided two data frame col by col according the same ID?

Body:
I have two data frames with different length as follow:

> df1

V1         V2          V3      V4   V5      V6  V7  V8  V9  V10 V11 V12 V13 V14 V15
chr1    1572489     1575053     -   SSU72   182 464 288 437 521 646 490 213 411 535
chr1    231532572   231536297   -   TAF5L   28  62  28  48  12  41  31  32  19  22
chr1    97305156    97306558    -   DPYD    13  18  9   17  20  22  1   2   2   3
chr1    10380576    10386010    +   KIF1B   274 324 99  183 223 153 270 250 314 190

> df2

V1         V2           V3      V4  V5      V6  V7  V8  V9  V10 V11 V12 V13 V14 V15
chr1    1551810      1552304    -   SSU72   12  32  274 99  68  5   113 58  187 156
chr1    231526495   231528472   -   TAF5L   48  29  64  50  36  40  83  26  73  51
chr1    10453959    10459017    +   KIF1B   152 346 891 419 476 752 420 242 477 550
chr1    10455753    10459010    +   KIF1B   152 345 887 412 470 748 420 237 473 540
chr1    222514442   222516274   +   MARK1   2   6   5   6   2   10  2   6   3   14

I would like to create some ratios according with the name in V5. So for example, as SSU72 is in both data frames, I would like to create the ratio for V6 to V15 like this:

(df1$V6/df2$V6, df1$V7/df2$V7.....df1V15/df2$V15)

I've tried to create some loops but I am lost.

Body:
Please:

df1 <- df1[df1$V5 %in% df2$V5,]
df2 <- df2[df2$V5 %in% df1$V5,]
df1 <- df1[order(df1$V5),]
df2 <- df2[order(df2$V5),]
df1$V6_ <- df1$V6/df2$V6


问:
Appending to a private TextArea from a different class in Java

class Backend extends UI {
    // some code
    void start() {
        txtRespond.append(Bot + ": hello, " + Name + "\n"); /* have a problem accessing txtRespond */

public class UI extends javax.swing.JFrame {
    // some code
    private javax.swing.JTextArea txtRespond;
```

I'm trying to add sentences to my JTextArea from a different class.

答: You cannot access private variable of parent, make the variable txtRespond protected or create a getter for that variable.

Body:
class Backend extends UI {
    // some code
    void start() {
        txtRespond.append(Bot + ": hello, " + Name + "\n"); /* have a problem accessing txtRespond */

public class UI extends javax.swing.JFrame {
    // some code
    private javax.swing.JTextArea txtRespond;

I'm trying to add sentences to my JTextArea from a different class.


问:
DocusignAPI : How can I download the internal document out of envelope without the envelope_id automatic stamp?
I have DocuSign documents (.pdf extension documents that were signed by docusign). I'm trying to find a programmatic solution via DocuSign API how can I remove the "DocuSign Envelope ID: {GUID}" automatic stamp that exists on every top of page in the documents.

Is there such a solution inside DocuSign API? and if yes, how can it be done?

If not, what are the alternatives?

Thanks a lot.

答:
For new envelopes, you can set the envelopeIdStamping property in your createEnvelope request so that the stamp is not included. The stamp cannot be removed on completed envelopes.

```<code>{
 "envelopeIdStamping" : "false",
 "status": "sent",
 "emailSubject": "Example of one recipient, type signer",
 "documents": [],
 "recipients": {}
}
</code>```

Note that envelopeIdStamping is driven based on Account and Admin settings.
See this answer for more information.
See this page for other options.

Body:
For new envelopes, you can set the envelopeIdStamping property in your createEnvelope request so that the stamp is not included. The stamp cannot be removed on completed envelopes.

{
 "envelopeIdStamping" : "false",
 "status": "sent",
 "emailSubject": "Example of one recipient, type signer",
 "documents": [],
 "recipients": {}
}

Note that envelopeIdStamping is driven based on Account and Admin settings.
See this answer for more information.
See this page for other options.


问:
Convert.DateTime
What Convert.DateTime will convert the date 7/25/2010 12:00:00 it's current format is(MM/dd/yyyy HH:mm:ss)?

When I convert this string format to date time I am getting the error "string was not recognized as valid DateTime"

答:
DateTime.TryParse() or DateTime.Parse() will do the trick.

Edit: This is assuming that you are going from a string to a DateTime object.

Edit2: I just tested this with your input string, and I receive no error with DateTime.Parse

Title: Convert.DateTime

ContentLicense: CC BY-SA 2.5


问:
Square v2 API - Questions on filtering
When we wrote or initial integration for Square v1 API, there wasn't an option to filter ListOrders by Date

Our questions for v2 api:

In v2, looks like all transactions are housed under the same endpoint.

Okay, we call GET /transactions
  How do we tell what is an order vs. payment vs. refund in the response?

not all payments are generated off an order.  For example, I can do one-off Square transactions on my phone for walk-up customers, which would not have an order associated with it)

Can we filter for orders only?
  Does the Transaction endpoint supports date filtering now?

Thank you for your time

答:
Take a look at the documentation for the v2 Transaction object. Refunds and orders are subsets of that object.

Also look at the documentation for the List Transactions where you can see that you can currently filter based on times only right now.

If it isn't listed in the documentation, then it probably isn't supported.

Title: Square v2 API - Questions on filtering


问:
How can call a method in onCreateView Android
How can I call a  method in onCreateView in android Fragment?

onCreateView code:

```<code> public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         final Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_user_list, container, false);
    btnBusquedaUserList = (Button) rootView.findViewById(R.id.btnBuscarUserList);
    rvUserList = (RecyclerView) rootView.findViewById(R.id.rvUserList);
    rvUserList.setLayoutManager(new LinearLayoutManager(getContext()));
    txtCIbusqueda = (TextInputEditText) rootView.findViewById(R.id.txtCIUserList);

    getActivity().setTitle("Lista Usuarios Check In");
    Bundle args = getArguments();
    idUsuario = args.getString("idLogueado");

    GetClient();

    btnBusquedaUserList.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ciUser = txtCIbusqueda.getText().toString();
            Object lista[] = new Object[2];
            lista[0] = ciUser;
            lista[1] = idUsuario;
            parametroApi.setDatoG(lista);
            GetClient();

        }
    });

    return rootView;

};
</code>```

My method GetClient()

```<code>public void GetClient() {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://80.241.210.8:8080/Exma/Service/api/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    ExmaApi service = retrofit.create(ExmaApi.class);
    Call<Respuesta<List<DataList>>>call=service.putClientList(parametroApi);

       call.enqueue(new Callback<Respuesta<List<DataList>>>() {
        @Override
        public void onResponse(Call<Respuesta<List<DataList>>> call,
         Response<Respuesta<List<DataList>>> response) {
            if (response.isSuccessful()) {
                Respuesta<List<DataList>> respuesta = response.body();
                try {
                    if (respuesta.respuestaExitosa() == true) {
                        Log.d(TAG, "TodoBien: " + respuesta.toString());
                        rvAdapter = new MyRecyclerViewAdapter(getActivity().getApplicationContext(), respuesta);
                        rvUserList.setAdapter(rvAdapter);

                    }

                } catch (Exception e) {
                    Log.d(TAG, "onResponse" + "Ocurrio un Error");
                    e.printStackTrace();

                }
            }
        }

        @Override
        public void onFailure(Call<Respuesta<List<DataList>>> call, Throwable t) {
            Log.d(TAG, "TodoMal: " + t.getMessage().toString());

        }
    });

}
</code>```

I have trouble when I want to call a method GetClient() in onCreateView, the method does not start, but in onClickListener from the button, the method start without problems, any way to call the method? in onCreateView from Fragments, I want to execute the method at the time that fragment start

答:
Like Activities , Fragment have his own lifecycle

onCreateView : Called to have the fragment instantiate its user interface view. This is optional, and non-graphical fragments can
  return null (which is the default implementation). This will be called
  between onCreate(Bundle) and onActivityCreated(Bundle).

So you should move all initialization that doesn't concern graphical element in onStart(). For example :

```<code>public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         final Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_user_list, container, false);
    btnBusquedaUserList = (Button) rootView.findViewById(R.id.btnBuscarUserList);
    rvUserList = (RecyclerView) rootView.findViewById(R.id.rvUserList);
    rvUserList.setLayoutManager(new LinearLayoutManager(getContext()));
    txtCIbusqueda = (TextInputEditText) rootView.findViewById(R.id.txtCIUserList);

    return rootView;
};

@Override
public void onStart() {

    getActivity().setTitle("Lista Usuarios Check In");
    Bundle args = getArguments();
    idUsuario = args.getString("idLogueado");
    GetClient();

    btnBusquedaUserList.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ciUser = txtCIbusqueda.getText().toString();
            Object lista[] = new Object[2];
            lista[0] = ciUser;
            lista[1] = idUsuario;
            parametroApi.setDatoG(lista);
            GetClient();

        }
    });
}
</code>```

Hope this helps.

Sorry for my english.

Body:
How can I call a  method in onCreateView in android Fragment?

onCreateView code:

 public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         final Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_user_list, container, false);
    btnBusquedaUserList = (Button) rootView.findViewById(R.id.btnBuscarUserList);
    rvUserList = (RecyclerView) rootView.findViewById(R.id.rvUserList);
    rvUserList.setLayoutManager(new LinearLayoutManager(getContext()));
    txtCIbusqueda = (TextInputEditText) rootView.findViewById(R.id.txtCIUserList);

    getActivity().setTitle("Lista Usuarios Check In");
    Bundle args = getArguments();
    idUsuario = args.getString("idLogueado");

    GetClient();

    btnBusquedaUserList.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ciUser = txtCIbusqueda.getText().toString();
            Object lista[] = new Object[2];
            lista[0] = ciUser;
            lista[1] = idUsuario;
            parametroApi.setDatoG(lista);
            GetClient();

        }
    });

    return rootView;

};

My method GetClient()

public void GetClient() {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://80.241.210.8:8080/Exma/Service/api/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    ExmaApi service = retrofit.create(ExmaApi.class);
    Call<Respuesta<List<DataList>>>call=service.putClientList(parametroApi);

       call.enqueue(new Callback<Respuesta<List<DataList>>>() {
        @Override
        public void onResponse(Call<Respuesta<List<DataList>>> call,
         Response<Respuesta<List<DataList>>> response) {
            if (response.isSuccessful()) {
                Respuesta<List<DataList>> respuesta = response.body();
                try {
                    if (respuesta.respuestaExitosa() == true) {
                        Log.d(TAG, "TodoBien: " + respuesta.toString());
                        rvAdapter = new MyRecyclerViewAdapter(getActivity().getApplicationContext(), respuesta);
                        rvUserList.setAdapter(rvAdapter);

                    }

                } catch (Exception e) {
                    Log.d(TAG, "onResponse" + "Ocurrio un Error");
                    e.printStackTrace();

                }
            }
        }

        @Override
        public void onFailure(Call<Respuesta<List<DataList>>> call, Throwable t) {
            Log.d(TAG, "TodoMal: " + t.getMessage().toString());

        }
    });

}

I have trouble when I want to call a method GetClient() in onCreateView, the method does not start, but in onClickListener from the button, the method start without problems, any way to call the method? in onCreateView from Fragments, I want to execute the method at the time that fragment start

Body:
Like Activities , Fragment have his own lifecycle

onCreateView : Called to have the fragment instantiate its user interface view. This is optional, and non-graphical fragments can
  return null (which is the default implementation). This will be called
  between onCreate(Bundle) and onActivityCreated(Bundle).

So you should move all initialization that doesn't concern graphical element in onStart(). For example :

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         final Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_user_list, container, false);
    btnBusquedaUserList = (Button) rootView.findViewById(R.id.btnBuscarUserList);
    rvUserList = (RecyclerView) rootView.findViewById(R.id.rvUserList);
    rvUserList.setLayoutManager(new LinearLayoutManager(getContext()));
    txtCIbusqueda = (TextInputEditText) rootView.findViewById(R.id.txtCIUserList);

    return rootView;
};

@Override
public void onStart() {

    getActivity().setTitle("Lista Usuarios Check In");
    Bundle args = getArguments();
    idUsuario = args.getString("idLogueado");
    GetClient();

    btnBusquedaUserList.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ciUser = txtCIbusqueda.getText().toString();
            Object lista[] = new Object[2];
            lista[0] = ciUser;
            lista[1] = idUsuario;
            parametroApi.setDatoG(lista);
            GetClient();

        }
    });
}

Hope this helps.

Sorry for my english.


问:
Is Keyrock's Project the same as Fiware-Service?
I'm studying Keyrock's functionalities and I have the following questions:

Are Projects the same that Fiware-Service?

Are Applications the same that Fiware-ServicePath?

Thanks,

Gabriel

答:
I think that the IdM Keyrock has not a mapping between the Fiware-Service/Fiware-ServicePath headers and entities in IdM keystone data model. In Fact looking into the PEP Proxy code I could not find a reference to this headers (I did a "search everywhere" in the project source code =D ).

This is, from my point of view quite interesting. Sadly I have not much experience with this implementation of the IdM GE, in fact I workerd with the Telefonica implementations of the IdM, PEP Proxy and Authorization PDP GEs.

What I can tell you for sure, is that Telefonica implementations and GING implementations are quite different. For example the Telefonica's Keystone has a direct mapping between Fiware-Service and Fiware-ServicePath wich is by the way the following:

Fiware-Service: Keystone Domain

Fiware-ServicePath: Keystone Project

In the case of the GING's Keystone, I believe that they use a single Keystone domain called "Default" and inside this domain they have organizations represented as Keystone projects. How ever, the thing seems much more complicated because GING bases his authentication model in OAuth2. Looking into de IdM data model (I enabled MySQL persistence and then saw the database schema) I did not see any relationship beetween OAuth2 applications (take a look to the table called "consumer_oauth2") and Fiware-Service or Fiware-ServicePath headers.

I think that some kind of orientation from the Fiware people, would be very helpful at this point because I have the same question.

I hope my answer has been helpful at some point.


问:
Dynamic breadcrumbs using react router
There is very good example of how to make a breadcrumbs on site in examples folder of react-router repo. But I'm wondering how to make breadcrumbs with dynamic routes.

Assume we have this configuration:

```<code>ReactDOM.render((
<Router history={browserHistory}>
    <Route path="/projects" component={ProjectsApp}>
        <IndexRoute component={ProjectsDashboard} />
        <Route path=":projectId" component={ProjectBoard}>
            <Route path=":taskId" component={ProjectTaskBoard}>
        </Route>
    </Route>
</Router>
), document.getElementById('app'));
</code>```

I want to make something like this:

Projects(link to '/projects') -> MyAwesomeProject (link to '/projects/11'. Title taken from somewhere (from store by id from routeParams or by another way)) -> MyTask (link to '/projects/11/999')

How can I achieve this result? Are there any best practices? Thanks.

答:
With react-router v4, all routes are dynamic (although I think there are still options to write static definitions).

As mentioned by @tbo in there comment, react-breadcrumbs was an ok solution for implementing this with version 3 of react-router. There were even some workarounds for the dynamic breadcrumbs you describe (e.g. using the prepend or getDisplayName props).

There is a conversation going on in this issue to determine how to best support react-router v4 which definitely ties into your question as well. I've dug through a bunch of other breadcrumbs component repositories which all seem to struggle from with the same static route issues, some having similar issues open for figuring out v4 support.

TLDR; If you're still on react-router v3, you can probably make the react-breadcrumbs package work for dynamic breadcrumbs. If you've migrated to v4, stay tuned and I'll hopefully have a better answer soon.

Update

After finding no other solutions that fit my needs I developed a solution and opened a pull request on the react-breadcrumbs repository. Auto-breadcrumb, as mentioned below, and this discussion are also potential solutions but allow less customization. If you need more customization, subscribe to and feel free to comment on or help with the pr.

Update (2020)

That pull request was merged, and react-breadcrumbs now works great for react-router version 4 and up.

Title: Dynamic breadcrumbs using react router

Body:
There is very good example of how to make a breadcrumbs on site in examples folder of react-router repo. But I'm wondering how to make breadcrumbs with dynamic routes.

Assume we have this configuration:

ReactDOM.render((
<Router history={browserHistory}>
    <Route path="/projects" component={ProjectsApp}>
        <IndexRoute component={ProjectsDashboard} />
        <Route path=":projectId" component={ProjectBoard}>
            <Route path=":taskId" component={ProjectTaskBoard}>
        </Route>
    </Route>
</Router>
), document.getElementById('app'));

I want to make something like this:

Projects(link to '/projects') -> MyAwesomeProject (link to '/projects/11'. Title taken from somewhere (from store by id from routeParams or by another way)) -> MyTask (link to '/projects/11/999')

How can I achieve this result? Are there any best practices? Thanks.

ContentLicense: CC BY-SA 4.0


问:
If checkbox is checked, change only style of that item
I'm making a checkbox list and when someone checks a checkbox, I need it to change text from pending to done and also change the background to green. I've managed to make all that work with jQuery.

Except it styles every checkbox container and not just the one checked. How can I fix that? And how can I make it change back to its original style if someone unchecks the checkbox again after?

This is my code so far:

$('.custom-control-input').click(function(){
    if (this.checked) {
        $('.pending').css('display', 'none')
        $('.done').css('display', 'block')
        $('.list-group-item').css('background-color','#4CAF50')
    }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.done {
  display: none;
}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

      <input type="checkbox" class="custom-control-input">

      Checkbox

done

pending

      <input type="checkbox" class="custom-control-input">

      Checkbox

done

pending

      <input type="checkbox" class="custom-control-input">

      Checkbox

done

pending

      <input type="checkbox" class="custom-control-input">

      Checkbox

done

pending

```

答:
This script will fix

$('.custom-control-input').click(function(){
    $(this).parents('.list-group-item').css('background-color', '#fdb515');
    $(this).parents('.list-group-item').find('.mb-0.done').show();
    $(this).parents('.list-group-item').find('.mb-0.pending').hide();
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.mb-0.done{
  display:none;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>

      <input type="checkbox" class="custom-control-input">

      Checkbox

done

pending

      <input type="checkbox" class="custom-control-input">

      Checkbox

done

pending

      <input type="checkbox" class="custom-control-input">

      Checkbox

done

pending

      <input type="checkbox" class="custom-control-input">

      Checkbox

done

pending

```

Body:
I'm making a checkbox list and when someone checks a checkbox, I need it to change text from pending to done and also change the background to green. I've managed to make all that work with jQuery.

Except it styles every checkbox container and not just the one checked. How can I fix that? And how can I make it change back to its original style if someone unchecks the checkbox again after?

This is my code so far:

$('.custom-control-input').click(function(){
    if (this.checked) {
        $('.pending').css('display', 'none')
        $('.done').css('display', 'block')
        $('.list-group-item').css('background-color','#4CAF50')
    }
})

.done {
  display: none;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

      <input type="checkbox" class="custom-control-input">

      Checkbox

done

pending

      <input type="checkbox" class="custom-control-input">

      Checkbox

done

pending

      <input type="checkbox" class="custom-control-input">

      Checkbox

done

pending

      <input type="checkbox" class="custom-control-input">

      Checkbox

done

pending

Body:
This script will fix

$('.custom-control-input').click(function(){
    $(this).parents('.list-group-item').css('background-color', '#fdb515');
    $(this).parents('.list-group-item').find('.mb-0.done').show();
    $(this).parents('.list-group-item').find('.mb-0.pending').hide();
})

.mb-0.done{
  display:none;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="list-group">
  <li class="list-group-item">
    <div class="form-check">
    <label class="custom-control custom-checkbox">
      <input type="checkbox" class="custom-control-input">
      <span class="custom-control-indicator"></span>
      <span class="custom-control-description ml-4">Checkbox</span>
    </label>
</div> <!-- /.form-check -->
    <div class="ml-auto status">
      <p class="mb-0 done">done</p>
      <p class="mb-0 pending">pending</p>
    </div>
  </li>
  <li class="list-group-item">
    <div class="form-check">
    <label class="custom-control custom-checkbox">
      <input type="checkbox" class="custom-control-input">
      <span class="custom-control-indicator"></span>
      <span class="custom-control-description ml-4">Checkbox</span>
    </label>
  </div> <!-- /.form-check -->
    <div class="ml-auto status">
      <p class="mb-0 done">done</p>
      <p class="mb-0 pending">pending</p>
    </div>
  </li>
  <li class="list-group-item">
    <div class="form-check">
    <label class="custom-control custom-checkbox">
      <input type="checkbox" class="custom-control-input">
      <span class="custom-control-indicator"></span>
      <span class="custom-control-description ml-4">Checkbox</span>
    </label>
  </div> <!-- /.form-check -->
    <div class="ml-auto status">
      <p class="mb-0 done">done</p>
      <p class="mb-0 pending">pending</p>
    </div>
  </li>
  <li class="list-group-item">
    <div class="form-check">
    <label class="custom-control custom-checkbox">
      <input type="checkbox" class="custom-control-input">
      <span class="custom-control-indicator"></span>
      <span class="custom-control-description ml-4">Checkbox</span>
    </label>
</div> <!-- /.form-check -->
    <div class="ml-auto status">
      <p class="mb-0 done">done</p>
      <p class="mb-0 pending">pending</p>
    </div>
  </li>
</ul>


问:
which slices form a P Frame or B Frame
In a H.264 bit stream, how can I find which p-slices/b-slices form which frame? Does the frame_num help anyway? Also in my source file(.264 file), frame_num field values are inconsistent, i.e, in first slice it is 10, later it becomes 5 like that. Is it okay? Should I use p-slices exactly in that order to make frames?

答: PArse the slice header. That will tell you what macroblocks are encoded into the slice. Once all macroblobs are accounted for, you are at the end of the frame. You can get the macroblock per frame number by parsing the SPS. </p>

Title: which slices form a P Frame or B Frame


问:
What does Future.cancel() do if not interrupting?
From java docs on Future.cancel()

```<code>boolean cancel(boolean mayInterruptIfRunning)
</code>```

Attempts to cancel execution of this task. This attempt will fail if the task has already completed, has already been cancelled, or could not be cancelled for some other reason. If successful, and this task has not started when cancel is called, this task should never run. If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted in an attempt to stop the task.

My question is what does cancel do if mayInterruptIfRunning  is false?

how does it cancel or stop the task from executing if it has already been run?

答:
nothing will be done if the task has already started and mayInterruptIfRunning is false,

below is the cancel()

```<code>public boolean cancel(boolean mayInterruptIfRunning) {
    if (state != NEW)
        return false;
    if (mayInterruptIfRunning) {
        if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, INTERRUPTING))
            return false;
        Thread t = runner;
        if (t != null)
            t.interrupt();
        UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED); // final state
    }
    else if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, CANCELLED))
        return false;
    finishCompletion();
    return true;
}
</code>```

we can see that if mayInterruptIfRunning is false,cancel() just change state from NEW to CANCELLED and return false,nothing else will be done

Body:
From java docs on Future.cancel()

boolean cancel(boolean mayInterruptIfRunning)

Attempts to cancel execution of this task. This attempt will fail if the task has already completed, has already been cancelled, or could not be cancelled for some other reason. If successful, and this task has not started when cancel is called, this task should never run. If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted in an attempt to stop the task.

My question is what does cancel do if mayInterruptIfRunning  is false?

how does it cancel or stop the task from executing if it has already been run?

Body:
nothing will be done if the task has already started and mayInterruptIfRunning is false,

below is the cancel()

public boolean cancel(boolean mayInterruptIfRunning) {
    if (state != NEW)
        return false;
    if (mayInterruptIfRunning) {
        if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, INTERRUPTING))
            return false;
        Thread t = runner;
        if (t != null)
            t.interrupt();
        UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED); // final state
    }
    else if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, CANCELLED))
        return false;
    finishCompletion();
    return true;
}

we can see that if mayInterruptIfRunning is false,cancel() just change state from NEW to CANCELLED and return false,nothing else will be done


问:
Zend Framework 3 translator from DB
I've recently started working with ZF3 and I'm working on internationalization of the project.

I've managed to get it work but I'd like to make the translator get the translates from the database instead of reading them from .mo files. This way the user would be able to edit them in admin part of the application.

I have installed the Zend\Mvc\I18n module, registered it as a view_helper

```<code>// module's module.config.php:
'view_helpers' => [
    'invokables' => [
        'translate' => \Zend\I18n\View\Helper\Translate::class
    ]
]
</code>```

and instead of

```<code>// module's module.config.php:
'translator' => [
    'locale' => 'en_US',
    'translation_file_patterns' => [
        [
            'type'     => 'gettext',
            'base_dir' => __DIR__ . '/../language',
            'pattern'  => '%s.mo',
        ],
    ],
]
</code>```

I have

```<code>// module's module.config.php:
'translator' => [
    'locale' => 'en_US',
    'remote_translation' => [
        [
            'type' => Service\Database::class
        ]
    ]
]
</code>```

and the Database service implements the RemoteLoaderInterface as required in the documentation, right now it has a hard-coded array but will later on replaced by the actual query.

```<code>//Database.php
namespace Core\Service;

use Zend\I18n\Translator\Loader\RemoteLoaderInterface;

class Database implements RemoteLoaderInterface {

    private $entityManager;

    public function __construct($entityManager)
    {
        $this->entityManager = $entityManager;
    }

    public function load($locale, $textDomain)
    {
        $array = [];
        $array['and'] = 'i';
        return $array;
    }
}
</code>```

In my layout printing

```<code>// layout.phtml
$this->translate("and") // prints "i"
</code>```

results in a "i", which is just what I wanted.

Now, my problem is how do I pass the doctrine entity manager to the Database service? I know I have to use a factory in these situations and I have one ready

```<code>//DatabaseFactory.php
namespace Core\Service\Factory;

use Core\Service\Database;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;

class DatabaseFactory implements FactoryInterface
{
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        $entityManager = $container->get('doctrine.entitymanager.orm_default');

        // Instantiate the service and inject dependencies
        return new Database($entityManager);
    }

}
</code>```

but I simply can't pass it in the module configuration because it requires the class to implement the RemoteLoaderInterface.

```<code>// module's module.config.php:
'remote_translation' => [
    [
        'type' => Service\Factory\DatabaseFactory::class // does not work
    ]
]
</code>```

Is there a workaround or anything I'm missing? Any help would be appreciated. Thanks in advice!

答:
This is a little bit tricky. You have to setup a translation loader factory before rendering occurs.

module\Application\src\Module.php:

```<code>public function init (ModuleManager $manager)
{
    $eventManager = $manager->getEventManager();
    $sharedEventManager = $eventManager->getSharedManager();

    $sharedEventManager->attach(__NAMESPACE__, 'dispatch',
        [$this, 'onDispatch'], 100);
}

public function onDispatch (MvcEvent $event)
{
    $translator = $event->getApplication ()->getServiceManager ()->get (\Zend\I18n\Translator\TranslatorInterface::class);
    $translator->getPluginManager()->setFactory(\Application\Translator\Database::class, \Application\Translator\DatabaseFactory::class);
</code>```

I don't know of any other way to configure service locator for the translator.

Title: Zend Framework 3 translator from DB

Body:
I've recently started working with ZF3 and I'm working on internationalization of the project.

I've managed to get it work but I'd like to make the translator get the translates from the database instead of reading them from .mo files. This way the user would be able to edit them in admin part of the application.

I have installed the Zend\Mvc\I18n module, registered it as a view_helper

// module's module.config.php:
'view_helpers' => [
    'invokables' => [
        'translate' => \Zend\I18n\View\Helper\Translate::class
    ]
]

and instead of

// module's module.config.php:
'translator' => [
    'locale' => 'en_US',
    'translation_file_patterns' => [
        [
            'type'     => 'gettext',
            'base_dir' => __DIR__ . '/../language',
            'pattern'  => '%s.mo',
        ],
    ],
]

I have

// module's module.config.php:
'translator' => [
    'locale' => 'en_US',
    'remote_translation' => [
        [
            'type' => Service\Database::class
        ]
    ]
]

and the Database service implements the RemoteLoaderInterface as required in the documentation, right now it has a hard-coded array but will later on replaced by the actual query.

//Database.php
namespace Core\Service;

use Zend\I18n\Translator\Loader\RemoteLoaderInterface;

class Database implements RemoteLoaderInterface {

    private $entityManager;

    public function __construct($entityManager)
    {
        $this->entityManager = $entityManager;
    }

    public function load($locale, $textDomain)
    {
        $array = [];
        $array['and'] = 'i';
        return $array;
    }
}

In my layout printing

// layout.phtml
$this->translate("and") // prints "i"

results in a "i", which is just what I wanted.

Now, my problem is how do I pass the doctrine entity manager to the Database service? I know I have to use a factory in these situations and I have one ready

//DatabaseFactory.php
namespace Core\Service\Factory;

use Core\Service\Database;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;

class DatabaseFactory implements FactoryInterface
{
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        $entityManager = $container->get('doctrine.entitymanager.orm_default');

        // Instantiate the service and inject dependencies
        return new Database($entityManager);
    }

}

but I simply can't pass it in the module configuration because it requires the class to implement the RemoteLoaderInterface.

// module's module.config.php:
'remote_translation' => [
    [
        'type' => Service\Factory\DatabaseFactory::class // does not work
    ]
]

Is there a workaround or anything I'm missing? Any help would be appreciated. Thanks in advice!

Body:
This is a little bit tricky. You have to setup a translation loader factory before rendering occurs.

module\Application\src\Module.php:

public function init (ModuleManager $manager)
{
    $eventManager = $manager->getEventManager();
    $sharedEventManager = $eventManager->getSharedManager();

    $sharedEventManager->attach(__NAMESPACE__, 'dispatch',
        [$this, 'onDispatch'], 100);
}

public function onDispatch (MvcEvent $event)
{
    $translator = $event->getApplication ()->getServiceManager ()->get (\Zend\I18n\Translator\TranslatorInterface::class);
    $translator->getPluginManager()->setFactory(\Application\Translator\Database::class, \Application\Translator\DatabaseFactory::class);

I don't know of any other way to configure service locator for the translator.


问:
How show json data with database in symfony
I have a little problem, because I have to show json date with database in Symfony3.

My controller

```<code>/**
     * @Route("/api/rest", name="rest_api")
     *
     *
     * @Template
     */
public function indexAction(Request $Request) {

    $Repo = $this->getDoctrine()->getRepository('CommonUserBundle:Comment');
    $row = $Repo->findAll();

    $data = json_encode($row, true);

    return array(
        'comment' => $data
    );
}
</code>```

And this is my layout in html.twig

```<code>{% for comments in comment %}
           {{ comments }}
{% endfor %}
</code>```

But I don't know why nothing show.
Help me please :)

答:
Ok using my deductive skills (as your question is a bit vague) I am going to make the opposite assumption as everyone else did and say use the JSON helper function (Since 3.2).

```<code>return $this->json($myThings);
</code>```

If you are working in older versions you need to return a proper Response object with the headers and such.

Body:
I have a little problem, because I have to show json date with database in Symfony3.

My controller

/**
     * @Route("/api/rest", name="rest_api")
     *
     *
     * @Template
     */
public function indexAction(Request $Request) {

    $Repo = $this->getDoctrine()->getRepository('CommonUserBundle:Comment');
    $row = $Repo->findAll();

    $data = json_encode($row, true);

    return array(
        'comment' => $data
    );
}

And this is my layout in html.twig

{% for comments in comment %}
           {{ comments }}
{% endfor %}

But I don't know why nothing show.
Help me please :)

Body:
Ok using my deductive skills (as your question is a bit vague) I am going to make the opposite assumption as everyone else did and say use the JSON helper function (Since 3.2).

return $this->json($myThings);

If you are working in older versions you need to return a proper Response object with the headers and such.


问:
How to print a line from a file that has the exact same index of the student?
I have students in file with first name,last name and index.

This is my txt file:

```<code>Jon Wick 1569
Mark Jones 1489
Mike Miler 2050
</code>```

I want the user to input an index number and program should print the line with same index of student.

this is my code:

```<code>    char ch;
    int index;
    FILE *pfile;

    pfile = fopen("student.txt","r");
    printf("Enter index of student: ");
    scanf("%d",&index);
    while((ch = fgetc(pfile)) != EOF){
        ...
    }

    fclose(pfile);
</code>```

答:
If I understand your question correctly, you can do this by:

```<code>#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE* file = fopen("student.txt", "r");
    if (file == NULL) {
      printf ("File cannot open\n");
      return 1;
    }
    char line[256];
    int index,search;
    printf("Please enter the student index?\n");
    scanf("%d", &search);
    while (fgets(line, sizeof(line), file)) {
        sscanf(line,"%*[^0-9]%d",&index);
        if(search == index)
        {
            printf("%s", line);
        }
    }
    fclose(file);
    return 0;
}
</code>```

If I didn't, add a comment below and I will try to improve my answer. It reads file line by line and then get integer form the line. That is student index. Compare it with the search value, if it satisfy. Then print it print that line.

Body:
I have students in file with first name,last name and index.

This is my txt file:

Jon Wick 1569
Mark Jones 1489
Mike Miler 2050

I want the user to input an index number and program should print the line with same index of student.

this is my code:

    char ch;
    int index;
    FILE *pfile;

    pfile = fopen("student.txt","r");
    printf("Enter index of student: ");
    scanf("%d",&index);
    while((ch = fgetc(pfile)) != EOF){
        ...
    }

    fclose(pfile);

Body:
If I understand your question correctly, you can do this by:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE* file = fopen("student.txt", "r");
    if (file == NULL) {
      printf ("File cannot open\n");
      return 1;
    }
    char line[256];
    int index,search;
    printf("Please enter the student index?\n");
    scanf("%d", &search);
    while (fgets(line, sizeof(line), file)) {
        sscanf(line,"%*[^0-9]%d",&index);
        if(search == index)
        {
            printf("%s", line);
        }
    }
    fclose(file);
    return 0;
}

If I didn't, add a comment below and I will try to improve my answer. It reads file line by line and then get integer form the line. That is student index. Compare it with the search value, if it satisfy. Then print it print that line.


问:
pssh and known_hosts file
when I use pssh, trying to access a remote machine which is not inside the UNIX
known hosts file, pssh freeze after giving the password.
After having added the host using a direct ssh command, pssh works.

So is there an option to give to the pssh command in order to avoid this problem ?

Thanks for your help,
Regards

答:
Try pssh -O StrictHostKeyChecking=no. This works for me.

By default ssh uses the value of "ask", which causes it to ask the user whether to continue connecting to unknown host. By setting the value to "no", you avoid the question, but are no longer protected against certain attacks. E.g. if you are connecting to hostA, and someone puts hostB there with the same IP address, then by default ssh will notice that hostB has changed, and will prompt you about it. With StrictHostKeyChecking=no, it will silently assume everything is OK.

Title: pssh and known_hosts file


问:
Create a new pandas column with a value from a user-defined function
I am getting a SettingWithCopyWarning when attempting to create a new column on a pandas dataframe using a function I created to return a value for that new column. I am using the movielens dataset and predicting the rating of a user on a movie.

This is an example of my dataframe:

Now if I want to add a new column called 'prediction' that sends the user_id and item_id to my function and return the prediction I have followed the advice of this other question

Hence using the code:

```<code>df['pred'] = df.apply(lambda x: predict_rating(x['user_id'], x['item_id']), axis =1)
</code>```

Yet I keep getting the SettingWithCopyWarning.

:44: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

Any advice would be welcome.

答:
It worked for me with this minimal example:

```<code>import pandas as pd

df = pd.DataFrame({'user_id':[22,224], 'item_id': [377,29], 'rating': [1,3]})
def prediction_func(row):
    return row['user_id'] + row['item_id']

df['prediction'] = df.apply(prediction_func, axis=1)
print(df.head())
</code>```

Output:

```<code>   item_id  rating  user_id  prediction
0      377       1       22         399
1       29       3      224         253
</code>```

Body:
I am getting a SettingWithCopyWarning when attempting to create a new column on a pandas dataframe using a function I created to return a value for that new column. I am using the movielens dataset and predicting the rating of a user on a movie.

This is an example of my dataframe:

Now if I want to add a new column called 'prediction' that sends the user_id and item_id to my function and return the prediction I have followed the advice of this other question

Hence using the code:

df['pred'] = df.apply(lambda x: predict_rating(x['user_id'], x['item_id']), axis =1)

Yet I keep getting the SettingWithCopyWarning.

:44: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

Any advice would be welcome.

Body:
It worked for me with this minimal example:

import pandas as pd

df = pd.DataFrame({'user_id':[22,224], 'item_id': [377,29], 'rating': [1,3]})
def prediction_func(row):
    return row['user_id'] + row['item_id']

df['prediction'] = df.apply(prediction_func, axis=1)
print(df.head())

Output:

   item_id  rating  user_id  prediction
0      377       1       22         399
1       29       3      224         253


问:
UIApplicationExitOnSuspend for Suspend not Background
I have an application that tends to stay awake in the background due to it playing music; however, on a rare occasion if the music stops between songs for longer than expected(can be relatively short amount of time) due to connectivity issues or the user mutes the music, the application will become suspended. I am aware of UIApplicationExitOnSuspend but unlike the description of it, this actually exits on entering background. I have done a fair amount of research, I am aware there are no system notifications for entering suspending state.

Is there anyway to identify on leaving suspended state that the app was suspended? Alternatively is there anyways to do something similar to UIApplicationExitOnSuspend except only when the application actually is suspended not just when it goes into the background?

答:
I ended up creating a small class to identify when the app has gone into a suspended state:</p>

```<code>class SuspendedMonitor {
  static let shared = SuspendedMonitor()

  var delegate: SuspendedMonitorDelegate?

  private let Interval = 10.0

  private let MaxDelta = 2.0

  private var _timestamp: Double

  private var _timer: Timer?

  private init() {
    _timestamp = timeInMs()
  }

  public func start() {
    _timestamp = timeInMs()

    NotificationCenter.default.addObserver(
      self,
      selector: #selector(enterForeground),
      name: NSNotification.Name.UIApplicationWillEnterForeground,
      object: nil
    )

    NotificationCenter.default.addObserver(
      self,
      selector: #selector(enterBackground),
      name: NSNotification.Name.UIApplicationDidEnterBackground,
      object: nil
    )
  }

  @objc func enterForeground() {
    checkSync()
    _timer?.invalidate()
  }

  @objc func enterBackground() {
    _timestamp = timeInMs()
    setupTimer()
  }

  @objc func incrementTime() {
    _timestamp = _timestamp + (Interval * 1000)
  }

  private func setupTimer() {
    _timer = Timer.scheduledTimer(
      timeInterval: Interval,
      target: self,
      selector: #selector(incrementTime),
      userInfo: nil,
      repeats: true
    )
  }

  private func checkSync() {
    if timeInMs() - _timestamp > ((Interval + MaxDelta) * 1000) { appSuspended() }
  }

  private func appSuspended() {
    delegate?.appDidSuspend(self)
  }

}

protocol SuspendedMonitorDelegate: class {
  func appDidSuspend(_ monitor: SuspendedMonitor)
}
</code>```

Body:
I ended up creating a small class to identify when the app has gone into a suspended state:

class SuspendedMonitor {
  static let shared = SuspendedMonitor()

  var delegate: SuspendedMonitorDelegate?

  private let Interval = 10.0

  private let MaxDelta = 2.0

  private var _timestamp: Double

  private var _timer: Timer?

  private init() {
    _timestamp = timeInMs()
  }

  public func start() {
    _timestamp = timeInMs()

    NotificationCenter.default.addObserver(
      self,
      selector: #selector(enterForeground),
      name: NSNotification.Name.UIApplicationWillEnterForeground,
      object: nil
    )

    NotificationCenter.default.addObserver(
      self,
      selector: #selector(enterBackground),
      name: NSNotification.Name.UIApplicationDidEnterBackground,
      object: nil
    )
  }

  @objc func enterForeground() {
    checkSync()
    _timer?.invalidate()
  }

  @objc func enterBackground() {
    _timestamp = timeInMs()
    setupTimer()
  }

  @objc func incrementTime() {
    _timestamp = _timestamp + (Interval * 1000)
  }

  private func setupTimer() {
    _timer = Timer.scheduledTimer(
      timeInterval: Interval,
      target: self,
      selector: #selector(incrementTime),
      userInfo: nil,
      repeats: true
    )
  }

  private func checkSync() {
    if timeInMs() - _timestamp > ((Interval + MaxDelta) * 1000) { appSuspended() }
  }

  private func appSuspended() {
    delegate?.appDidSuspend(self)
  }

}

protocol SuspendedMonitorDelegate: class {
  func appDidSuspend(_ monitor: SuspendedMonitor)
}


问:
Extract integer from a list
I have a list like ['-1', '1,2,3', '2'] and I want to extract all the integers in it.
I don't know the number of integers in each position of the list ie the list can also be ['2,3,4','1,2,3','-1'] but it will never have an empty string.
So I want that the answer should be [2,3,4,1,2,3,-1]

What is the best way to do so in terms of complexity as well as less code.

Thanks...

答:
```<code>map(int, ','.join(l).split(','))
</code>```

where l is your list.

Title: Extract integer from a list

Body:
map(int, ','.join(l).split(','))

where l is your list.


问:
GCM Push Notifications are not coming on iPhone when app is not active for one day
On iPhone/iPad after installing the app, app is able to receive notification first time. Once app is inactive, then it stops getting notification in both foreground and background.

Can someone point, what I am I missing . Looks like no issue with message format since I get first time.

Server Code:

```<code>            message.put("priority", "high");
            message.put("content_available",true);
            if (to != null)
            {
                message.put("to", to.replace("\\", ""));
            }
            if (messageId != null)
            {
                message.put("message_id", messageId);
            }
            JSONObject subobj = new JSONObject();
            subobj.put("sound", "default");
            message.put("notification", subobj);

            message.put("data", payload);
            if (timeToLive != null)
            {
                message.put("time_to_live", timeToLive);
            }
            if (delayWhileIdle != null && delayWhileIdle)
            {
                message.put("delay_while_idle", true);
            }
            if (collapseKey != null)
            {
                message.put("collapse_key", collapseKey);
            }
            message.put("delivery_receipt_requested", true);
</code>```

Client Code:

```<code>     - (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
</code>```

{

```<code>// First run Delete keychain

if (![[NSUserDefaults standardUserDefaults] objectForKey:@"FirstRun"]) {
    // Delete values from keychain here

    application.applicationIconBadgeNumber = 0;

    [self resetKeychain];
    [[NSUserDefaults standardUserDefaults] setValue:@"1strun" forKey:@"FirstRun"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

self.viewController = [[MainViewController alloc] init];

CGRect screenBounds = [[UIScreen mainScreen] bounds];

#if __has_feature(objc_arc)
    self.window = [[UIWindow alloc] initWithFrame:screenBounds];
#else
   self.window = [[[UIWindow alloc] initWithFrame:screenBounds]
autorelease];
#endif
self.window.autoresizesSubviews = YES;
//notification

[self updateDurationLabel];
UIFont *font = [UIFont boldSystemFontOfSize:10.0f];
NSDictionary *attributes = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
[self.segFromStyle setTitleTextAttributes:attributes forState:UIControlStateNormal];
[self.segToStyle setTitleTextAttributes:attributes forState:UIControlStateNormal];

[self flowManager];

UILocalNotification *remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (remoteNotification) {
    application.applicationIconBadgeNumber = 0;
    self.launchNotification = remoteNotification.userInfo;

    NSLog(@"NotificationCheck: remoteNotification");

}

UILocalNotification *localNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];

if (localNotification) {
    application.applicationIconBadgeNumber = 0;
    NSLog(@"NotificationCheck: localNotification");

    self.launchNotification = localNotification.userInfo;

    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:localNotification.userInfo options:0 error:nil];
    NSString* jsonString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];

    NSLog(@"Dict:%@", jsonString);
      }
[self.window makeKeyAndVisible];

return YES;
</code>```

}

答:
You may refer with this thread wherein it suggested to add the "priority": "high" to the JSON toget the notifications in the background.

```<code>{
  "to" : "token...",
  "priority": "high",
  "notification" : {
    "title": "GCM TITLE",
    "body" : "FROM GCM",
    "badge": "1",
    "sound": "default"
  }
}
</code>```

Additional references:

GCM push notification to iOS with content_available (not working to invoke from inactive state)

GCM support for ios application when application in background or killed

Making GCM work for iOS device in the background

Body:
On iPhone/iPad after installing the app, app is able to receive notification first time. Once app is inactive, then it stops getting notification in both foreground and background.

Can someone point, what I am I missing . Looks like no issue with message format since I get first time.

Server Code:

            message.put("priority", "high");
            message.put("content_available",true);
            if (to != null)
            {
                message.put("to", to.replace("\\", ""));
            }
            if (messageId != null)
            {
                message.put("message_id", messageId);
            }
            JSONObject subobj = new JSONObject();
            subobj.put("sound", "default");
            message.put("notification", subobj);

            message.put("data", payload);
            if (timeToLive != null)
            {
                message.put("time_to_live", timeToLive);
            }
            if (delayWhileIdle != null && delayWhileIdle)
            {
                message.put("delay_while_idle", true);
            }
            if (collapseKey != null)
            {
                message.put("collapse_key", collapseKey);
            }
            message.put("delivery_receipt_requested", true);

Client Code:

     - (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions

{

// First run Delete keychain

if (![[NSUserDefaults standardUserDefaults] objectForKey:@"FirstRun"]) {
    // Delete values from keychain here

    application.applicationIconBadgeNumber = 0;

    [self resetKeychain];
    [[NSUserDefaults standardUserDefaults] setValue:@"1strun" forKey:@"FirstRun"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

self.viewController = [[MainViewController alloc] init];

CGRect screenBounds = [[UIScreen mainScreen] bounds];

#if __has_feature(objc_arc)
    self.window = [[UIWindow alloc] initWithFrame:screenBounds];
#else
   self.window = [[[UIWindow alloc] initWithFrame:screenBounds]
autorelease];
#endif
self.window.autoresizesSubviews = YES;
//notification

[self updateDurationLabel];
UIFont *font = [UIFont boldSystemFontOfSize:10.0f];
NSDictionary *attributes = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
[self.segFromStyle setTitleTextAttributes:attributes forState:UIControlStateNormal];
[self.segToStyle setTitleTextAttributes:attributes forState:UIControlStateNormal];

[self flowManager];

UILocalNotification *remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (remoteNotification) {
    application.applicationIconBadgeNumber = 0;
    self.launchNotification = remoteNotification.userInfo;

    NSLog(@"NotificationCheck: remoteNotification");

}

UILocalNotification *localNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];

if (localNotification) {
    application.applicationIconBadgeNumber = 0;
    NSLog(@"NotificationCheck: localNotification");

    self.launchNotification = localNotification.userInfo;

    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:localNotification.userInfo options:0 error:nil];
    NSString* jsonString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];

    NSLog(@"Dict:%@", jsonString);
      }
[self.window makeKeyAndVisible];

return YES;

}

Body:
You may refer with this thread wherein it suggested to add the "priority": "high" to the JSON toget the notifications in the background.

{
  "to" : "token...",
  "priority": "high",
  "notification" : {
    "title": "GCM TITLE",
    "body" : "FROM GCM",
    "badge": "1",
    "sound": "default"
  }
}

Additional references:

GCM push notification to iOS with content_available (not working to invoke from inactive state)

GCM support for ios application when application in background or killed

Making GCM work for iOS device in the background


问:
Powershell script not running on scheduled task
I can run the script outside and inside the Task Scheduler. But the scheduled tasks will not run the script automatically when triggered. I have tried configuring the Local Security Policies by changing,  User Account Control: Admin Approval Mode for the Built-i Administrator account (Not Defined) - User Account Control: Run all administrators in Admin Approval Mode (Disabled) - User Account Control: Behavior of the elevation prompt for administrators in Admin Approval Mode (Elevate without prompting). This did not work. Any help would be great. Thanks.

Program/script: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

Add arguments: -NoProfile -ExecutionPolicy Bypass -File C:\Users\Andersen\Desktop\moveFiles.ps1

```<code>Try
{

$Time = Get-Date

if(Test-Path C:\Users\Andersen\Desktop\src) {
    "Source exists."
} else {
    Write-Output "This script made a read attempt at [$Time]. Source (C:\Users\Andersen\Desktop\src) cannot be found." | out-file C:\Users\Andersen\Desktop\KofaxScriptErrorLog.txt -Append
    Exit
}

$IDsrc = (Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\ID - Sub Invoice").Count
$Jsrc  = (Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\J - Sub Invoice").Count
$ORsrc = (Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\OR - Sub Invoice").Count
$OR2   = (Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\OR2 - Sub Invoice").Count
$SCsrc = (Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\SC Invoice").Count
$WAsrc = (Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\WA - Sub Invoice").Count

# move Kofax ID files to ID folder in Egnyte
If ($IDsrc -ne 0){
Get-ChildItem  -Path "C:\Users\Andersen\Desktop\src\ID - Sub Invoice" -Recurse -ErrorAction Stop |
    Move-Item -Destination "C:\Users\Andersen\Desktop\Current Imaging\ID - Sub Invoice" -Force -ErrorAction Stop
    }
# move Kofax J files to J folder in Egnyte
If ($Jsrc -ne 0){
Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\J - Sub Invoice" -Recurse -ErrorAction Stop |
    Move-Item -Destination "C:\Users\Andersen\Desktop\Current Imaging\J - Sub Invoice" -Force -ErrorAction Stop
    }
# move Kofax OR files to OR folder in Egnyte
If ($ORsrc -ne 0){
Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\OR - Sub Invoice" -Recurse -ErrorAction Stop |
    Move-Item -Destination "C:\Users\Andersen\Desktop\Current Imaging\OR - Sub Invoice" -Force -ErrorAction Stop
    }
# move Kofax OR2 files to OR2 folder in Egnyte
If ($OR2src -ne 0){
Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\OR2 - Sub Invoice" -Recurse -ErrorAction Stop |
    Move-Item -Destination "C:\Users\Andersen\Desktop\Current Imaging\OR2 - Sub Invoice" -Force -ErrorAction Stop
    }
# move Kofax SC(multi) files to SC(multi) folder in Egnyte
If ($SCsrc -ne 0){
Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\SC Invoice" -Recurse -ErrorAction Stop |
    Move-Item -Destination "C:\Users\Andersen\Desktop\Current Imaging\SC Invoice" -Force -ErrorAction Stop
                    }
# move Kofax WA files to WA folder in Egnyte
If ($WAsrc -ne 0){
Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\WA - Sub Invoice" -Recurse -ErrorAction Stop |
    Move-Item -Destination "C:\Users\Andersen\Desktop\Current Imaging\WA - Sub Invoice" -Force -ErrorAction Stop
    }

}

Catch {

$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
    "The script to move files from the Kofax server to Egynte made a run attempt at $Time. Error Details: $ErrorMessage $FailedItem" | out-file C:\Users\Andersen\Desktop\KofaxScriptErrorLog.txt -Append
    Break
}

Finally
{

    "This script made a complete read attempt at $Time" | out-file C:\Users\Andersen\Desktop\KofaxScriptLog.txt -Append
}
</code>```

答:
Call the Powershell.exe in your schedulded task:

```<code>C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
</code>```

Set this arguments:

```<code>-noprofile -executionpolicy unrestricted -noninteractive -file "C:\Path\To\MyScript.ps1"
</code>```

Body:
I can run the script outside and inside the Task Scheduler. But the scheduled tasks will not run the script automatically when triggered. I have tried configuring the Local Security Policies by changing,  User Account Control: Admin Approval Mode for the Built-i Administrator account (Not Defined) - User Account Control: Run all administrators in Admin Approval Mode (Disabled) - User Account Control: Behavior of the elevation prompt for administrators in Admin Approval Mode (Elevate without prompting). This did not work. Any help would be great. Thanks.

Program/script: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

Add arguments: -NoProfile -ExecutionPolicy Bypass -File C:\Users\Andersen\Desktop\moveFiles.ps1

Try
{

$Time = Get-Date

if(Test-Path C:\Users\Andersen\Desktop\src) {
    "Source exists."
} else {
    Write-Output "This script made a read attempt at [$Time]. Source (C:\Users\Andersen\Desktop\src) cannot be found." | out-file C:\Users\Andersen\Desktop\KofaxScriptErrorLog.txt -Append
    Exit
}

$IDsrc = (Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\ID - Sub Invoice").Count
$Jsrc  = (Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\J - Sub Invoice").Count
$ORsrc = (Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\OR - Sub Invoice").Count
$OR2   = (Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\OR2 - Sub Invoice").Count
$SCsrc = (Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\SC Invoice").Count
$WAsrc = (Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\WA - Sub Invoice").Count

# move Kofax ID files to ID folder in Egnyte
If ($IDsrc -ne 0){
Get-ChildItem  -Path "C:\Users\Andersen\Desktop\src\ID - Sub Invoice" -Recurse -ErrorAction Stop |
    Move-Item -Destination "C:\Users\Andersen\Desktop\Current Imaging\ID - Sub Invoice" -Force -ErrorAction Stop
    }
# move Kofax J files to J folder in Egnyte
If ($Jsrc -ne 0){
Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\J - Sub Invoice" -Recurse -ErrorAction Stop |
    Move-Item -Destination "C:\Users\Andersen\Desktop\Current Imaging\J - Sub Invoice" -Force -ErrorAction Stop
    }
# move Kofax OR files to OR folder in Egnyte
If ($ORsrc -ne 0){
Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\OR - Sub Invoice" -Recurse -ErrorAction Stop |
    Move-Item -Destination "C:\Users\Andersen\Desktop\Current Imaging\OR - Sub Invoice" -Force -ErrorAction Stop
    }
# move Kofax OR2 files to OR2 folder in Egnyte
If ($OR2src -ne 0){
Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\OR2 - Sub Invoice" -Recurse -ErrorAction Stop |
    Move-Item -Destination "C:\Users\Andersen\Desktop\Current Imaging\OR2 - Sub Invoice" -Force -ErrorAction Stop
    }
# move Kofax SC(multi) files to SC(multi) folder in Egnyte
If ($SCsrc -ne 0){
Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\SC Invoice" -Recurse -ErrorAction Stop |
    Move-Item -Destination "C:\Users\Andersen\Desktop\Current Imaging\SC Invoice" -Force -ErrorAction Stop
                    }
# move Kofax WA files to WA folder in Egnyte
If ($WAsrc -ne 0){
Get-ChildItem -Path "C:\Users\Andersen\Desktop\src\WA - Sub Invoice" -Recurse -ErrorAction Stop |
    Move-Item -Destination "C:\Users\Andersen\Desktop\Current Imaging\WA - Sub Invoice" -Force -ErrorAction Stop
    }

}

Catch {

$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
    "The script to move files from the Kofax server to Egynte made a run attempt at $Time. Error Details: $ErrorMessage $FailedItem" | out-file C:\Users\Andersen\Desktop\KofaxScriptErrorLog.txt -Append
    Break
}

Finally
{

    "This script made a complete read attempt at $Time" | out-file C:\Users\Andersen\Desktop\KofaxScriptLog.txt -Append
}

Body:
Call the Powershell.exe in your schedulded task:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

Set this arguments:

-noprofile -executionpolicy unrestricted -noninteractive -file "C:\Path\To\MyScript.ps1"


问:
Divide One Column by Another with Time Lag
I have a table storing stock prices, i.e. stock ID, date, open price, close price. I want to select a table within a certain date range, and also comes with the price returns from yesterday's close to today's open.

Basically I need to add a column, where the value for ith row equals Open(i)/Close(i-1), how can I do it?

I know if easy to calculate Open(i)/Close(i), but how to divide with a value from a different row? The length of the new column will be 1 unit less than the length of other columns, is it possible to put an 'NA' in order to match the length?

答:
In SQL Server, the lag function can be used to retrieve values from other rows, like so:

```<code>Select
[stock_id],
[date],
[open]/LAG([close],1) OVER (PARTITION BY [stock_id] ORDER BY [date] asc) as [return]
from tbl_1
ORDER BY [stock_id],[date]
</code>```

This will also automatically NULL the first date in the series, where it is not possible to calculate the return.

Body:
In SQL Server, the lag function can be used to retrieve values from other rows, like so:

Select
[stock_id],
[date],
[open]/LAG([close],1) OVER (PARTITION BY [stock_id] ORDER BY [date] asc) as [return]
from tbl_1
ORDER BY [stock_id],[date]

This will also automatically NULL the first date in the series, where it is not possible to calculate the return.


问:
How to design a method that contains lots of IF's or Switch statements
How can i make the design of this class more dynamic so i can add new extensions and types as required.

```<code>public class Processor
{
    public Processor(string fileName)
    {
        string extension = Path.GetExtension(fileName);
        if(extension == "jpg" || extension == "gif" || extension == "png")
        {
            //Process Image file type
        }
        else if(extension == "xls" || extension == "xlsx")
        {
            //Process spreadsheet type
        }
        else if(extension == "doc" || extension == "docx")
        {
            //Process document file type
        }
        //and so forth ...
    }
}
</code>```

We may need to process .tiff files in future or we may need to process video files, which means a new if branch

```<code>else if(extension == "avi" || extension == "mp4")
{
    //Process video file type
}
</code>```

As you can see this can get very long.

The valid files types and groups are stored in a DB...

Can anyone recommend any patterns or clever ideas to solve this problem?
Cheers

答:
There is a rule for this refactoring--

Replace condition with Polymorphism/strategy.
The obvious problem with if/switch is very likely to have errors in such code, and it is difficult to maintain or enhance.

Considering the same and the "Open-Closed Principal"  ( -- Classes should be open for extension but closed for modifications.).

I would suggest for the code below.

```<code>public class Processor
    {
        private Dictionary<string,FileParserBase> _fileExtension2FileParser;

        public Processor() {
            _fileExtension2FileParser = new Dictionary<string, FileParserBase>();

            AddParser(new DocExtensionWordParser());
            AddParser(new DocXExtensionWordParser());
            //..more,more
        }

        private void AddParser(FileParserBase fileParserBase) {

            _fileExtension2FileParser.Add(fileParserBase.Extension, fileParserBase);
        }

    public void Process(string fileName)
    {
        string extension = Path.GetExtension(fileName);
        FileParserBase fileParser;
        if (_fileExtension2FileParser.TryGetValue(extension, out fileParser)) {
            fileParser.Process(fileName);
        }

    }
    }

    public interface FileParserBase
    {
        string Extension { get; }
        void Process(string filePath);
    }

    public abstract class WordParserBase : FileParserBase
    {
        private string _extension;

        public WordParserBase(string extension)
        {
            _extension = extension;
        }

        public override void Process(string filePath)
        {
            //Do the processing for WORD Document
        }

        public override string Extension
        {
            get { return _extension; }
        }
    }

    public class DocExtensionWordParser : WordParserBase
    {

        public DocExtensionWordParser():base("doc"){}
    }

    public class DocXExtensionWordParser : WordParserBase
    {

        public DocXExtensionWordParser() : base("docx") { }
    }
</code>```

Body:
How can i make the design of this class more dynamic so i can add new extensions and types as required.

public class Processor
{
    public Processor(string fileName)
    {
        string extension = Path.GetExtension(fileName);
        if(extension == "jpg" || extension == "gif" || extension == "png")
        {
            //Process Image file type
        }
        else if(extension == "xls" || extension == "xlsx")
        {
            //Process spreadsheet type
        }
        else if(extension == "doc" || extension == "docx")
        {
            //Process document file type
        }
        //and so forth ...
    }
}

We may need to process .tiff files in future or we may need to process video files, which means a new if branch

else if(extension == "avi" || extension == "mp4")
{
    //Process video file type
}

As you can see this can get very long.

The valid files types and groups are stored in a DB...

Can anyone recommend any patterns or clever ideas to solve this problem?
Cheers

Body:
There is a rule for this refactoring--

Replace condition with Polymorphism/strategy.
The obvious problem with if/switch is very likely to have errors in such code, and it is difficult to maintain or enhance.

Considering the same and the "Open-Closed Principal"  ( -- Classes should be open for extension but closed for modifications.).

I would suggest for the code below.

public class Processor
    {
        private Dictionary<string,FileParserBase> _fileExtension2FileParser;

        public Processor() {
            _fileExtension2FileParser = new Dictionary<string, FileParserBase>();

            AddParser(new DocExtensionWordParser());
            AddParser(new DocXExtensionWordParser());
            //..more,more
        }

        private void AddParser(FileParserBase fileParserBase) {

            _fileExtension2FileParser.Add(fileParserBase.Extension, fileParserBase);
        }

    public void Process(string fileName)
    {
        string extension = Path.GetExtension(fileName);
        FileParserBase fileParser;
        if (_fileExtension2FileParser.TryGetValue(extension, out fileParser)) {
            fileParser.Process(fileName);
        }

    }
    }

    public interface FileParserBase
    {
        string Extension { get; }
        void Process(string filePath);
    }

    public abstract class WordParserBase : FileParserBase
    {
        private string _extension;

        public WordParserBase(string extension)
        {
            _extension = extension;
        }

        public override void Process(string filePath)
        {
            //Do the processing for WORD Document
        }

        public override string Extension
        {
            get { return _extension; }
        }
    }

    public class DocExtensionWordParser : WordParserBase
    {

        public DocExtensionWordParser():base("doc"){}
    }

    public class DocXExtensionWordParser : WordParserBase
    {

        public DocXExtensionWordParser() : base("docx") { }
    }


问:
Django: How to get all users with profiles as JSON (extended User model)
I have extended the default User model in Django. Now my models look like following:

```<code>class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
birth_date = models.DateField(auto_now=False, auto_now_add=False, default=datetime.now)
phone_number = models.CharField(max_length=13, blank=True, default="")
address = models.CharField(max_length=100, blank=True, default="")
organization = models.ForeignKey(Organization, blank=True, null=True)
</code>```

Everything works fine, I am able to add new users through admin panel and so on.
However, I have got a problem. I need to return a customize JSON response to certain request in form of:

```<code>[
{"firs_name": first_name, "phone_number": phone_number, ...},
{"firs_name": first_name, "phone_number": phone_number, ...},
...
]
</code>```

As you can see, the phone_number attribute belongs to the Profile model, and I cannot get ALL users with their Profiles included (I am able to get only id of user).
Here is the response I get for now:

```<code>[{"username": "user", "profile": 2, "first_name": "User", "last_name": "User"}, {"username": "user1", "profile": 3, "first_name": "User1", "last_name": "User1"}, {"username": "user2", "profile": 4, "first_name": "User2", "last_name": "User2"}]
</code>```

Question: Is there any way to get all user objects with profile information included in it through User.Objects.all()?

Thanks!

P.S.:
This is how I make custom JSON response:

```<code>def get_users_as_json(request):
all_users = User.objects.all().values("username", "first_name", "last_name", 'profile')
user_list = list(all_users)
return JsonResponse(user_list, safe=False)
</code>```

答:
There are no.of ways to Do so , try these </p>

```<code>def get_users_as_json(request):
    col = ["username", "first_name", "last_name", 'profile_id', \
    'profile__phone_number', 'profile__address_no', 'profile__birth_date']

    all_users = User.objects.all().values(*col)
    user_list = list(all_users)
    return JsonResponse(user_list, safe=False)

def get_user_as_json(request):
    user_list = []
    users = User.objects.all()
    for user in users:
        user_dict = {}
        user_dict['user_name'] = user.username
        user_dict['first_name'] = user.first_name
        user_dict['phone_number'] = user.profile.phone_number
        user_dict['birthdate'] = user.profile.birth_date
        ...

        user_list.append(user_dict)

    user_list = list(user_list)
    return JsonResponse(user_list, safe=False)
</code>```

Body:
I have extended the default User model in Django. Now my models look like following:

class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
birth_date = models.DateField(auto_now=False, auto_now_add=False, default=datetime.now)
phone_number = models.CharField(max_length=13, blank=True, default="")
address = models.CharField(max_length=100, blank=True, default="")
organization = models.ForeignKey(Organization, blank=True, null=True)

Everything works fine, I am able to add new users through admin panel and so on.
However, I have got a problem. I need to return a customize JSON response to certain request in form of:

[
{"firs_name": first_name, "phone_number": phone_number, ...},
{"firs_name": first_name, "phone_number": phone_number, ...},
...
]

As you can see, the phone_number attribute belongs to the Profile model, and I cannot get ALL users with their Profiles included (I am able to get only id of user).
Here is the response I get for now:

[{"username": "user", "profile": 2, "first_name": "User", "last_name": "User"}, {"username": "user1", "profile": 3, "first_name": "User1", "last_name": "User1"}, {"username": "user2", "profile": 4, "first_name": "User2", "last_name": "User2"}]

Question: Is there any way to get all user objects with profile information included in it through User.Objects.all()?

Thanks!

P.S.:
This is how I make custom JSON response:

def get_users_as_json(request):
all_users = User.objects.all().values("username", "first_name", "last_name", 'profile')
user_list = list(all_users)
return JsonResponse(user_list, safe=False)

Body:
There are no.of ways to Do so , try these

def get_users_as_json(request):
    col = ["username", "first_name", "last_name", 'profile_id', \
    'profile__phone_number', 'profile__address_no', 'profile__birth_date']

    all_users = User.objects.all().values(*col)
    user_list = list(all_users)
    return JsonResponse(user_list, safe=False)

def get_user_as_json(request):
    user_list = []
    users = User.objects.all()
    for user in users:
        user_dict = {}
        user_dict['user_name'] = user.username
        user_dict['first_name'] = user.first_name
        user_dict['phone_number'] = user.profile.phone_number
        user_dict['birthdate'] = user.profile.birth_date
        ...

        user_list.append(user_dict)

    user_list = list(user_list)
    return JsonResponse(user_list, safe=False)


问:
SQL Server - DB Impact on VARCHAR and NVARCHAR
SQL Server gives super easy options for developers to create VARCHAR and NVARCHAR columns. However, I see for the same data stored in the column, the SQL Server database size is almost double.

Of course a little exaggerating but the database size is really high. I did look at the SQL Server MDB size and also checked the table size with VARCHAR column and same table with NVARCHAR column.

Does that mean that we need to use NVARCHAR sensibly?

答:
This depends on your requirements.

If you need to store unicode then you have to use NVARCHAR.
If you only store ascii or only one language which can stored in 8bit, then you can use NVARCHAR. if it take "too much" space then use VARCHAR.


问:
Reset Expander to default collapse behavior
I'm using an expander inside a Resizer (a ContentControl with a resize gripper), and it expands/collapses properly when the control initially comes up.  Once I resize it, the Expander won't properly collapse, as documented below.  I ran Snoop on my application, and I don't see any heights set on Expander or its constituents.

How would I go about convincing Expander to collapse properly again?  Or modifying Resizer to not make Expander sad would work as well.

Expander documentation says:

"For an Expander to work correctly, do not specify a Height on the Expander control when the ExpandDirection property is set to Down or Up. Similarly, do not specify a Width on the Expander control when the ExpandDirection property is set to Left or Right. When you set a size on the Expander control in the direction that the expanded content is displayed, the area that is defined by the size parameter is displayed with a border around it. This area displays even when the window is collapsed. To set the size of the expanded window, set size dimensions on the content of the Expander control or the ScrollViewer that encloses the content."

答:
Answering this a bit late (2+ years), but, hey, better late than never, right?

Anyway, I ran into this exact problem and was able to solve it with some code-behind to save and reset column widths.

I have a 3 columned Grid, with some content in the first column, the GridSplitter in the second column, and the Expander in the third column. It looks like what is happening is that after the GridSplitter is moved the width of the column containing the Expander is altered from Auto to a fixed size. This causes the Expander to no longer collapse as expected.

So, I added a private variable and two event handlers:

```<code>    private GridLength _columnWidth;

    private void Expander_Expanded (object sender, RoutedEventArgs e)
    {
        // restore column fixed size saved in Collapse event
        Column2.Width = _columnWidth;
    }

    private void Expander_Collapsed (object sender, RoutedEventArgs e)
    {
        // save current column width so we can restore when expander is expanded
        _columnWidth = Column2.Width;

        // reset column width to auto so the expander will collapse properly
        Column2.Width = GridLength.Auto;
    }
</code>```

When the Expander is collapsed I save Column2's fixed width (which was altered from Auto auto-magically in the background somewhere) then reset the width to Auto.

Then, when the expander is expanded, I restore the column back to the fixed width so it expands to the same width it was before it was collapsed.

Here's the XAML for reference:

```<code><Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="2*" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition x:Name="Column2" Width="Auto" />
    </Grid.ColumnDefinitions>
    <ScrollViewer Grid.Column="0" VerticalScrollBarVisibility="Auto">
        <!-- some content goes here -->
    </ScrollViewer>
    <GridSplitter HorizontalAlignment="Right" VerticalAlignment="Stretch"
         Grid.Column="1" ResizeBehavior="PreviousAndNext" Width="5"
         Background="Black" />
    <Expander Grid.Column="2" ExpandDirection="Left"
         IsExpanded="True" Style="{StaticResource LeftExpander}"
         Expanded="Expander_Expanded" Collapsed="Expander_Collapsed">
        <Grid>
            <TextBox TextWrapping="Wrap" Height="Auto" Margin="0 5 5 5" />
        </Grid>
    </Expander>
</Grid>
</code>```

OwnerDisplayName: Tom

Body:
Answering this a bit late (2+ years), but, hey, better late than never, right?

Anyway, I ran into this exact problem and was able to solve it with some code-behind to save and reset column widths.

I have a 3 columned Grid, with some content in the first column, the GridSplitter in the second column, and the Expander in the third column. It looks like what is happening is that after the GridSplitter is moved the width of the column containing the Expander is altered from Auto to a fixed size. This causes the Expander to no longer collapse as expected.

So, I added a private variable and two event handlers:

    private GridLength _columnWidth;

    private void Expander_Expanded (object sender, RoutedEventArgs e)
    {
        // restore column fixed size saved in Collapse event
        Column2.Width = _columnWidth;
    }

    private void Expander_Collapsed (object sender, RoutedEventArgs e)
    {
        // save current column width so we can restore when expander is expanded
        _columnWidth = Column2.Width;

        // reset column width to auto so the expander will collapse properly
        Column2.Width = GridLength.Auto;
    }

When the Expander is collapsed I save Column2's fixed width (which was altered from Auto auto-magically in the background somewhere) then reset the width to Auto.

Then, when the expander is expanded, I restore the column back to the fixed width so it expands to the same width it was before it was collapsed.

Here's the XAML for reference:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="2*" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition x:Name="Column2" Width="Auto" />
    </Grid.ColumnDefinitions>
    <ScrollViewer Grid.Column="0" VerticalScrollBarVisibility="Auto">
        <!-- some content goes here -->
    </ScrollViewer>
    <GridSplitter HorizontalAlignment="Right" VerticalAlignment="Stretch"
         Grid.Column="1" ResizeBehavior="PreviousAndNext" Width="5"
         Background="Black" />
    <Expander Grid.Column="2" ExpandDirection="Left"
         IsExpanded="True" Style="{StaticResource LeftExpander}"
         Expanded="Expander_Expanded" Collapsed="Expander_Collapsed">
        <Grid>
            <TextBox TextWrapping="Wrap" Height="Auto" Margin="0 5 5 5" />
        </Grid>
    </Expander>
</Grid>


问:
Creating all possible ways of a boolean array of size n?
I need to be able to create a boolean array of one combination and run it through a program to see if it works. If not then I dispose of it and go to the next combination. My issue is that I don't know how to create this array because n can be equal anywhere from 1-1000. So I was planning on using Integer.toBinaryString but that won't work due to its too big when it gets to past 32.
Any help would be greatful.

Thanks!

答:
The "accepted answer" states that

Tested and this will work for high values of n, such as 10000 and so on.

But this is incorrect.

```<code>public static void main(String[] args) {
    final int n = 3;
    for (int i = 0; i < Math.pow(2, n); i++) {
        String bin = Integer.toBinaryString(i);
        while (bin.length() < n)
            bin = "0" + bin;
        char[] chars = bin.toCharArray();
        boolean[] boolArray = new boolean[n];
        for (int j = 0; j < chars.length; j++) {
            boolArray[j] = chars[j] == '0' ? true : false;
        }
        System.out.println(Arrays.toString(boolArray));
    }
}
</code>```

When n > 31 it will loop forever repeating the first 2^31 combinations since i will overflow and will never reach Math.pow(2, n). You can easily test this with

```<code>public static void main2(String[] args){
        int n = 32;
        for (int i = 0; i < Math.pow(2, n); i++){
            if (i == Integer.MIN_VALUE) {
                // i overflows
                System.out.println("i exceeded Integer.MAX_VALUE");
            }
        }
    }
</code>```

Code above will indefinitely print i exceeded Integer.MAX_VALUE
However this can easily be corrected using BigInteger or a similar data structure for looping. The code below will work for n <= Integer.MAX_VALUE

```<code>public static void main(String[] args) {
    final int n = 32;
    BigInteger bi = BigInteger.ZERO;
    BigDecimal rows = new BigDecimal(Math.pow(2, n));
    while (bi.compareTo(rows.toBigInteger()) < 0) {
        String bin = bi.toString(2);//Integer.toBinaryString(i);
        while (bin.length() < n)
            bin = "0" + bin;
        char[] chars = bin.toCharArray();
        boolean[] boolArray = new boolean[n];
        for (int j = 0; j < chars.length; j++) {
            boolArray[j] = chars[j] == '0' ? true : false;
        }
        System.out.println(Arrays.toString(boolArray));
        bi = bi.add(BigInteger.ONE);
    }
}
</code>```

Body:
The "accepted answer" states that

Tested and this will work for high values of n, such as 10000 and so on.

But this is incorrect.

public static void main(String[] args) {
    final int n = 3;
    for (int i = 0; i < Math.pow(2, n); i++) {
        String bin = Integer.toBinaryString(i);
        while (bin.length() < n)
            bin = "0" + bin;
        char[] chars = bin.toCharArray();
        boolean[] boolArray = new boolean[n];
        for (int j = 0; j < chars.length; j++) {
            boolArray[j] = chars[j] == '0' ? true : false;
        }
        System.out.println(Arrays.toString(boolArray));
    }
}

When n > 31 it will loop forever repeating the first 2^31 combinations since i will overflow and will never reach Math.pow(2, n). You can easily test this with

public static void main2(String[] args){
        int n = 32;
        for (int i = 0; i < Math.pow(2, n); i++){
            if (i == Integer.MIN_VALUE) {
                // i overflows
                System.out.println("i exceeded Integer.MAX_VALUE");
            }
        }
    }

Code above will indefinitely print i exceeded Integer.MAX_VALUE
However this can easily be corrected using BigInteger or a similar data structure for looping. The code below will work for n <= Integer.MAX_VALUE

public static void main(String[] args) {
    final int n = 32;
    BigInteger bi = BigInteger.ZERO;
    BigDecimal rows = new BigDecimal(Math.pow(2, n));
    while (bi.compareTo(rows.toBigInteger()) < 0) {
        String bin = bi.toString(2);//Integer.toBinaryString(i);
        while (bin.length() < n)
            bin = "0" + bin;
        char[] chars = bin.toCharArray();
        boolean[] boolArray = new boolean[n];
        for (int j = 0; j < chars.length; j++) {
            boolArray[j] = chars[j] == '0' ? true : false;
        }
        System.out.println(Arrays.toString(boolArray));
        bi = bi.add(BigInteger.ONE);
    }
}