问:
Copy .txt file and capitalise first letter of each word and write to new file
I'm making a small script that opens the file_name and writes a copy of it to the destination .txt file but the first letter of each word is capitalised and all whitespace is just replaced by a singular space. I was trying to do this with the .capitalize method or the .capwords method.

```<code>def capitalise_words(file_name, destination):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        capped = text_str.capwords()

    with open(destination, "w") as writefile:
        writefile.write(capped)
</code>```

I can't figure out how I can get this to work. Perhaps slicing to the first character of each word if I split them into a list and capitalizing it using .capitalize?

答:
Assuming:

```<code>raw_text="""
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
"""
</code>```

You can use `capitalize()' when iterate through a list of words.

```<code>txt_split = raw_text.split()

for i, word in enumerate(txt_split):
    txt_split[i] = word.capitalize()

txt_output = ' '.join(txt_split)

print(txt_output)
</code>```

Output:

Lorem Ipsum Dolor Sit Amet, Consectetur Adipisicing Elit, Sed Do Eiusmod Tempor Incididunt Ut Labore Et Dolore Magna Aliqua. Ut Enim Ad Minim Veniam, Quis Nostrud Exercitation Ullamco Laboris Nisi Ut Aliquip Ex Ea Commodo Consequat. Duis Aute Irure Dolor In Reprehenderit In Voluptate Velit Esse Cillum Dolore Eu Fugiat Nulla Pariatur. Excepteur Sint Occaecat Cupidatat Non Proident, Sunt In Culpa Qui Officia Deserunt Mollit Anim Id Est Laborum.

string.capwords() is the same thing packed into a helper function for ease of use

Body:
I'm making a small script that opens the file_name and writes a copy of it to the destination .txt file but the first letter of each word is capitalised and all whitespace is just replaced by a singular space. I was trying to do this with the .capitalize method or the .capwords method.

def capitalise_words(file_name, destination):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        capped = text_str.capwords()

    with open(destination, "w") as writefile:
        writefile.write(capped)

I can't figure out how I can get this to work. Perhaps slicing to the first character of each word if I split them into a list and capitalizing it using .capitalize?

Body:
Assuming:

raw_text="""
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
"""

You can use `capitalize()' when iterate through a list of words.

txt_split = raw_text.split()

for i, word in enumerate(txt_split):
    txt_split[i] = word.capitalize()

txt_output = ' '.join(txt_split)

print(txt_output)

Output:

Lorem Ipsum Dolor Sit Amet, Consectetur Adipisicing Elit, Sed Do Eiusmod Tempor Incididunt Ut Labore Et Dolore Magna Aliqua. Ut Enim Ad Minim Veniam, Quis Nostrud Exercitation Ullamco Laboris Nisi Ut Aliquip Ex Ea Commodo Consequat. Duis Aute Irure Dolor In Reprehenderit In Voluptate Velit Esse Cillum Dolore Eu Fugiat Nulla Pariatur. Excepteur Sint Occaecat Cupidatat Non Proident, Sunt In Culpa Qui Officia Deserunt Mollit Anim Id Est Laborum.

string.capwords() is the same thing packed into a helper function for ease of use


来源: stackexchange

问:
Django ORM order by day from ISO time and score
HI in my database I have some data with created date and and some score associated with it.The created_date is of type DateTime. I am using django ORM.

The data is like

```<code>**col1   created_date                  score**
xxx    2019-05-28T10:07:57.000Z      8
yye    2019-05-27T10:07:57.000Z      9
abc    2019-05-28T09:07:57.000Z      10
</code>```

I want my date to be sorted by day then score in descending order ie

```<code>abc    2019-05-28T09:07:57.000Z      10
xxx    2019-05-28T10:07:57.000Z      8
yye    2019-05-27T10:07:57.000Z      9
</code>```

I am using

```<code>SomeModel.objects.values_list(col , score, created_date
).filter(somefilter tcategory=cat).order_by(
                        '-created_date__day',
                        '-score')
</code>```

I am getting exception --

```<code>    raise NotImplementedError('subclasses of BaseDatabaseOperations may require a datetime_extract_sql() method')
NotImplementedError: subclasses of BaseDatabaseOperations may require a datetime_extract_sql() method
</code>```

Thanks

答:
It does not seem to make much sense to add a __day lookup here, you can just order in descending order by created_by_date:

```<code>SomeModel.objects.values_list(
    'col' , 'score', 'created_date'
).filter(
    somefilter tcategory=cat
).order_by(<b>'-created_date'</b>, '-score')</code>```

If you really want to order by the date of that day, you can use an annotation with TruncDate [Django-doc]:

```<code>from django.db.models.functions import <b>TruncDate</b>

SomeModel.objects.values_list(
    'col' , 'score', 'created_date'
).annotate(
    <b>create_day=TruncDate('created_date')</b>
).filter(
    somefilter tcategory=cat
).order_by(<b>'-create_day'</b>, '-score')</code>```

ContentLicense: CC BY-SA 4.0

Body:
HI in my database I have some data with created date and and some score associated with it.The created_date is of type DateTime. I am using django ORM.

The data is like

**col1   created_date                  score**
xxx    2019-05-28T10:07:57.000Z      8
yye    2019-05-27T10:07:57.000Z      9
abc    2019-05-28T09:07:57.000Z      10

I want my date to be sorted by day then score in descending order ie

abc    2019-05-28T09:07:57.000Z      10
xxx    2019-05-28T10:07:57.000Z      8
yye    2019-05-27T10:07:57.000Z      9

I am using

SomeModel.objects.values_list(col , score, created_date
).filter(somefilter tcategory=cat).order_by(
                        '-created_date__day',
                        '-score')

I am getting exception --

    raise NotImplementedError('subclasses of BaseDatabaseOperations may require a datetime_extract_sql() method')
NotImplementedError: subclasses of BaseDatabaseOperations may require a datetime_extract_sql() method

Thanks

Body:
It does not seem to make much sense to add a __day lookup here, you can just order in descending order by created_by_date:

SomeModel.objects.values_list(
    'col' , 'score', 'created_date'
).filter(
    somefilter tcategory=cat
).order_by('-created_date', '-score')

If you really want to order by the date of that day, you can use an annotation with TruncDate [Django-doc]:

from django.db.models.functions import TruncDate

SomeModel.objects.values_list(
    'col' , 'score', 'created_date'
).annotate(
    create_day=TruncDate('created_date')
).filter(
    somefilter tcategory=cat
).order_by('-create_day', '-score')


问:
How can I center elements horizontally or vertically with Twitter Bootstrap?
Is there any way to center html elements vertically or horizontally inside the main parents?</p>

答:
for bootstrap4 vertical center of few items

d-flex for flex rules

flex-column for vertical direction on items

align-items-center for horizontal centering

justify-content-center for vertical centering

style='height: 300px;' must have for set points where center be calc or use h-100 class

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" rel="stylesheet"/>

Flex item

Flex item

Flex item

```

Body:
for bootstrap4 vertical center of few items

d-flex for flex rules

flex-column for vertical direction on items

align-items-center for horizontal centering

justify-content-center for vertical centering

style='height: 300px;' must have for set points where center be calc or use h-100 class

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div class="d-flex flex-column align-items-center justify-content-center bg-secondary" style="
    height: 300px;
">
    <div class="p-2 bg-primary">Flex item</div>
    <div class="p-2 bg-primary">Flex item</div>
    <div class="p-2 bg-primary">Flex item</div>
</div>


问:
MVC5 app hangs on starting application pool on IIS / Windows 2019 Server
I have an MVC5 application which uses various nugets (autofac, devextreme, automapper, entity framework).  I have 15 other MVC apps which also use all of these and work fine, but this one.....

Locally, either on IISExpress or IIS (Windows 10) it works fine.
When I deploy it to a Windows 2019, though, it hangs on startup.  It seems to be stuck in a memory-grabbing loop of some sort.  No http requests ever return and after 30 seconds running the Application Pool is using over 2GB of memory when locally it uses 200MB max.

Nothing is logged to EventLog.

I've added logging (serilog) and tracing to no avail....My startup code (global.asax / startup.cs) runs successfully and exits...and then nothing....The first http request hangs and all subsequent ones queue.

I've got no idea where to look next.  My final hail mary has been to install DebugDiag and create a dump - the analysis of which is HERE

I'm no DebugDiag / Dump expert and all this is telling me is that every thread is waiting for Garbage Collection...Well...Not helpful...

Can someone please look at the dump analysis and tell me what I can do next / what is going on?

答: So, this seemed to be resolved by increasing the amount of memory available to the server?!  Since I increased RAM it has never happened again......</p>


问:
Render state in another component in reactjs
I'm trying to display current user name in a different component but It's not working, what am I doing wrong ?

Here's where I'm initialising the username (App.js)

class App extends Component{
  constructor(props) {
    super(props);
    this.state = {
      logged_in: localStorage.getItem('token') ? true : false,
      username: ''
    };
  }
  componentDidMount() {
    if (this.state.logged_in) {
      fetch('http://localhost:8000/user/current_user/', {
        headers: {
          Authorization: `JWT ${localStorage.getItem('token')}`
        }
      })
        .then(res => res.json())
        .then(json => {
          this.setState({ username: json.username });
          console.log(json.username);
        });

    }
  }
  render() {
  return (

      <Router history={history}>
        <Switch>
          <Route exact path="/" component={First} />
          <Route path="/home" component={Projects} />
          <Route path="/menu" component={MenuH} />
          <Route path ="/createProject" component={CreateP} />
          <Route path ="/connect" component={Newacount} />
          <Route component={Notfound} />
        </Switch>
      </Router>

  );
  }
}
...
```

<p>And here's how I'm calling it in a different component (projects)</p>

<pre class="lang-js prettyprint-override"><code>{this.state.username}
</code>```

答:
Your Projects component does not have access to the state in App.

You should do this with a state manager like React Context or Redux

Body:
I'm trying to display current user name in a different component but It's not working, what am I doing wrong ?

Here's where I'm initialising the username (App.js)

class App extends Component{
  constructor(props) {
    super(props);
    this.state = {
      logged_in: localStorage.getItem('token') ? true : false,
      username: ''
    };
  }
  componentDidMount() {
    if (this.state.logged_in) {
      fetch('http://localhost:8000/user/current_user/', {
        headers: {
          Authorization: `JWT ${localStorage.getItem('token')}`
        }
      })
        .then(res => res.json())
        .then(json => {
          this.setState({ username: json.username });
          console.log(json.username);
        });

    }
  }
  render() {
  return (

      <Router history={history}>
        <Switch>
          <Route exact path="/" component={First} />
          <Route path="/home" component={Projects} />
          <Route path="/menu" component={MenuH} />
          <Route path ="/createProject" component={CreateP} />
          <Route path ="/connect" component={Newacount} />
          <Route component={Notfound} />
        </Switch>
      </Router>

  );
  }
}
...

And here's how I'm calling it in a different component (projects)

{this.state.username}


问:
How to open a specific nested bootstrap accordeon based on its unique id
I am generating a dynamic nested accordion with unique client ids. Let's say a user needs to do a modification on accordeon 3, he opens the specific accordion and click on the button "modify". The user is then transported to a new form on a new page to do his modification.

After validating his modification, the user needs to return to the previous page with the listed accordion and have only the specific accordion he selected earlier open. Can somebody please assist me?

Here is my code:

```<code><div id="accordionbox">
    <?php
    if (isset($listeClient) && count($listeClient) > 0) {
        ?>
        <?php
        $iClients = 0;
        while ($iClients < count($listeClient)) {
            $CLIENT_ID = $listeClient[$iClients]['CLIENT_ID'] == "" ? "" : $listeClient[$iClients]['CLIENT_ID'];
            $nom = $listeClient[$iClients]['CLIENT_NOM'] == "" ? "" : $listeClient[$iClients]['CLIENT_NOM'];
            $prenom = $listeClient[$iClients]['CLIENT_PRENOM'] == "" ? "" : $listeClient[$iClients]['CLIENT_PRENOM'];
            $projet[] = $listeClient[$iClients]['projet'];
            ?>

            <div class="form-group">
                <div class="col-xs-12">
                    <div class="panel panel-default">

                        <div id="accordionMain<?php echo $iClients; ?>" class="panel-group" aria-multiselectable="true">

                            <div id="headingClient<?php echo $iClients; ?>" class="panel">
                                <a class="panel-heading collapsed" title="Tab1"
                                   aria-controls="collapseMain-<?php echo $CLIENT_ID; ?>" aria-expanded="false"
                                   href="#collapseMain-<?php echo $CLIENT_ID; ?>" data-toggle="collapse">
                                    <span class="panel-title"><?php echo $nom . ' ' . $prenom; ?></span>
                                </a>

                                <div id="collapseMain-<?php echo $CLIENT_ID; ?>" class="panel-collapse collapse"
                                     aria-labelledby="heading<?php echo $CLIENT_ID; ?>" aria-expanded="false">

                                    <div class="panel-body">

                                        <div id="accordionInside-<?php echo $CLIENT_ID; ?>" class="panel-group"
                                             aria-multiselectable="true" role="tablist">

                                            <!-- Informations Personnelles -->
                                            <div class="panel panel-default">

                                                <a id="headingPersonnelle-<?php echo $CLIENT_ID; ?>"
                                                   class="panel-heading collapsed" title="Tab1"
                                                   aria-controls="collapsePersonnelle-<?php echo $CLIENT_ID; ?>"
                                                   aria-expanded="false"
                                                   href="#collapsePersonnelle-<?php echo $CLIENT_ID; ?>"
                                                   data-toggle="collapse" role="tab">
                                                    <span class="panel-title">Informations Personnelles</span>
                                                </a>

                                                <div id="collapsePersonnelle-<?php echo $CLIENT_ID; ?>"
                                                     class="panel-collapse collapse"
                                                     aria-labelledby="headingPersonnelle-<?php echo $CLIENT_ID; ?>"
                                                     role="tabpanel" aria-expanded="false">
                                                    <div class="panel-body">
                                                        Personelle
                                                    </div>
                                                </div>

                                            </div> <!-- Fin Informations Personnelles -->

                                            <!-- Contracts -->
                                            <div class="panel panel-default">

                                                <a id="headingContract-<?php echo $CLIENT_ID; ?>"
                                                   class="panel-heading collapsed" title="Tab2"
                                                   aria-controls="collapseContract-<?php echo $CLIENT_ID; ?>"
                                                   aria-expanded="false"
                                                   href="#collapseContract-<?php echo $CLIENT_ID; ?>"
                                                   data-toggle="collapse" role="tab">
                                                    <span class="panel-title">Dossiers</span>
                                                </a>

                                                <div id="collapseContract-<?php echo $CLIENT_ID; ?>"
                                                     class="panel-collapse collapse"
                                                     aria-labelledby="headingContract-<?php echo $CLIENT_ID; ?>"
                                                     role="tabpanel" aria-expanded="false">
                                                    <div class="panel-body">

                                                        <div id="accordionContractBody-<?php echo $CLIENT_ID; ?>"
                                                             class="panel-group" aria-multiselectable="true"
                                                             role="tablist">

                                                            <?php
                                                            $iProjets = 0;
                                                            while ($iProjets < count($projet[$iClients]['projetz'])) {
                                                                $PROJET_ID = $projet[$iClients]['projetz'][$iProjets]['PROJET_ID'];
                                                                ?>

                                                                <div id="accordionContract-<?php echo $CLIENT_ID . '-' . $PROJET_ID; ?>"
                                                                     class="panel-group rapprocher"
                                                                     aria-multiselectable="true" role="tablist">

                                                                    <div class="panel panel-default">
                                                                        <a id="headingProjet-<?php echo $CLIENT_ID . '-' . $PROJET_ID; ?>"
                                                                           class="panel-heading collapsed" title="Tab1"
                                                                           aria-controls="collapse-<?php echo $CLIENT_ID . '-' . $PROJET_ID; ?>"
                                                                           aria-expanded="false"
                                                                           href="#collapseProjet-<?php echo $CLIENT_ID . '-' . $PROJET_ID; ?>"
                                                                           data-toggle="collapse" role="tab">
                                                                            <span class="panel-title"><?php echo $projet[$iClients]['projetz'][$iProjets]['PROJET_NOM']; ?></span>
                                                                        </a>
                                                                    </div>

                                                                    <div id="collapseProjet-<?php echo $CLIENT_ID . '-' . $PROJET_ID; ?>"
                                                                         class="panel-collapse collapse"
                                                                         aria-labelledby="headingProjet-<?php echo $CLIENT_ID . '-' . $PROJET_ID; ?>"
                                                                         role="tabpanel" aria-expanded="false">
                                                                        <div class="panel-body">
                                                                            Contracts
                                                                        </div>
                                                                    </div>

                                                                </div>

                                                                <?php
                                                                $iProjets++;
                                                            }
                                                            ?>

                                                        </div>
                                                    </div>
                                                </div>

                                            </div> <!-- Fin Contracts -->

                                        </div>
                                    </div>

                                </div>
                            </div>

                        </div>

                    </div>
                </div>
            </div>

            <?php
            $iClients++;
        }
        ?>
        <?php
    }
    ?>
</div>
</code>```

And here is what i have been trying:

```<code><?php
if (isset($client_id) && $client_id <> "") {
    ?>
    <script>
        $(document).ready(function () {

            //open all div starting with collapseMain
            $("div[id^='collapseMain']").addClass("in");

            //open all div starting with collapsePersonnelle
            $("div[id^='collapsePersonnelle']").addClass("in");

            //open all div starting with collapseContract
            $("div[id^='collapseContract']").addClass("in");

            //open all div starting with collapseProjet
            $("div[id^='collapseProjet']").addClass("in");

            //how to open only the specific accordion with the client id

        });
    </script>
    <?php
}
?>
</code>```

答:
We can see that you have added unique id to all your ".panel-collapse" divs as id="collapseMain-<?php echo $CLIENT_ID; ?>". We also know that you have the id for which you want to open the accordion.

You can use jquery selector $("#collapseMain-<?php echo $client_id; ?>") to select only the accordion that should be opened.

Lets assume the html code generated by php is:

```<code>
<div id="accordionbox">
  <div class="form-group">
    <div class="col-xs-12">
      <div class="panel panel-default">
        <div id="accordionMain-1" class="panel-group" aria-multiselectable="true">
          <div id="headingClient-1" class="panel">
            <a class="panel-heading collapsed" title="Tab1"
                                   aria-controls="collapseMain-1>" aria-expanded="false"
                                   href="#collapseMain-1" data-toggle="collapse"><span class="panel-title">Client 1</span></a>
            <div id="collapseMain-1" class="panel-collapse collapse"
                                     aria-labelledby="heading1" aria-expanded="false">
               <div class="panel-body">
                Content 1
               </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="form-group">
    <div class="col-xs-12">
      <div class="panel panel-default">
        <div id="accordionMain-2" class="panel-group" aria-multiselectable="true">
          <div id="headingClient-2" class="panel">
            <a class="panel-heading collapsed" title="Tab2"
                                   aria-controls="collapseMain-2>" aria-expanded="false"
                                   href="#collapseMain-2" data-toggle="collapse"><span class="panel-title">Client 2</span></a>
            <div id="collapseMain-2" class="panel-collapse collapse"
                                     aria-labelledby="heading2" aria-expanded="false">
               <div class="panel-body">
                Content 2
               </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="form-group">
    <div class="col-xs-12">
      <div class="panel panel-default">
        <div id="accordionMain-3" class="panel-group" aria-multiselectable="true">
          <div id="headingClient-3" class="panel">
            <a class="panel-heading collapsed" title="Tab3"
                                   aria-controls="collapseMain-3>" aria-expanded="false"
                                   href="#collapseMain-3" data-toggle="collapse"><span class="panel-title">Client 3</span></a>
            <div id="collapseMain-3" class="panel-collapse collapse"
                                     aria-labelledby="heading3" aria-expanded="false">
               <div class="panel-body">
                Content 3
               </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

</div>

</code>```

Then you can generate javascript code using php like

```<code>
<?php
if (isset($client_id) && $client_id <> "") {
    ?>
$(document).ready(function() {
  $("#collapseMain-<?php echo $client_id; ?>").addClass("in");
});

<?php } ?>

</code>```

You can have a look at this jsfiddle

Body:
I am generating a dynamic nested accordion with unique client ids. Let's say a user needs to do a modification on accordeon 3, he opens the specific accordion and click on the button "modify". The user is then transported to a new form on a new page to do his modification.

After validating his modification, the user needs to return to the previous page with the listed accordion and have only the specific accordion he selected earlier open. Can somebody please assist me?

Here is my code:

    <?php
    if (isset($listeClient) && count($listeClient) > 0) {
        ?>
        <?php
        $iClients = 0;
        while ($iClients < count($listeClient)) {
            $CLIENT_ID = $listeClient[$iClients]['CLIENT_ID'] == "" ? "" : $listeClient[$iClients]['CLIENT_ID'];
            $nom = $listeClient[$iClients]['CLIENT_NOM'] == "" ? "" : $listeClient[$iClients]['CLIENT_NOM'];
            $prenom = $listeClient[$iClients]['CLIENT_PRENOM'] == "" ? "" : $listeClient[$iClients]['CLIENT_PRENOM'];
            $projet[] = $listeClient[$iClients]['projet'];
            ?>

                        <div id="accordionMain<?php echo $iClients; ?>" class="panel-group" aria-multiselectable="true">

                            <div id="headingClient<?php echo $iClients; ?>" class="panel">
                                <a class="panel-heading collapsed" title="Tab1"
                                   aria-controls="collapseMain-<?php echo $CLIENT_ID; ?>" aria-expanded="false"
                                   href="#collapseMain-<?php echo $CLIENT_ID; ?>" data-toggle="collapse">
                                    <?php echo $nom . ' ' . $prenom; ?>

                                <div id="collapseMain-<?php echo $CLIENT_ID; ?>" class="panel-collapse collapse"
                                     aria-labelledby="heading<?php echo $CLIENT_ID; ?>" aria-expanded="false">

                                        <div id="accordionInside-<?php echo $CLIENT_ID; ?>" class="panel-group"
                                             aria-multiselectable="true" role="tablist">

                                                <a id="headingPersonnelle-<?php echo $CLIENT_ID; ?>"
                                                   class="panel-heading collapsed" title="Tab1"
                                                   aria-controls="collapsePersonnelle-<?php echo $CLIENT_ID; ?>"
                                                   aria-expanded="false"
                                                   href="#collapsePersonnelle-<?php echo $CLIENT_ID; ?>"
                                                   data-toggle="collapse" role="tab">
                                                    Informations Personnelles

                                                <div id="collapsePersonnelle-<?php echo $CLIENT_ID; ?>"
                                                     class="panel-collapse collapse"
                                                     aria-labelledby="headingPersonnelle-<?php echo $CLIENT_ID; ?>"
                                                     role="tabpanel" aria-expanded="false">

                                                        Personelle

                                                <a id="headingContract-<?php echo $CLIENT_ID; ?>"
                                                   class="panel-heading collapsed" title="Tab2"
                                                   aria-controls="collapseContract-<?php echo $CLIENT_ID; ?>"
                                                   aria-expanded="false"
                                                   href="#collapseContract-<?php echo $CLIENT_ID; ?>"
                                                   data-toggle="collapse" role="tab">
                                                    Dossiers

                                                <div id="collapseContract-<?php echo $CLIENT_ID; ?>"
                                                     class="panel-collapse collapse"
                                                     aria-labelledby="headingContract-<?php echo $CLIENT_ID; ?>"
                                                     role="tabpanel" aria-expanded="false">

                                                        <div id="accordionContractBody-<?php echo $CLIENT_ID; ?>"
                                                             class="panel-group" aria-multiselectable="true"
                                                             role="tablist">

                                                            <?php
                                                            $iProjets = 0;
                                                            while ($iProjets < count($projet[$iClients]['projetz'])) {
                                                                $PROJET_ID = $projet[$iClients]['projetz'][$iProjets]['PROJET_ID'];
                                                                ?>

                                                                <div id="accordionContract-<?php echo $CLIENT_ID . '-' . $PROJET_ID; ?>"
                                                                     class="panel-group rapprocher"
                                                                     aria-multiselectable="true" role="tablist">

                                                                        <a id="headingProjet-<?php echo $CLIENT_ID . '-' . $PROJET_ID; ?>"
                                                                           class="panel-heading collapsed" title="Tab1"
                                                                           aria-controls="collapse-<?php echo $CLIENT_ID . '-' . $PROJET_ID; ?>"
                                                                           aria-expanded="false"
                                                                           href="#collapseProjet-<?php echo $CLIENT_ID . '-' . $PROJET_ID; ?>"
                                                                           data-toggle="collapse" role="tab">
                                                                            <?php echo $projet[$iClients]['projetz'][$iProjets]['PROJET_NOM']; ?>

                                                                    <div id="collapseProjet-<?php echo $CLIENT_ID . '-' . $PROJET_ID; ?>"
                                                                         class="panel-collapse collapse"
                                                                         aria-labelledby="headingProjet-<?php echo $CLIENT_ID . '-' . $PROJET_ID; ?>"
                                                                         role="tabpanel" aria-expanded="false">

                                                                            Contracts

                                                                <?php
                                                                $iProjets++;
                                                            }
                                                            ?>

            <?php
            $iClients++;
        }
        ?>
        <?php
    }
    ?>

And here is what i have been trying:

<?php
if (isset($client_id) && $client_id <> "") {
    ?>

    <?php
}
?>

Body:
We can see that you have added unique id to all your ".panel-collapse" divs as id="collapseMain-<?php echo $CLIENT_ID; ?>". We also know that you have the id for which you want to open the accordion.

You can use jquery selector $("#collapseMain-<?php echo $client_id; ?>") to select only the accordion that should be opened.

Lets assume the html code generated by php is:

<div id="accordionbox">
  <div class="form-group">
    <div class="col-xs-12">
      <div class="panel panel-default">
        <div id="accordionMain-1" class="panel-group" aria-multiselectable="true">
          <div id="headingClient-1" class="panel">
            <a class="panel-heading collapsed" title="Tab1"
                                   aria-controls="collapseMain-1>" aria-expanded="false"
                                   href="#collapseMain-1" data-toggle="collapse"><span class="panel-title">Client 1</span></a>
            <div id="collapseMain-1" class="panel-collapse collapse"
                                     aria-labelledby="heading1" aria-expanded="false">
               <div class="panel-body">
                Content 1
               </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="form-group">
    <div class="col-xs-12">
      <div class="panel panel-default">
        <div id="accordionMain-2" class="panel-group" aria-multiselectable="true">
          <div id="headingClient-2" class="panel">
            <a class="panel-heading collapsed" title="Tab2"
                                   aria-controls="collapseMain-2>" aria-expanded="false"
                                   href="#collapseMain-2" data-toggle="collapse"><span class="panel-title">Client 2</span></a>
            <div id="collapseMain-2" class="panel-collapse collapse"
                                     aria-labelledby="heading2" aria-expanded="false">
               <div class="panel-body">
                Content 2
               </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="form-group">
    <div class="col-xs-12">
      <div class="panel panel-default">
        <div id="accordionMain-3" class="panel-group" aria-multiselectable="true">
          <div id="headingClient-3" class="panel">
            <a class="panel-heading collapsed" title="Tab3"
                                   aria-controls="collapseMain-3>" aria-expanded="false"
                                   href="#collapseMain-3" data-toggle="collapse"><span class="panel-title">Client 3</span></a>
            <div id="collapseMain-3" class="panel-collapse collapse"
                                     aria-labelledby="heading3" aria-expanded="false">
               <div class="panel-body">
                Content 3
               </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

</div>

Then you can generate javascript code using php like

<?php
if (isset($client_id) && $client_id <> "") {
    ?>
$(document).ready(function() {
  $("#collapseMain-<?php echo $client_id; ?>").addClass("in");
});

<?php } ?>

You can have a look at this jsfiddle


问:
How do I force Maven to use my local repository rather than going out to remote repos to retrieve artifacts?
I’m using Maven 3.3.3 with Java 8 on Mac Yosemite.  I have a multi-module project.

```<code>    <modules>
            <module>first-module</module>
            <module>my-module</module>
                …
    </modules>
</code>```

When I build my one of my child modules, for example, “my-module” from above, using “mvn clean install”, the build attempts to download the child module artifacts from a remote repository I have defined in my ~/.m2/settings.xml file.  Output is below

```<code>[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building my-module 87.0.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
Downloading: https://my.remoterepository.com/nexus/content/repositories/snapshots/org/mainco/subco/first-module/87.0.0-SNAPSHOT/maven-metadata.xml
Downloading: http://download.java.net/maven/2/org/mainco/subco/first-module/87.0.0-SNAPSHOT/maven-metadata.xml
Downloaded: https://my.remoterepository.com/nexus/content/repositories/snapshots/org/mainco/subco/first-module/87.0.0-SNAPSHOT/maven-metadata.xml (788 B at 0.9 KB/sec)
Downloading: https://my.remoterepository.com/nexus/content/repositories/snapshots/org/mainco/subco/first-module/87.0.0-SNAPSHOT/first-module-87.0.0-20151104.200545-4.pom
</code>```

How do I force Maven to check my local ~/.m2/repository first before trying to download from the remote repositories?  Below is where I have my remote repositories defined in my ~/.m2/settings.xml file …

```<code><profile>
    <id>releases</id>
    <activation>
        <property>
            <name>!releases.off</name>
        </property>
    </activation>
    <repositories>
        <repository>
            <id>releases</id>
            <url>https://my.remoterepository.com/nexus/content/repositories/releases/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
</profile>
<profile>
    <id>snapshots</id>
    <activation>
        <property>
            <name>!snapshots.off</name>
        </property>
    </activation>
    <repositories>
        <repository>
            <id>snapshots</id>
            <url>https://my.remoterepository.com/nexus/content/repositories/snapshots/</url>
            <releases>
                <enabled>false</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>
</profile>
</code>```

Edit: In response to the answer saying that the download occurs when the artifact is not there, below is the terminal output in which I prove the file was there in my repo but Maven is trying to download it anyway ...

```<code>Daves-MacBook-Pro-2:my-module davea$ ls -al ~/.m2/repository/org/mainco/subco/first-module/87.0.0-SNAPSHOT/first-module-87.0.0-SNAPSHOT.jar
-rw-r--r--  1 davea  staff  10171 Nov  5 10:22 /Users/davea/.m2/repository/org/mainco/subco/first-module/87.0.0-SNAPSHOT/first-module-87.0.0-SNAPSHOT.jar
Daves-MacBook-Pro-2:my-module davea$ mvn clean install
[INFO] Scanning for projects...
[WARNING]
[WARNING] Some problems were encountered while building the effective model for org.mainco.subco:my-module:jar:87.0.0-SNAPSHOT
[WARNING] 'build.plugins.plugin.(groupId:artifactId)' must be unique but found duplicate declaration of plugin org.apache.maven.plugins:maven-antrun-plugin @ org.mainco.subco:my-module:[unknown-version], /Users/davea/Documents/sb_workspace/my-module/pom.xml, line 678, column 12
[WARNING]
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING]
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING]
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building my-module 87.0.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
Downloading: https://my.remoterepository.com/nexus/content/repositories/snapshots/org/mainco/subco/first-module/87.0.0-SNAPSHOT/maven-metadata.xml
Downloading: http://download.java.net/maven/2/org/mainco/subco/first-module/87.0.0-SNAPSHOT/maven-metadata.xml
Downloaded: https://my.remoterepository.com/nexus/content/repositories/snapshots/org/mainco/subco/first-module/87.0.0-SNAPSHOT/maven-metadata.xml (788 B at 0.8 KB/sec)
Downloading: https://my.remoterepository.com/nexus/content/repositories/snapshots/org/mainco/subco/first-module/87.0.0-SNAPSHOT/first-module-87.0.0-20151106.043202-8.pom
Downloaded: https://my.remoterepository.com/nexus/content/repositories/snapshots/org/mainco/subco/first-module/87.0.0-SNAPSHOT/first-   module-87.0.0-20151106.043202-8.pom (3 KB at 21.9 KB/sec)
Downloading: http://download.java.net/maven/2/org/mainco/subco/subco/87.0.0-SNAPSHOT/maven-metadata.xml
Downloading: https://my.remoterepository.com/nexus/content/repositories/snapshots/org/mainco/subco/subco/87.0.0-SNAPSHOT/maven-metadata.xml
</code>```

答:
Follow below steps:

Ensure to delete all the contents of the jar folder located in your local except the jar that you want to keep.

For example files like .repositories, .pom, .sha1, .lastUpdated etc.

Execute mvn clean install -o command

This will help to use local repository jar files rather than connecting to any repository.

Body:
I’m using Maven 3.3.3 with Java 8 on Mac Yosemite.  I have a multi-module project.

    <modules>
            <module>first-module</module>
            <module>my-module</module>
                …
    </modules>

When I build my one of my child modules, for example, “my-module” from above, using “mvn clean install”, the build attempts to download the child module artifacts from a remote repository I have defined in my ~/.m2/settings.xml file.  Output is below

[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building my-module 87.0.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
Downloading: https://my.remoterepository.com/nexus/content/repositories/snapshots/org/mainco/subco/first-module/87.0.0-SNAPSHOT/maven-metadata.xml
Downloading: http://download.java.net/maven/2/org/mainco/subco/first-module/87.0.0-SNAPSHOT/maven-metadata.xml
Downloaded: https://my.remoterepository.com/nexus/content/repositories/snapshots/org/mainco/subco/first-module/87.0.0-SNAPSHOT/maven-metadata.xml (788 B at 0.9 KB/sec)
Downloading: https://my.remoterepository.com/nexus/content/repositories/snapshots/org/mainco/subco/first-module/87.0.0-SNAPSHOT/first-module-87.0.0-20151104.200545-4.pom

How do I force Maven to check my local ~/.m2/repository first before trying to download from the remote repositories?  Below is where I have my remote repositories defined in my ~/.m2/settings.xml file …

<profile>
    <id>releases</id>
    <activation>
        <property>
            <name>!releases.off</name>
        </property>
    </activation>
    <repositories>
        <repository>
            <id>releases</id>
            <url>https://my.remoterepository.com/nexus/content/repositories/releases/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
</profile>
<profile>
    <id>snapshots</id>
    <activation>
        <property>
            <name>!snapshots.off</name>
        </property>
    </activation>
    <repositories>
        <repository>
            <id>snapshots</id>
            <url>https://my.remoterepository.com/nexus/content/repositories/snapshots/</url>
            <releases>
                <enabled>false</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>
</profile>

Edit: In response to the answer saying that the download occurs when the artifact is not there, below is the terminal output in which I prove the file was there in my repo but Maven is trying to download it anyway ...

Daves-MacBook-Pro-2:my-module davea$ ls -al ~/.m2/repository/org/mainco/subco/first-module/87.0.0-SNAPSHOT/first-module-87.0.0-SNAPSHOT.jar
-rw-r--r--  1 davea  staff  10171 Nov  5 10:22 /Users/davea/.m2/repository/org/mainco/subco/first-module/87.0.0-SNAPSHOT/first-module-87.0.0-SNAPSHOT.jar
Daves-MacBook-Pro-2:my-module davea$ mvn clean install
[INFO] Scanning for projects...
[WARNING]
[WARNING] Some problems were encountered while building the effective model for org.mainco.subco:my-module:jar:87.0.0-SNAPSHOT
[WARNING] 'build.plugins.plugin.(groupId:artifactId)' must be unique but found duplicate declaration of plugin org.apache.maven.plugins:maven-antrun-plugin @ org.mainco.subco:my-module:[unknown-version], /Users/davea/Documents/sb_workspace/my-module/pom.xml, line 678, column 12
[WARNING]
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING]
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING]
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building my-module 87.0.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
Downloading: https://my.remoterepository.com/nexus/content/repositories/snapshots/org/mainco/subco/first-module/87.0.0-SNAPSHOT/maven-metadata.xml
Downloading: http://download.java.net/maven/2/org/mainco/subco/first-module/87.0.0-SNAPSHOT/maven-metadata.xml
Downloaded: https://my.remoterepository.com/nexus/content/repositories/snapshots/org/mainco/subco/first-module/87.0.0-SNAPSHOT/maven-metadata.xml (788 B at 0.8 KB/sec)
Downloading: https://my.remoterepository.com/nexus/content/repositories/snapshots/org/mainco/subco/first-module/87.0.0-SNAPSHOT/first-module-87.0.0-20151106.043202-8.pom
Downloaded: https://my.remoterepository.com/nexus/content/repositories/snapshots/org/mainco/subco/first-module/87.0.0-SNAPSHOT/first-   module-87.0.0-20151106.043202-8.pom (3 KB at 21.9 KB/sec)
Downloading: http://download.java.net/maven/2/org/mainco/subco/subco/87.0.0-SNAPSHOT/maven-metadata.xml
Downloading: https://my.remoterepository.com/nexus/content/repositories/snapshots/org/mainco/subco/subco/87.0.0-SNAPSHOT/maven-metadata.xml


问:
How to use Exception filters in MVC 5
How i can implement Exception Filters in MVC5.

I want to throw the exception to NLog and redirect the page to a default error page which displays "Something is gone wrong"

I have a Filter class as follows

```<code>using System;
using System.Diagnostics;
using System.Security.Policy;
using System.Web.Mvc;
using System.Web.Mvc.Filters;
using System.Web.Routing;
using System.Web.UI.WebControls;
using Delivros.UI.Controllers;
using Delivros.UI.Areas.User.ViewModel;
using System.Web;

namespace Delivros.UI.Filters
{

public class CustomAuthenticationFilter : IAuthenticationFilter
{
    public void OnAuthentication(AuthenticationContext filterContext)
    {

    }

    public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
    {
        Debug.WriteLine("OnAuthenticationChallenge : MyAuthenticationFilter");
    }
}
 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MyAuthorizationFilter : AuthorizeAttribute
{
     public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext.RequestContext.HttpContext.Request.Cookies[System.Configuration.ConfigurationManager.AppSettings[Convert.ToString(CookieField.cookieName)]] == null)
        {

        }
        else
{
            filterContext.Result = new RedirectToRouteResult(
            new RouteValueDictionary
    {
                { "controller", "User" },
                { "action", "UserRegistration" } ,
                {"Area","User"}
            });

        }
    }
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class CustomActionFilter : ActionFilterAttribute
{
    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
        filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        filterContext.HttpContext.Response.Cache.SetNoStore();
        base.OnResultExecuted(filterContext);
        filterContext.Result = new RedirectToRouteResult(
              new RouteValueDictionary
            {
                { "controller", "User" },
                { "action", "UserRegistration" } ,
                {"Area","User"}
            });
        // ActionResult home = new HomeController().Index();
    }
}

public class MyResultFilter : IResultFilter
{
    public void OnResultExecuting(ResultExecutingContext filterContext)
    {

    }

    public void OnResultExecuted(ResultExecutedContext filterContext)
    {

    }
}

public class MyExceptionFilter : IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        filterContext.Result = new RedirectToRouteResult(
              new RouteValueDictionary
            {
                { "controller", "User" },
                { "action", "UserLogOut" } ,
                {"Area","User"}
            });

    }
}
</code>```

}

But nothing is redirecting to the page...

答:
Exception filters are run only when unhandled  exception has been thrown inside an action method. As you asked, here is an example to redirect to another page upon exception:

```<code>public class MyExceptionAttribute : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        if(!filterContext.ExceptionHandled)
        {
            filterContext.Result = new RedirectResult("~/Content/ErrorPage.html");
            filterContext.ExceptionHandled = true;
        }
    }
}
</code>```

Now, to apply this filter to either controllers or individual actions, put [MyException] on them.

You may need to check the occurence of an specific Exception inside the if clause.
e.g.:

```<code>if(... && filterContext.Excaption is ArgumentOutOfRangeException)
</code>```

To return a View as Exception Response:

```<code>filterContext.Result = new RedirectResult("/Home/ErrorAction");
</code>```

other alternatives you might use to redirect are:

new RedirectToRouteResult{ ... }

new ViewResult{ ... }

ContentLicense: CC BY-SA 3.0

Title: How to use Exception filters in MVC 5

Body:
How i can implement Exception Filters in MVC5.

I want to throw the exception to NLog and redirect the page to a default error page which displays "Something is gone wrong"

I have a Filter class as follows

using System;
using System.Diagnostics;
using System.Security.Policy;
using System.Web.Mvc;
using System.Web.Mvc.Filters;
using System.Web.Routing;
using System.Web.UI.WebControls;
using Delivros.UI.Controllers;
using Delivros.UI.Areas.User.ViewModel;
using System.Web;

namespace Delivros.UI.Filters
{

public class CustomAuthenticationFilter : IAuthenticationFilter
{
    public void OnAuthentication(AuthenticationContext filterContext)
    {

    }

    public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
    {
        Debug.WriteLine("OnAuthenticationChallenge : MyAuthenticationFilter");
    }
}
 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MyAuthorizationFilter : AuthorizeAttribute
{
     public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext.RequestContext.HttpContext.Request.Cookies[System.Configuration.ConfigurationManager.AppSettings[Convert.ToString(CookieField.cookieName)]] == null)
        {

        }
        else
{
            filterContext.Result = new RedirectToRouteResult(
            new RouteValueDictionary
    {
                { "controller", "User" },
                { "action", "UserRegistration" } ,
                {"Area","User"}
            });

        }
    }
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class CustomActionFilter : ActionFilterAttribute
{
    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
        filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        filterContext.HttpContext.Response.Cache.SetNoStore();
        base.OnResultExecuted(filterContext);
        filterContext.Result = new RedirectToRouteResult(
              new RouteValueDictionary
            {
                { "controller", "User" },
                { "action", "UserRegistration" } ,
                {"Area","User"}
            });
        // ActionResult home = new HomeController().Index();
    }
}

public class MyResultFilter : IResultFilter
{
    public void OnResultExecuting(ResultExecutingContext filterContext)
    {

    }

    public void OnResultExecuted(ResultExecutedContext filterContext)
    {

    }
}

public class MyExceptionFilter : IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        filterContext.Result = new RedirectToRouteResult(
              new RouteValueDictionary
            {
                { "controller", "User" },
                { "action", "UserLogOut" } ,
                {"Area","User"}
            });

    }
}

}

But nothing is redirecting to the page...

Body:
Exception filters are run only when unhandled  exception has been thrown inside an action method. As you asked, here is an example to redirect to another page upon exception:

public class MyExceptionAttribute : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        if(!filterContext.ExceptionHandled)
        {
            filterContext.Result = new RedirectResult("~/Content/ErrorPage.html");
            filterContext.ExceptionHandled = true;
        }
    }
}

Now, to apply this filter to either controllers or individual actions, put [MyException] on them.

You may need to check the occurence of an specific Exception inside the if clause.
e.g.:

if(... && filterContext.Excaption is ArgumentOutOfRangeException)

To return a View as Exception Response:

filterContext.Result = new RedirectResult("/Home/ErrorAction");

other alternatives you might use to redirect are:

new RedirectToRouteResult{ ... }

new ViewResult{ ... }


问:
In GBM of h2o, I set training_frame, validation_frame and nfolds at the same time. I want to know the order of training
If the training_frame, validation_frame and nfolds exist at the same time. How gbm train and valid by using h2o.gbm</p>

答:
If validation_frame is provided and nfolds >= 2 at the same time then first cross validation metrics will be computed and as a next step gbm will score on validation_frame. So for example in Flow there will be two sections:

Output - Validation Metrics

Output - Cross Validation Metrics


问:
How to generate all posible binary nxm matrices, where the sum of each row is 1
I'm working on an assignment where i have to assign 1 up to 10 distribution centers  to all US states. I have made a model in excel to calculate all the costs, and clearly the goal of the assignment is to find the cheapest way. I have 50 rows (for each state) and 10 columns (for all possible DC locations). My model is based on this matrix, and if I change the matrix, the costs will instantly display. The only constraint is that each state is supplied by exactly 1 DC.

Its clear I cant make all possible combinations by hand, I have tried to translate my model into an optimization program (AIMMS), but it'l take allot of time witch I already put in the excel model. I was thinking if I had all possible matrices (generated in R, Matlab, or Python, dont care witch one) i can loop over my spreadsheet them and let a program read the cost, to determine the best choice. Its theoretically possible to supply all state by 1 DC, and at most 10, so every possible  1x50, 2x50, 3x50 ... 10x50 matrix is needed to determine the best one.

So again in short, is it possible to generate every nxm binary matrix with a sum total of 1 on each row in preferably R, or otherwise in Matlab or Python?

答:
TLDR: No.

Let's look at the simpliest example: 2 DC. Your possible rows will be:

(1,0)

(0,1)

Now you want to construct all possible 2x50 matrices. Their number is 2^50 (2 possible rows in 50 rows). It is equal to:

1125899906842624

We suppose that each matrix stores 100 bytes. That all 2x50 matrices will store:

(2**50) * 100 / 1024 / 1024 / 1024 / 1024 = 102400 terabytes of data.

And to process all of them (in the most optimistic results for normal computers) will spend time equal to:

(2**50) / 10**9 / 60 / 60 = 312 hours.

And 10x50 will be even more...


问:
Storing const reference to an object in class
This sounds like a basic question, but I didn't find any comprehensive answer, so here it is. Consider this code snippet:

```<code>struct A {
    const std::string& s;
    A(const std::string& s) : s(s) {}
};

int main() {
    A a("abc");
    std::cout << a.s << std::endl;
    return 0;
}
</code>```

Demo.

As long as I understand, this is UB. String literal "abc" binds to const std::string& in constructor, creating a temporary string object. It is also bound to reference a.s, and it is destroyed once a is constructed. That is, const reference cannot chain lifetime prolongation. Dangling reference, boom. In this particular case I see no output at all on ideone.com, but anything could happen (remember velociraptors).

Ok, this one is clear. But what if this is actually our very intent: we want to store a const reference to an object? To an existing one, not to temporary? This sounds like a very natural task, yet I came up with only one (almost) natural solution to it. Accepting constructor's argument by std::reference_wrapper instead of by reference:

```<code>    A(std::reference_wrapper<const std::string> r) : s(r) {}
</code>```

Since std::reference_wrapper has deleted constructors from temporaries:

```<code>reference_wrapper( T&& x ) = delete;
</code>```

this works just like expected. However, this is not quite elegant. Another approach I can think of is to accept forwarding reference T&& and to reject everything except const l-value strings with std::enable_if. This is even less elegant, I think.

Any other approaches?

UPD Another question: is this a legitimate usage of std::reference_wrapper, or may it be considered too specific?

答:
There is a very simple class lvalue_ref provided in the lightweight and convenient "explicit" library by Andrzej Krzemieński, which solves exactly this problem with a clear intention:

```<code>struct Processor
{
  Big const& _big;
  explicit Processor(lvalue_ref<const Big> b) : _big(b) {}
};

const Big b {};
Processor p {b}; // ok
Processor q {Big{}}; // error (temporary)
</code>```

Body:
This sounds like a basic question, but I didn't find any comprehensive answer, so here it is. Consider this code snippet:

struct A {
    const std::string& s;
    A(const std::string& s) : s(s) {}
};

int main() {
    A a("abc");
    std::cout << a.s << std::endl;
    return 0;
}

Demo.

As long as I understand, this is UB. String literal "abc" binds to const std::string& in constructor, creating a temporary string object. It is also bound to reference a.s, and it is destroyed once a is constructed. That is, const reference cannot chain lifetime prolongation. Dangling reference, boom. In this particular case I see no output at all on ideone.com, but anything could happen (remember velociraptors).

Ok, this one is clear. But what if this is actually our very intent: we want to store a const reference to an object? To an existing one, not to temporary? This sounds like a very natural task, yet I came up with only one (almost) natural solution to it. Accepting constructor's argument by std::reference_wrapper instead of by reference:

    A(std::reference_wrapper<const std::string> r) : s(r) {}

Since std::reference_wrapper has deleted constructors from temporaries:

reference_wrapper( T&& x ) = delete;

this works just like expected. However, this is not quite elegant. Another approach I can think of is to accept forwarding reference T&& and to reject everything except const l-value strings with std::enable_if. This is even less elegant, I think.

Any other approaches?

UPD Another question: is this a legitimate usage of std::reference_wrapper, or may it be considered too specific?

Body:
There is a very simple class lvalue_ref provided in the lightweight and convenient "explicit" library by Andrzej Krzemieński, which solves exactly this problem with a clear intention:

struct Processor
{
  Big const& _big;
  explicit Processor(lvalue_ref<const Big> b) : _big(b) {}
};

const Big b {};
Processor p {b}; // ok
Processor q {Big{}}; // error (temporary)


答:
This won't work, you cannot just access the parent's state directly in all the child components,
you have to send the parents state down to the child components as a prop to access them.

In scenario like this where you want to use one state in all of your child components the good thing is to use Redux, it will provide you a global state which will be accessible in all of your components.
Also you can solve this problem with React's Context API.

Title: Render state in another component in reactjs


问:
How can LiveDocx in PHP be used to read .doc & .docx files and read text inside it and save to HTML?
Let's say we have a .doc & .docx files. I want to use LiveDocx in PHP to load the files, read it's content and strip the text from inside it. Then save it to an HTML string.

Can this be done?

I've searched the documentation, and it seams that LiveDocx only loads .doc & .docx template files only!

答:
I think you can find what you need in this example.

I might be wrong, but I think they call them "template" files because they act like a template but are still normal .doc/.docx documents. I suggest you simply try to run that example.

ContentLicense: CC BY-SA 2.5


问:
Define a class is not working globally but locally it is
When I define a code for a class within the custom CSS of a post this is working however if I define the same code globally under my theme options-> Custom CSS this is not working.

```<code>.learndash-wrapper .ld-table-list a.ld-table-list-item-preview {
    color: #13fff8;
}.
</code>```

Therefore I have to go post by post adding this code to get the proper font color... and I would like to have it globally working.

Any idea why this happened?

答:
First, check whether you have a typo or not. After verifying that you have entered class name properly. You can try out as,

```<code>.your-class-name{
  color : #ffffff !important;
}
</code>```

!important has the superpower to override previous CSS class and it's properties.

There are guidelines and defined the precedence of different CSS stylings.
Checkout,

https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

Ask in the comment if required a more specific answer.

Body:
When I define a code for a class within the custom CSS of a post this is working however if I define the same code globally under my theme options-> Custom CSS this is not working.

.learndash-wrapper .ld-table-list a.ld-table-list-item-preview {
    color: #13fff8;
}.

Therefore I have to go post by post adding this code to get the proper font color... and I would like to have it globally working.

Any idea why this happened?

Body:
First, check whether you have a typo or not. After verifying that you have entered class name properly. You can try out as,

.your-class-name{
  color : #ffffff !important;
}

!important has the superpower to override previous CSS class and it's properties.

There are guidelines and defined the precedence of different CSS stylings.
Checkout,

https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

Ask in the comment if required a more specific answer.


答:
Use str.title()

Ex:

```<code>def capitalise_words(file_name, destination):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        capped = text_str.title()

    with open(destination, "w") as writefile:
        writefile.write(capped)
</code>```

To replace all new-line chars use

```<code>capped = " ".join(word for word in text_str.splitlines()).title()
</code>```

Title: Copy .txt file and capitalise first letter of each word and write to new file

Body:
Use str.title()

Ex:

def capitalise_words(file_name, destination):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        capped = text_str.title()

    with open(destination, "w") as writefile:
        writefile.write(capped)

To replace all new-line chars use

capped = " ".join(word for word in text_str.splitlines()).title()


问:
How to show a loading indicator when loading the app at the first time
I have to load many files for my AngularJs single page application, like angular.js, jquery.js, bootstrap.js, bootstrap.css, some_plugins.js, my_main.js and others,

It take some time to load the entire app, so I want to show a loading indicator (a spinner for example) in a void page until all the js and css files load and then display the content.

答:
you can simply do it in 3 steps as follows.

1.add

 inside ,

2.add .se-pre-con css class to your styles,

3.finally add these few jquery codes:

$(window).load(function () {$(".se-pre-con").fadeOut("slow");});

(don't forget to add JQuery library in your project)

that's it.

this is an example that work:

```<code><!-- language: lang-html -->

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<!DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="utf-8" />
        <title>title</title>
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta content="" name="keywords">
        <meta content="" name="description">
        <meta content="width=device-width, initial-scale=1" name="viewport" />

        <style>

            body {
                background: green;
            }

            .se-pre-con {
                position: fixed;
                left: 0px;
                top: 0px;
                width: 100%;
                height: 100%;
                z-index: 9999;
                background: url('https://cdn.dribbble.com/users/421466/screenshots/2390664/orbit-400px.gif') center no-repeat white;
                background-size: 150px 150px;
            }
        </style>

    </head>
    <body>

        <div class="se-pre-con"></div>

        <!--==========================
        your body content will come here
        ============================-->

        <script>
            $(window).load(function () {
                $(".se-pre-con").fadeOut("slow");
            });
        </script>

    </body>

    </html>
</code>```

in this example because of light page the loader gif disapear very fast. but in heavy pages it is a good solution for your problem.

this is a plunker run

I wish it helps

Body:
you can simply do it in 3 steps as follows.

1.add <div class="se-pre-con"></div> inside <body>,

2.add .se-pre-con css class to your styles,

3.finally add these few jquery codes:

$(window).load(function () {$(".se-pre-con").fadeOut("slow");});

(don't forget to add JQuery library in your project)

that's it.

this is an example that work:

<!-- language: lang-html -->

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<!DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="utf-8" />
        <title>title</title>
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta content="" name="keywords">
        <meta content="" name="description">
        <meta content="width=device-width, initial-scale=1" name="viewport" />

        <style>

            body {
                background: green;
            }

            .se-pre-con {
                position: fixed;
                left: 0px;
                top: 0px;
                width: 100%;
                height: 100%;
                z-index: 9999;
                background: url('https://cdn.dribbble.com/users/421466/screenshots/2390664/orbit-400px.gif') center no-repeat white;
                background-size: 150px 150px;
            }
        </style>

    </head>
    <body>

        <div class="se-pre-con"></div>

        <!--==========================
        your body content will come here
        ============================-->

        <script>
            $(window).load(function () {
                $(".se-pre-con").fadeOut("slow");
            });
        </script>

    </body>

    </html>

in this example because of light page the loader gif disapear very fast. but in heavy pages it is a good solution for your problem.

this is a plunker run

I wish it helps


问:
Find missing permutation
This problem was presented by google at a recent codejam round and it still haunts me how i didnt manage to solve it. please show me how it can be done:

Go, go, Power Arrangers! Everyone loves this team of five superhero
  high school students who wear the letters A, B, C, D, and E. When they
  stand side by side to confront evil monsters, they arrange their team
  in one of 120 possible different left-to-right orders, giving them
  various different tactical superpowers. They are even more popular
  than the Teenage Permutant Ninja Turtles!

Some critics of the show claim that the team only has its arrangment
  gimmick so that the owners of the show can sell 120 separate sets of 5
  action figures, each of which features the team in a different
  left-to-right order, glued to a base so that the set cannot be
  rearranged. As an avid Power Arrangers fan, you have collected 119 of
  these sets, but you do not remember which set you are missing. Your
  119 sets are lined up horizontally along a shelf, such that there are
  a total of 119 × 5 = 595 action figures in left-to-right order. You do
  not remember how the sets are arranged, but you know that the
  permutation of the sets is selected uniformly at random from all
  possible permutations, and independently for each case.

You do not want to waste any time figuring out which set you are
  missing, so you plan to look at the letters on at most F figures on
  the shelf. For instance, you might choose to look at the letter on the
  eighth figure from the left, which would be the third figure from the
  left in the second set from the left. When looking at a figure, you
  only get the letter from that one figure; the letters are hard to see,
  and the different team members look very similar otherwise!

After checking at most F figures, you must figure out which of the
  sets is missing, so you can complete your collection and be ready to
  face any possible evil threat!

Input and output

This is an interactive problem. You should make sure you have read the
  information in the Interactive Problems section of our FAQ.

Initially, your program should read a single line containing two
  integers T, the number of test cases, and F, the number of figures you
  are allowed to inspect per test case. Then, you need to process T test
  cases.

Within each test case, the missing set of figures is chosen uniformly
  at random from all possible sets, and the order of the remaining sets
  is chosen uniformly at random from all possible orders as well. Every
  choice is made independently of all other choices and of your inputs.

In each test case, your program will process up to F + 1 exchanges
  with our judge. You may make up to F exchanges of the following form:

Your program outputs one line containing a single integer between 1 and 595, inclusive, indicating which figure (in left-to-right order
  along the shelf) you wish to look at. As a further example, 589 would
  represent the fourth figure from the left in the second set from the
  right.

The judge responds with one line containing a single uppercase letter A, B, C, D, or E, indicating the letter on that figure. If you
  sent invalid data (e.g., a number out of range, or a malformed line),
  the judge will instead respond with one line containing the single
  uppercase letter N.

Then, after you have made as many of the F exchanges above as you
  want, you must make one more exchange of the following form:

Your program outputs one line containing a single string of five uppercase letters: the permutation corresponding to the missing set
  (e.g., CADBE).

The judge responds with one line containing a single uppercase letter: Y if your answer was correct, and N if it was not (or you
  provided a malformed line). If you receive Y, you should begin the
  next test case, or stop sending input if there are no more test cases.

After the judge sends N to your input stream (because of either
  invalid data or an incorrect answer), it will not send any other
  output. If your program continues to wait for the judge after
  receiving N, your program will time out, resulting in a Time Limit
  Exceeded error. Notice that it is your responsibility to have your
  program exit in time to receive a Wrong Answer judgment instead of a
  Time Limit Exceeded error. As usual, if the memory limit is exceeded,
  or your program gets a runtime error, you will receive the appropriate
  judgment. Limits

1 ≤ T ≤ 50. Time limit: 40 seconds per test set. Memory limit: 1GB.
  The missing set, and the order of the remaining sets, are chosen
  uniformly and independently at random. Test set 1 (Visible)

F = 475. Test set 2 (Hidden)

F = 150.

答:
You could try something like this:

use your first 119 queries to query the first element of each "block", i.e. the 0th, 5th, 10th, etc. element

count how often you find each letter, and where; there should be 24 permutations for each starting letter, but for one there are only 23

continue with those 23 permutations and query the second letter of those blocks, e.g. if the starting positions of those were 15, 40, 60, ..., query the 16th, 41th, 61th, ... letter

again, count how often you find each second letter; there should be 6 for each, but for one letter there are only 5

continue with those 5 and query the 3rd letter of those; for one of those, there will be only one permutation instead of two

now you know the first three letters of the missing permutation; make a final query for the fourth (or fifth) letter of that single permutation with the same first three digits from the last step, and you can infer the last two digits of the missing permutation

This way, you will need 119 + 23 + 5 + 1 = 148 queries to find the missing permutation.

Example implementation in Python:

import itertools, random, collections
permutations = list(itertools.permutations("ABCDE"))
random.shuffle(permutations)
permutations.pop()
flat_permutations = [c for p in permutations for c in p]

queries = 0
candidates = [i * 5 for i in range(119)]
missing = ""
for i in [0, 1, 2, 4]:
    where = collections.defaultdict(list)
    for t in candidates:
        queries += 1
        c = flat_permutations[t + i]
        where[c].append(t)
    c, candidates = min(where.items(), key=lambda item: len(item[1]))
    missing += c

# we queried for the 5th and used it as 4th in 'missing'
missing += next(c for c in "ABCDE" if c not in missing)

print("queries", queries)
print("missing", missing)
print("correct?", tuple(missing) not in permutations)
```

This will always find the missing permutation, but it will also always1) take 148 queries.

If F is smaller, you might just query random positions and then use probability to guess the permutation that least fits those guesses.

1) Technically, you could find it with fewer queries, e.g. if you are very lucky and after 100 queries you alredy have 4 letters with 24 positions each, you do not need to do the last 19 queries, but that would be pure luck, and the chances for this are rather slim.

Title: Find missing permutation

Body:
You could try something like this:

use your first 119 queries to query the first element of each "block", i.e. the 0th, 5th, 10th, etc. element

count how often you find each letter, and where; there should be 24 permutations for each starting letter, but for one there are only 23

continue with those 23 permutations and query the second letter of those blocks, e.g. if the starting positions of those were 15, 40, 60, ..., query the 16th, 41th, 61th, ... letter

again, count how often you find each second letter; there should be 6 for each, but for one letter there are only 5

continue with those 5 and query the 3rd letter of those; for one of those, there will be only one permutation instead of two

now you know the first three letters of the missing permutation; make a final query for the fourth (or fifth) letter of that single permutation with the same first three digits from the last step, and you can infer the last two digits of the missing permutation

This way, you will need 119 + 23 + 5 + 1 = 148 queries to find the missing permutation.

Example implementation in Python:

import itertools, random, collections
permutations = list(itertools.permutations("ABCDE"))
random.shuffle(permutations)
permutations.pop()
flat_permutations = [c for p in permutations for c in p]

queries = 0
candidates = [i * 5 for i in range(119)]
missing = ""
for i in [0, 1, 2, 4]:
    where = collections.defaultdict(list)
    for t in candidates:
        queries += 1
        c = flat_permutations[t + i]
        where[c].append(t)
    c, candidates = min(where.items(), key=lambda item: len(item[1]))
    missing += c

# we queried for the 5th and used it as 4th in 'missing'
missing += next(c for c in "ABCDE" if c not in missing)

print("queries", queries)
print("missing", missing)
print("correct?", tuple(missing) not in permutations)

This will always find the missing permutation, but it will also always1) take 148 queries.

If F is smaller, you might just query random positions and then use probability to guess the permutation that least fits those guesses.

1) Technically, you could find it with fewer queries, e.g. if you are very lucky and after 100 queries you alredy have 4 letters with 24 positions each, you do not need to do the last 19 queries, but that would be pure luck, and the chances for this are rather slim.


问:
How to backup a partitioned table in GreenPlum 5.18
Is it possible to make a backup of a specific partitioned table with GreenPlum?

When using:

```<code>pg_dump -t schema.partitioned_table dbname >/tmp/tlb
</code>```

I could get all partition tables with DDL if I exe my command on my GP's master node.

I could not get any partitions tables with DDL when I exe my command without my GP's nodes.

What should I do without my GP's nodes to get partition tables with DDL?

pro on  pg 10

答:
Ok.

The answer is GP's pg_dump is different from pg's pg_dmp.
Exe the command on GP's master node and any other pg nodes to see the different.

pg_dump --help

Body:
Is it possible to make a backup of a specific partitioned table with GreenPlum?

When using:

pg_dump -t schema.partitioned_table dbname >/tmp/tlb

I could get all partition tables with DDL if I exe my command on my GP's master node.

I could not get any partitions tables with DDL when I exe my command without my GP's nodes.

What should I do without my GP's nodes to get partition tables with DDL?

pro on  pg 10


问:
Pyspark UDF - TypeError: 'module' object is not callable
I am trying to run the following code based on some tutorial I found online:

```<code>import pandas as pd
from pyspark.sql import SparkSession
from pyspark.sql import functions
from pyspark.sql import udf
df_pd = pd.DataFrame(
data={'integers': [1, 2, 3],
 'floats': [-1.0, 0.5, 2.7],
 'integer_arrays': [[1, 2], [3, 4, 5], [6, 7, 8, 9]]}
)

df = spark.createDataFrame(df_pd)
df.show()

def square(x):
    return x**2
from pyspark.sql.types import IntegerType
square_udf_int = udf(lambda z: square(z), IntegerType())
</code>```

But when I run the last line I get the following error:

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
</code>```

I am using spark 2.3.3 on Hadoop 2.7.

Thanks

答:
it seems you're importing from pyspark.sql while it should be pyspark.sql.functions
like...

```<code>import pyspark.sql.functions as F

     udf_fun = F.udf (lambda..., Type())
</code>```

Body:
I am trying to run the following code based on some tutorial I found online:

import pandas as pd
from pyspark.sql import SparkSession
from pyspark.sql import functions
from pyspark.sql import udf
df_pd = pd.DataFrame(
data={'integers': [1, 2, 3],
 'floats': [-1.0, 0.5, 2.7],
 'integer_arrays': [[1, 2], [3, 4, 5], [6, 7, 8, 9]]}
)

df = spark.createDataFrame(df_pd)
df.show()

def square(x):
    return x**2
from pyspark.sql.types import IntegerType
square_udf_int = udf(lambda z: square(z), IntegerType())

But when I run the last line I get the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable

I am using spark 2.3.3 on Hadoop 2.7.

Thanks

Body:
it seems you're importing from pyspark.sql while it should be pyspark.sql.functions
like...

import pyspark.sql.functions as F

     udf_fun = F.udf (lambda..., Type())


问:
PHP How to remove white spaces, obfuscating the output HTML CODE on the fly at the Server
I have a simple website in PHP.

My website does not use any Data Source, just some simple PHP scripts to allow some basic functionality.

As for my understanding when a User request my website the PHP code generates the HTML code that will be read by their browser.

I need to make difficult (in some how obfuscate) the HTML generated, so if the user would save a HTML page the code would be difficult to modify and uneasy to interpreter.

My basic need are basically COMPRESSING the HTML:

Eliminate white space. So all code would be packed in few line. Making it in some how human unreadable

Encode the HTML (optional)

Because I have many pages in my website. I'm looking for an automatic solution so I can add some code in one place and have for the next moment all pages output as described above.

Any idea how to do it?

Thanks for your time.

答:
You can use output buffering and "obfuscate" your output in a global callback function:

http://php.net/manual/en/function.ob-start.php


问:
How to add multiple knowledge base to a single bot in Azure portal using Node.js?
I have two knowledge base and I wan to use both of them for a single bot to search an answer. How can I use multiple knowledge bases.</p>

答:
Below is the text from my answer here. A sample nodejs application is available in the official repo.

There is a guide and sample project available here.

Basically you create a LUIS app and then you use the Dispatch tool to create a local file which scans all of your knowledge bases and extracts your questions to use as something that LUIS calls utterances, these utterances are then used to determine the user's LUIS intent in your case which knowledge base to use. Basically the dispatch app in LUIS acts as a router. One you have created the dispatch file locally then you need to push it up to your LUIS app (dispatch create command).

I would recommend downloading the sample app and running through the whole process to get a basic understanding of how everything fits together. Once you have published your LUIS app you will be able to test it within the LUIS portal by inputting example utterances and inspecting the reply to see the intent that was selected. The documentation for the Dispatch tool is available here, please note that when you update your knowledge bases (by adding new entries or alternative phrasing) after publishing your dispatch app initially you will have to refresh your dispatch model for these new questions/alternative phrase to have an utterance added in LUIS to that map to the correct LUIS intent - otherwise they will return the None intent.

NB. you could hack around the need to update the dispatcher by handling the case when you get a the "None" intent back and iterating through all of your knowledge bases to request an answer for the user's query and just return the answer with the higher score (have a collection that keeps the answer from each knowledge base) but I wouldn't recommend it as you miss out on the benefits of Active learning for LUIS and QnA Maker.


问:
App crashes when attempting to swap activities
This is a basic activity swapping.

The app does not crash if i declare a local button inside the configureActivitySwap() method like this:

```<code>Button voiceBtn = (findViewById(R.id.goToVoice));
</code>```

But I have to declare the button in the global scope instead so I can use the button in other methods, mainly activating and deactivating the button when it should/should not be pressed.

I also noticed that if I remove the finish(); method and replace it with something else the app functions normally, but I have to have the finish(); method one way or another.

```<code>public class RecogActivity extends AppCompatActivity {

    private Button voiceBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        voiceBtn = findViewById(R.id.goToVoice);
        setContentView(R.layout.main_layout);

        // some unrelated code

        configureActivitySwap();
    }

    public void configureActivitySwap(){
        // Button voiceBtn = (findViewById(R.id.goToVoice));

        voiceBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

}
</code>```

My runtime error logs:

```<code>    E/AndroidRuntime: FATAL EXCEPTION: main
        Process: tk.gandriks.gaaudiotransform, PID: 23125
        java.lang.RuntimeException: Unable to start activity ComponentInfo{tk.gandriks.gaaudiotransform/tk.gandriks.gaaudiotransform.RecogActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
            at android.app.ActivityThread.-wrap11(Unknown Source:0)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
            at android.os.Handler.dispatchMessage(Handler.java:105)
            at android.os.Looper.loop(Looper.java:164)
            at android.app.ActivityThread.main(ActivityThread.java:6944)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
         Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
            at tk.gandriks.gaaudiotransform.RecogActivity.configureActivitySwap(RecogActivity.java:140)
            at tk.gandriks.gaaudiotransform.RecogActivity.onCreate(RecogActivity.java:124)
            at android.app.Activity.performCreate(Activity.java:7183)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2910)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
            at android.app.ActivityThread.-wrap11(Unknown Source:0)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
            at android.os.Handler.dispatchMessage(Handler.java:105)
            at android.os.Looper.loop(Looper.java:164)
            at android.app.ActivityThread.main(ActivityThread.java:6944)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
</code>```

答:
```<code>voiceBtn = (Button) findViewById(R.id.goToVoice);
</code>```

replace the statement in your onCreate() method with the above. It should work.

and use

```<code>super.finish() instead of finish()
</code>```

Body:
This is a basic activity swapping.

The app does not crash if i declare a local button inside the configureActivitySwap() method like this:

Button voiceBtn = (findViewById(R.id.goToVoice));

But I have to declare the button in the global scope instead so I can use the button in other methods, mainly activating and deactivating the button when it should/should not be pressed.

I also noticed that if I remove the finish(); method and replace it with something else the app functions normally, but I have to have the finish(); method one way or another.

public class RecogActivity extends AppCompatActivity {

    private Button voiceBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        voiceBtn = findViewById(R.id.goToVoice);
        setContentView(R.layout.main_layout);

        // some unrelated code

        configureActivitySwap();
    }

    public void configureActivitySwap(){
        // Button voiceBtn = (findViewById(R.id.goToVoice));

        voiceBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

}

My runtime error logs:

    E/AndroidRuntime: FATAL EXCEPTION: main
        Process: tk.gandriks.gaaudiotransform, PID: 23125
        java.lang.RuntimeException: Unable to start activity ComponentInfo{tk.gandriks.gaaudiotransform/tk.gandriks.gaaudiotransform.RecogActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
            at android.app.ActivityThread.-wrap11(Unknown Source:0)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
            at android.os.Handler.dispatchMessage(Handler.java:105)
            at android.os.Looper.loop(Looper.java:164)
            at android.app.ActivityThread.main(ActivityThread.java:6944)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
         Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
            at tk.gandriks.gaaudiotransform.RecogActivity.configureActivitySwap(RecogActivity.java:140)
            at tk.gandriks.gaaudiotransform.RecogActivity.onCreate(RecogActivity.java:124)
            at android.app.Activity.performCreate(Activity.java:7183)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2910)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
            at android.app.ActivityThread.-wrap11(Unknown Source:0)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
            at android.os.Handler.dispatchMessage(Handler.java:105)
            at android.os.Looper.loop(Looper.java:164)
            at android.app.ActivityThread.main(ActivityThread.java:6944)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

Body:
voiceBtn = (Button) findViewById(R.id.goToVoice);

replace the statement in your onCreate() method with the above. It should work.

and use

super.finish() instead of finish()


问:
Running dotnet command line within Visual Studio
The majority of .NET core tutorials online seem to use Visual Studio code, rather than Visual Studio (Full fat? Is there a proper term for the full version? I use Professional but there is also Community, Enterprise etc).

These tutorials make the most of the integrated terminal within VS code for running dotnet command line commands (dotnet new, dotnet build etc).

I am struggling to find where to execute these commands in Visual Studio. Where is the right place to do this? I have .NET core SDK installed.

I have seen some suggestions for the package manager console - although this seems odd, why should I be running dotnet commands via a "package manager console"?

答:
While following a tutorial to update database, I had to run these commands

dotnet ef migrations add MaxLengthOnNames
dotnet ef database update

in the command window of Visual studio, as per tutorial. When I opened this window in visual studio (View > Other Windows > Command Window) and attempted to run these commands, I received this error:

```<code>>dotnet ef migrations add MaxLengthOnNames
Command "dotnet" is not valid.
>dotnet ef database update
Command "dotnet" is not valid.
>
</code>```

When I attempted to run them in Package Manager Console, this is the result I got:

No project was found. Change the current working directory or use the --project option.

Now, I googled it a bit and got the hint that I must run these commands in windows command prompt (opened by typing "cmd" in Windows start search). Steps are:

Open windows command prompt

Set your project directory as current directory

run any dotnet command you need like I entered this: dotnet ef database update

success

Body:
While following a tutorial to update database, I had to run these commands

dotnet ef migrations add MaxLengthOnNames
dotnet ef database update

in the command window of Visual studio, as per tutorial. When I opened this window in visual studio (View > Other Windows > Command Window) and attempted to run these commands, I received this error:

>dotnet ef migrations add MaxLengthOnNames
Command "dotnet" is not valid.
>dotnet ef database update
Command "dotnet" is not valid.
>

When I attempted to run them in Package Manager Console, this is the result I got:

No project was found. Change the current working directory or use the --project option.

Now, I googled it a bit and got the hint that I must run these commands in windows command prompt (opened by typing "cmd" in Windows start search). Steps are:

Open windows command prompt

Set your project directory as current directory

run any dotnet command you need like I entered this: dotnet ef database update

success


问:
How to use TextClassificationManager to Detect language
TextClassificationManager is available from API-26. Its public methods available for classify text .
My requirement is i need to detect language from a giver Text offline.
 TextClassificationManager  also have detectLanguages() method but its hidden.
Can i Use TextClassificationManager to detect language ?

I have searched a bit and i Found This Project Using TextClassificationManager by Reflection. But it throws NoSuchMethodErrror and Returns ..
So if anyone Used TextClassificationManager for this purpose can help me .

答:
It's a bad decision to use hidden functions via reflection. You can never know if the function will be there and available so you have to prepare a fallback mechanism. </p>

<p>For Android SDK 26-27 You can try and use this Android lib project - https://github.com/rmtheis/language-detection but be aware that it's no longer maintained so use it for your own research but it's probably not a good idea to use it for production or apps released in Google Play. </p>

Body:
It's a bad decision to use hidden functions via reflection. You can never know if the function will be there and available so you have to prepare a fallback mechanism.

For Android SDK 26-27 You can try and use this Android lib project - https://github.com/rmtheis/language-detection but be aware that it's no longer maintained so use it for your own research but it's probably not a good idea to use it for production or apps released in Google Play.