问:
Button submit in ASP.NET MVC
I'm moving from php to asp.net. I created a simple page with a dropdown, a textarea (tinyMCE), and a button to save the text into the database. The save button opens a bootstrap modal to enter the name of the form that I want to save.

```<code>@model FormsCreator.Models.ModelView.ListFormsCreator
@{
    Layout = "";
}

<html>
<head>
    <script src="~/Scripts/jquery-3.2.1.min.js"></script>
    <script src="~/Scripts/tinymce/tinymce.min.js"></script>
    <script src="~/Scripts/JS/formsCreator.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
    <form>
        <br/><br />
        <div class="form-group col-sm-3">
            @Html.DropDownListFor(m => m.Forms, new SelectList(Model.Forms, "FormsCreatorID", "FormName"),
                "Select a Form", new { @class = "form-control" })
        </div>
        <br/><br/>
        <div class="form-group col-sm-12">
            <textarea class="form-control" id="mytextarea" name="mytextarea">Next, start a free trial!</textarea>
        </div>
        <div class="form-group col-sm-12">
            <button id="btnSaveForms" align="center" type="button" class="btn btn-primary" onclick="openModal();">Save</button>
        </div>
    </form>
    <div class="modal fade" id="saveForm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button aria-hidden="true" data-dismiss="modal" class="close" type="button">X</button>
                </div>
                <div class="modal-body">
                    <input type="text" id="formName" name="formName" required />
                </div>
                <div class="modal-footer">
                    <button data-dismiss="modal" class="btn btn-success" type="button" onclick="location.href='@Url.Action("SaveForm", "FormsCreator")'">Save</button>
                    <button data-dismiss="modal" class="btn btn-primary" type="button">Close</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        function openModal() {
            $("#saveForm").modal();
        }
    </script>
</body>
</html>
</code>```

Everything works fine, but how can I get in my Controller SaveForm the value of mytextarea and formName from the view? So, I can save it into the database. BTW, I'm probably doing it in the wrong way, so please if there is a better way let me know.

Controler:

```<code>public ActionResult SaveFormPrintable(){
    return View();
}
</code>```

Thanks

答:
Your current save button inside the modal has this code

```<code>onclick="location.href='@Url.Action("SaveForm", "FormsCreator")'"
</code>```

So when user clicks on the button, it will executed the code window.location.href='/FormsCreator/SaveForm;, which does a GET call (redirect to that url.

What you need is a form submit. You can keep the input for the form name inside the form as a hidden input element along with the Forms dropdown and your textarea. Have another textbox inside the modal dialog to read the form name from the user and when user clicks on the save button, read the value of that textbox and update the formname hidden input element inside our actual form, which has an action attribute set to your HttpPost action method.

```<code><form action="@Url.Action("SaveForm", "FormsCreator")" method="post">
    <textarea class="form-control" id="mytextarea"
              name="mytextarea">Next, start a free trial!</textarea>
    <input type="hidden" id="formName" name="formName" required />
   <button  type="button" class="btn btn-primary" onclick="openModal();">Save</button>
</form>
<div class="modal fade" id="saveForm" tabindex="-1" role="dialog"
                                      aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button aria-hidden="true" data-dismiss="modal" class="close"
                                           type="button">X</button>
            </div>
            <div class="modal-body">
                <input type="text" id="formNameTemp"  required />
            </div>
            <div class="modal-footer">
                <button data-dismiss="modal" class="btn" id="btn-save"
                                             type="button">Save</button>
                <button data-dismiss="modal" class="btn" type="button">Close</button>
            </div>
        </div>
    </div>
</div>
</code>```

And have the javscript code, which listen to the click event on the save button on the modal dialog, read the value and set to the hidden input inside our form and fire the form submit event.

```<code>$(document).ready(function () {

    $("#btn-save").click(function(e) {
        //Read the value from input in modal dialog
        var v = $("#formNameTemp").val();
        // Set the value to the hidden input in form and submit the form
        $("#formName").val(v).closest("form").submit();
    });

});
</code>```

Now since the form will be submitted to the Save Form action method, you can use the same view model as your method parameter.

```<code>[HttpPost]
public ActionResult SaveForm(YourFormContentViewModel model)
{
  // to do : return something
}
</code>```

Now this is doing a normal form submit, you can  update it to do an ajax post if needed. There are tons of examples on stack overflow explaining how to do that.

Title: Button submit in ASP.NET MVC

Body:
I'm moving from php to asp.net. I created a simple page with a dropdown, a textarea (tinyMCE), and a button to save the text into the database. The save button opens a bootstrap modal to enter the name of the form that I want to save.

@model FormsCreator.Models.ModelView.ListFormsCreator
@{
    Layout = "";
}

    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />

    <form>

            @Html.DropDownListFor(m => m.Forms, new SelectList(Model.Forms, "FormsCreatorID", "FormName"),
                "Select a Form", new { @class = "form-control" })

            <textarea class="form-control" id="mytextarea" name="mytextarea">Next, start a free trial!</textarea>

            <button id="btnSaveForms" align="center" type="button" class="btn btn-primary" onclick="openModal();">Save</button>

    </form>

                    <button aria-hidden="true" data-dismiss="modal" class="close" type="button">X</button>

                    <input type="text" id="formName" name="formName" required />

                    <button data-dismiss="modal" class="btn btn-success" type="button" onclick="location.href='@Url.Action("SaveForm", "FormsCreator")'">Save</button>
                    <button data-dismiss="modal" class="btn btn-primary" type="button">Close</button>

Everything works fine, but how can I get in my Controller SaveForm the value of mytextarea and formName from the view? So, I can save it into the database. BTW, I'm probably doing it in the wrong way, so please if there is a better way let me know.

Controler:

public ActionResult SaveFormPrintable(){
    return View();
}

Thanks

Body:
Your current save button inside the modal has this code

onclick="location.href='@Url.Action("SaveForm", "FormsCreator")'"

So when user clicks on the button, it will executed the code window.location.href='/FormsCreator/SaveForm;, which does a GET call (redirect to that url.

What you need is a form submit. You can keep the input for the form name inside the form as a hidden input element along with the Forms dropdown and your textarea. Have another textbox inside the modal dialog to read the form name from the user and when user clicks on the save button, read the value of that textbox and update the formname hidden input element inside our actual form, which has an action attribute set to your HttpPost action method.

<form action="@Url.Action("SaveForm", "FormsCreator")" method="post">
    <textarea class="form-control" id="mytextarea"
              name="mytextarea">Next, start a free trial!</textarea>
    <input type="hidden" id="formName" name="formName" required />
   <button  type="button" class="btn btn-primary" onclick="openModal();">Save</button>
</form>
<div class="modal fade" id="saveForm" tabindex="-1" role="dialog"
                                      aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button aria-hidden="true" data-dismiss="modal" class="close"
                                           type="button">X</button>
            </div>
            <div class="modal-body">
                <input type="text" id="formNameTemp"  required />
            </div>
            <div class="modal-footer">
                <button data-dismiss="modal" class="btn" id="btn-save"
                                             type="button">Save</button>
                <button data-dismiss="modal" class="btn" type="button">Close</button>
            </div>
        </div>
    </div>
</div>

And have the javscript code, which listen to the click event on the save button on the modal dialog, read the value and set to the hidden input inside our form and fire the form submit event.

$(document).ready(function () {

    $("#btn-save").click(function(e) {
        //Read the value from input in modal dialog
        var v = $("#formNameTemp").val();
        // Set the value to the hidden input in form and submit the form
        $("#formName").val(v).closest("form").submit();
    });

});

Now since the form will be submitted to the Save Form action method, you can use the same view model as your method parameter.

[HttpPost]
public ActionResult SaveForm(YourFormContentViewModel model)
{
  // to do : return something
}

Now this is doing a normal form submit, you can  update it to do an ajax post if needed. There are tons of examples on stack overflow explaining how to do that.

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
Direct download Sql database azure portal data into excel sheet?
I want to download Azure Portal sql data into excel sheet without using sqlserver.
Is this Possible ?
Data for security checks under Vulnerability Assessment (Preview),

See Sample Data :-
https://learn.microsoft.com/en-us/azure/sql-database/sql-vulnerability-assessment

答: You will need to use a SQL tool to download data from a SQL database into Excel. You have several options. The first one is to run a query in SQL Server Management Studio and copy paste the result into Excel. Another option is to use the bcp utility with Unicode encoding (option -w).</p>

ContentLicense: CC BY-SA 3.0


问:
I want to create a program that returns a list that contains only the elements that are common between the lists (without duplicates)
Below is the code:

```<code>a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
c = []

cal = len(a)

for d in range(cal):
     if a[d] in b and a[d] not in c:
         c.append(a[d])
print(c)
</code>```

Below is the output:

[1, 2, 3, 5, 8, 13]

Process finished with exit code 0

I was not able to make the logic myself so I had looked at the solution but still didn't get the concept behind the code. The point where I am getting confused is that in cal I am storing the length of a which is 11, then I am doing a for loop 11 times(I am not sure why this is being done and what will we get from this part), then then finally conditional using "a[d]". It just doesnt makes sense to me.

Body:
Below is the code:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
c = []

cal = len(a)

for d in range(cal):
     if a[d] in b and a[d] not in c:
         c.append(a[d])
print(c)

Below is the output:

[1, 2, 3, 5, 8, 13]

Process finished with exit code 0

I was not able to make the logic myself so I had looked at the solution but still didn't get the concept behind the code. The point where I am getting confused is that in cal I am storing the length of a which is 11, then I am doing a for loop 11 times(I am not sure why this is being done and what will we get from this part), then then finally conditional using "a[d]". It just doesnt makes sense to me.

Body:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
c = [x for x in set(a) if x in set(b)]
print c

Output:

[1, 2, 3, 5, 8, 13]


问:
Rxjava2 just method - how to run room insertion on another thread?
I have a room persistant database insertion method which looks like this:

```<code>@Dao
public interface CountriesDao{

    @Insert(onConflict = REPLACE)
    List<Long> addCountries(List<CountryModel> countryModel);
}
</code>```

I realize that this can't be run on the main thread. Here is how I define my database:

```<code>Room.inMemoryDatabaseBuilder(context.getApplicationContext(), MyDatabase.class).build();
</code>```

I am trying to use rxjava2 so that I don't run on main thread. I have created the following method:

```<code>public void storeCountries(List<CountryModel> countriesList) {
        Observable.just(db.countriesDao().addCountries(countriesList))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultSubscriber<List<Long>>(){
            @Override
            public void onSubscribe(@NonNull Disposable d) {
                super.onSubscribe(d);
            }

            @Override
            public void onNext(@NonNull List<Long> longs) {
                super.onNext(longs);
                Timber.d("insert countries transaction complete");
            }

            @Override
            public void onError(@NonNull Throwable e) {
                super.onError(e);
                Timber.d("error storing countries in db"+e);
            }

            @Override
            public void onComplete() {
                Timber.d("insert countries transaction complete");
            }
        });
    }
</code>```

For me this is clearly now running on another thread. NOT the main thread but when I run this code i get the following error:

The full stack trace is below. Why is this happening ?

Process: com.mobile.myapp.staging, PID: 12990

  java.lang.IllegalStateException: Fatal Exception thrown on Scheduler.
  Caused by: java.lang.IllegalStateException: Cannot access database on
  the main thread since it may potentially lock the UI for a long period
  of time.
                                                                                at
  io.reactivex.android.schedulers.HandlerScheduler$ScheduledRunnable.run(HandlerScheduler.java:111)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
                                                                                Caused by: java.lang.IllegalStateException: Cannot access database on
  the main thread since it may potentially lock the UI for a long period
  of time.
                                                                                at
  android.arch.persistence.room.RoomDatabase.assertNotMainThread(RoomDatabase.java:138)
                                                                                at
  android.arch.persistence.room.RoomDatabase.beginTransaction(RoomDatabase.java:185)
                                                                                at
  com.mobile.myapp.data.room.dao.CountriesDao_Impl.addCountries(CountriesDao_Impl.java:165)
                                                                                at
  com.mobile.myapp.data.repositories.CountryRepository.storeCountries(CountryRepository.java:42)
                                                                                at
  com.mobile.myapp.UI.mvp.Presenters.SignUpPresenter.cacheCountries(SignUpPresenter.java:40)
                                                                                at
  com.mobile.myapp.UI.mvp.Presenters.SignUpPresenter$CountriesSubscriber.onNext(SignUpPresenter.java:60)
                                                                                at
  com.mobile.myapp.UI.mvp.Presenters.SignUpPresenter$CountriesSubscriber.onNext(SignUpPresenter.java:49)
                                                                                at
  io.reactivex.internal.operators.observable.ObservableObserveOn$ObserveOnObserver.drainNormal(ObservableObserveOn.java:200)
                                                                                at
  io.reactivex.internal.operators.observable.ObservableObserveOn$ObserveOnObserver.run(ObservableObserveOn.java:252)
                                                                                at
  io.reactivex.android.schedulers.HandlerScheduler$ScheduledRunnable.run(HandlerScheduler.java:109)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)

Not important but if you need to know what defaultSubscriber class looks like here it is:

DefaultSubscriber.java

```<code>public class DefaultSubscriber<T> implements Observer<T> {

Disposable disposable;

@Override
public void onSubscribe(@NonNull Disposable d) {
    disposable = d;
}

@Override
public void onNext(@NonNull T t) {

}

@Override
public void onError(@NonNull Throwable e) {
    Timber.e(e);
}

@Override
public void onComplete() {

}

public void unsubscribe(){
    if(disposable!=null && !disposable.isDisposed()){
        disposable.dispose();
    }
  }
}
</code>```

答:
You can also use the Single observable</p>

```<code>        Single.create(new SingleOnSubscribe<List<Long>>() {
        @Override
        public void subscribe(SingleEmitter<List<Long>> emitter) throws Exception {
            try {
                List<Long> ids = db.countriesDao().addCountries(countriesList);
                emitter.onSuccess(ids);
            } catch (Throwable t) {
                emitter.onError(t);
            }
        }})
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeOn(Schedulers.io())
    .subscribeWith(new DisposableSingleObserver<Long>() {
        @Override
        public void onSuccess(List<Long> ids) {

        }

        @Override
        public void onError(Throwable e) {

        }
});
</code>```

Body:
I have a room persistant database insertion method which looks like this:

@Dao
public interface CountriesDao{

    @Insert(onConflict = REPLACE)
    List<Long> addCountries(List<CountryModel> countryModel);
}

I realize that this can't be run on the main thread. Here is how I define my database:

Room.inMemoryDatabaseBuilder(context.getApplicationContext(), MyDatabase.class).build();

I am trying to use rxjava2 so that I don't run on main thread. I have created the following method:

public void storeCountries(List<CountryModel> countriesList) {
        Observable.just(db.countriesDao().addCountries(countriesList))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultSubscriber<List<Long>>(){
            @Override
            public void onSubscribe(@NonNull Disposable d) {
                super.onSubscribe(d);
            }

            @Override
            public void onNext(@NonNull List<Long> longs) {
                super.onNext(longs);
                Timber.d("insert countries transaction complete");
            }

            @Override
            public void onError(@NonNull Throwable e) {
                super.onError(e);
                Timber.d("error storing countries in db"+e);
            }

            @Override
            public void onComplete() {
                Timber.d("insert countries transaction complete");
            }
        });
    }

For me this is clearly now running on another thread. NOT the main thread but when I run this code i get the following error:

The full stack trace is below. Why is this happening ?

Process: com.mobile.myapp.staging, PID: 12990

  java.lang.IllegalStateException: Fatal Exception thrown on Scheduler.
  Caused by: java.lang.IllegalStateException: Cannot access database on
  the main thread since it may potentially lock the UI for a long period
  of time.
                                                                                at
  io.reactivex.android.schedulers.HandlerScheduler$ScheduledRunnable.run(HandlerScheduler.java:111)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
                                                                                Caused by: java.lang.IllegalStateException: Cannot access database on
  the main thread since it may potentially lock the UI for a long period
  of time.
                                                                                at
  android.arch.persistence.room.RoomDatabase.assertNotMainThread(RoomDatabase.java:138)
                                                                                at
  android.arch.persistence.room.RoomDatabase.beginTransaction(RoomDatabase.java:185)
                                                                                at
  com.mobile.myapp.data.room.dao.CountriesDao_Impl.addCountries(CountriesDao_Impl.java:165)
                                                                                at
  com.mobile.myapp.data.repositories.CountryRepository.storeCountries(CountryRepository.java:42)
                                                                                at
  com.mobile.myapp.UI.mvp.Presenters.SignUpPresenter.cacheCountries(SignUpPresenter.java:40)
                                                                                at
  com.mobile.myapp.UI.mvp.Presenters.SignUpPresenter$CountriesSubscriber.onNext(SignUpPresenter.java:60)
                                                                                at
  com.mobile.myapp.UI.mvp.Presenters.SignUpPresenter$CountriesSubscriber.onNext(SignUpPresenter.java:49)
                                                                                at
  io.reactivex.internal.operators.observable.ObservableObserveOn$ObserveOnObserver.drainNormal(ObservableObserveOn.java:200)
                                                                                at
  io.reactivex.internal.operators.observable.ObservableObserveOn$ObserveOnObserver.run(ObservableObserveOn.java:252)
                                                                                at
  io.reactivex.android.schedulers.HandlerScheduler$ScheduledRunnable.run(HandlerScheduler.java:109)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)

Not important but if you need to know what defaultSubscriber class looks like here it is:

DefaultSubscriber.java

public class DefaultSubscriber<T> implements Observer<T> {

Disposable disposable;

@Override
public void onSubscribe(@NonNull Disposable d) {
    disposable = d;
}

@Override
public void onNext(@NonNull T t) {

}

@Override
public void onError(@NonNull Throwable e) {
    Timber.e(e);
}

@Override
public void onComplete() {

}

public void unsubscribe(){
    if(disposable!=null && !disposable.isDisposed()){
        disposable.dispose();
    }
  }
}

Body:
You can also use the Single observable

        Single.create(new SingleOnSubscribe<List<Long>>() {
        @Override
        public void subscribe(SingleEmitter<List<Long>> emitter) throws Exception {
            try {
                List<Long> ids = db.countriesDao().addCountries(countriesList);
                emitter.onSuccess(ids);
            } catch (Throwable t) {
                emitter.onError(t);
            }
        }})
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeOn(Schedulers.io())
    .subscribeWith(new DisposableSingleObserver<Long>() {
        @Override
        public void onSuccess(List<Long> ids) {

        }

        @Override
        public void onError(Throwable e) {

        }
});


问:
most frequent character in 2d array with pointer
i want to find the most frequent character for 5 strings,i thought of this ,i have done it for a specific character,in my ocasion s ,but how can i make it for every character,its only part of my code

Ch is a pointer!!!

```<code>for(i = 0; i < five; i++){
    ch = strchr(cities[i], 's');

    if (ch != NULL){ //if this is true
        ch1++;
        printf("exists in %s\n", cities[i]); //print
    }
    else
    {
        printf ("doesnt exist in %s\n", cities[i]); //print
    }
}
printf("The character 's' appears in %d cities\n", ch1);
</code>```

答:
You have to somehow store the number of occurences for each character somewhere.

With that given a hint would be to keep one variable with storing the max occurence of the character and the character itself. Nothing else. And for looping you need to consider all characters from a to z.

The code will be something like:-(Only look if you feel you have tried enough).

To make you aware of what this code does - it counts the character which occurs in maximum number of cities. In case there is a tie, it selects the smaller alphabet first (lexicographically).

```<code>for( char c = 'a'; c <= 'z';c++){
    int ch1 = 0, mxch1 = 0;
    char mch='?';
    for(i = 0; i < numOfCities; i++){
      ch=strchr(cities[i],c);
        if( ch ){
           printf("Exist in %s\n",cities[i]);
           ch1++;
        }
        else
           printf("Doesn't Exist in %s\n",cities[i]);
    }
    if( ch1 > mch1) {
      mch1 = ch1;
      mch = c;
  }
    printf("The character %c appears in %d cities\n",c,ch1);
}
printf("Character which occured in max number of cities is %c %d",mch,mch1);```

The code for most frequent character will be a bit different.

```<code>int charMap[26]={0};
for(size_t i = 0; i < numOfCities; i++){
  for(size_t j = 0; cities[i][j]; j++)
      charMap[cities[i][j]-'a']++;
}
int mx = 0;
mxi = 0;
for(size_t i = 0; i < sizeof(charMap)/sizeof(charMap[0]); i++){
  if(charMap[i]>mx){
      mx  = charMap[i];
      mxi = i;
  }

printf("Character which occured max number of times is %c %d", (char)(mxi+'a'),mx);```

Body:
i want to find the most frequent character for 5 strings,i thought of this ,i have done it for a specific character,in my ocasion s ,but how can i make it for every character,its only part of my code

Ch is a pointer!!!

for(i = 0; i < five; i++){
    ch = strchr(cities[i], 's');

    if (ch != NULL){ //if this is true
        ch1++;
        printf("exists in %s\n", cities[i]); //print
    }
    else
    {
        printf ("doesnt exist in %s\n", cities[i]); //print
    }
}
printf("The character 's' appears in %d cities\n", ch1);

Body:
You have to somehow store the number of occurences for each character somewhere.

With that given a hint would be to keep one variable with storing the max occurence of the character and the character itself. Nothing else. And for looping you need to consider all characters from a to z.

The code will be something like:-(Only look if you feel you have tried enough).

To make you aware of what this code does - it counts the character which occurs in maximum number of cities. In case there is a tie, it selects the smaller alphabet first (lexicographically).

for( char c = 'a'; c <= 'z';c++){
    int ch1 = 0, mxch1 = 0;
    char mch='?';
    for(i = 0; i < numOfCities; i++){
      ch=strchr(cities[i],c);
        if( ch ){
           printf("Exist in %s\n",cities[i]);
           ch1++;
        }
        else
           printf("Doesn't Exist in %s\n",cities[i]);
    }
    if( ch1 > mch1) {
      mch1 = ch1;
      mch = c;
  }
    printf("The character %c appears in %d cities\n",c,ch1);
}
printf("Character which occured in max number of cities is %c %d",mch,mch1);

The code for most frequent character will be a bit different.

int charMap[26]={0};
for(size_t i = 0; i < numOfCities; i++){
  for(size_t j = 0; cities[i][j]; j++)
      charMap[cities[i][j]-'a']++;
}
int mx = 0;
mxi = 0;
for(size_t i = 0; i < sizeof(charMap)/sizeof(charMap[0]); i++){
  if(charMap[i]>mx){
      mx  = charMap[i];
      mxi = i;
  }

printf("Character which occured max number of times is %c %d", (char)(mxi+'a'),mx);


问:
How to center HTML code while using Bootstrap
Part of my code sticks to the left side of the page. I can not figure out a way to put these buttons in the middle of the website. Just trying to make look better if I add center or text block center it does not work it only ads the radio button symbol above the text or it shifts just the symbol to the middle.

```<code>    <div class="jumbotron">
    <h1 class="jumbotron-heading"><center>Bazár Bez Havárie</center></h1>
    <p class="lead text-muted"><center>Vitajte v Bazáry Bez Havárie. Vyberte
    si svoje auto.</center></p><br>
    <h2 class="jumbotron-heading"><center><b>Objednávkový formulár.</b>
    </center></h1><br>
    <form class="form-horizontal" role="form" method="get"
    action="objednavka.php">
    <div class="form-group">
    <label for="name" class="col-sm-2 control-label"><center>Meno</center>
    </label>
    <div class="col-sm-12">
    <input type="text" class="form-control" id="name" name="name"
    placeholder="" value="">
    </div>
    </div>
    <div class="form-group">
    <label for="email" class="col-sm-2 control-label"><center>Email</center>
    </label>
    <div class="col-sm-12">
    <input type="email" class="form-control" id="email" name="email"
    placeholder="" value="">
    </div>
    </div>
    <div class="form-group">
    <label for="adress" class="col-sm-2 control-label">
    <center>Adresa</center></label>
    <div class="col-sm-12">
    <input type="adress" class="form-control" id="address" name="address"
    placeholder="" value="">
    </div>
    </div>

    <h2><b>Auto na vyber</b></h2><br>

   <div class="btn-group" data-toggle="buttons">

   <label class="btn btn-light">
   <input type="radio" name="options" id="option1" value="Ferrari GTC4Lusso"
   autocomplete="off"><center> Ferrari GTC4Lusso </center>
   </label>

   <label class="btn btn-light">
   <input type="radio" name="options" id="option2" value="Porsche Carrera
   GT" autocomplete="off"> <center>Porsche Carrera GT </center>
   </label>

   </div>
   <br><br>
   <h2><b>Farba auta</b></h2><br> <div class="btn-group" data-
   toggle="buttons">
</code>```

Here in the middle

```<code>   <label class="btn btn-sample">
   <label class="btn btn-cierna btn-lg btn-lg">
   <input type="radio" name="tlacidla" id="tlacidla2" value="Čierna"
   autocomplete="off"><center> Čierna </center>
   </label>
   <label class="btn btn-cervena btn-lg btn-lg">
   <input type="radio" name="tlacidla" id="tlacidla3" value="Červená"
    autocomplete="off"><center> Červená </center>
</code>```

Ends here

```<code>   </label>
   </div><br><br>
   <div class="form-group">
</code>```

And this one below too.

```<code>   <input type="submit" name="submit"  value="Potvrdit Objednavku"
    class="btn btn-outline-danger">
    </div>
   </form>
   </div>
</code>```

答:
Just add class text-center to it like</p>

```<code><div class="text-
center ">
<label class="btn btn-
light ">
<input type="radio"
name ="options"
id ="option1"
value ="Ferrari
GTC4Lusso "
autocomplete="off">.
<center> Ferrari GTC4Lusso </center>
</label>
</div>
</code>```

Body:
Part of my code sticks to the left side of the page. I can not figure out a way to put these buttons in the middle of the website. Just trying to make look better if I add center or text block center it does not work it only ads the radio button symbol above the text or it shifts just the symbol to the middle.

Bazár Bez Havárie

Vitajte v Bazáry Bez Havárie. Vyberte
    si svoje auto.

Objednávkový formulár.

    <form class="form-horizontal" role="form" method="get"
    action="objednavka.php">

    Meno

    <input type="text" class="form-control" id="name" name="name"
    placeholder="" value="">

    Email

    <input type="email" class="form-control" id="email" name="email"
    placeholder="" value="">

    Adresa

    <input type="adress" class="form-control" id="address" name="address"
    placeholder="" value="">

Auto na vyber

   <input type="radio" name="options" id="option1" value="Ferrari GTC4Lusso"
   autocomplete="off"> Ferrari GTC4Lusso

   <input type="radio" name="options" id="option2" value="Porsche Carrera
   GT" autocomplete="off"> Porsche Carrera GT

Farba auta

Here in the middle

   <input type="radio" name="tlacidla" id="tlacidla2" value="Čierna"
   autocomplete="off"> Čierna

   <input type="radio" name="tlacidla" id="tlacidla3" value="Červená"
    autocomplete="off"> Červená

Ends here

And this one below too.

   <input type="submit" name="submit"  value="Potvrdit Objednavku"
    class="btn btn-outline-danger">

   </form>

Body:
Just add class text-center to it like

<div class="text-
center ">
<label class="btn btn-
light ">
<input type="radio"
name ="options"
id ="option1"
value ="Ferrari
GTC4Lusso "
autocomplete="off">.
<center> Ferrari GTC4Lusso </center>
</label>
</div>


问:
Keep focus on child form without dialog?
I have a borderless form displayed as a progress object. This is displayed via childform.show().

I'm overriding CS_DROPSHADOW to give it the shadow (pictured),
when the form loses focus (parent clicked or another form\application) the shadow is lost.

How can I keep the form focused\selected similar to a modal form? (I cannot use showdialog due this being called from various threads other than UI) Using Me.TopMost = True works, but obviously puts the form above all others rather than just the parent.

答:
As long as you are creating this window in a worker thread then you really are stuck with TopMost = true.  Winforms won't let you use the Show(owner) overload, it throws an InvalidOperationException when it detects that the parent is owned by the UI thread.  Just calling Show() makes the desktop window the owner.  Which is a problem, the progress window can disappear behind another window and the user can't easily get it back.  Since it is asynchronous, this can easily happen while the user is working in a UI window, she might never even notice the popup.

Just punt this problem, use Control.BeginInvoke() to let a method create the dialog on the UI thread.  Now you can call ShowDialog(), all your problems are solved.

ContentLicense: CC BY-SA 2.5


问:
Handling header dependencies with cmake
Let's say I have main.cpp, a.h and b.h in the same folder. main.cpp includes a.h, and a.h includes b.h.

Checking the generated depends.make file, main.cpp.o depends both on a.h and b.h, as expected.

If b.h is moved to a folder B, and used the -iquote B flag, main.cpp.o does not depend any more on b.h.

I can put back the dependency by adding include_directories(${CMAKE_SOURCE_DIR}/B) to the CMakeLists.txt file. This however has a side effect: when compiling main.cpp, cmake uses the flag -I/pathTo/B. I prefer using -iquote instead of -I.

Is there a way in this second case to let cmake to detect the dependencies automatically without introducing the -I compiler flag?

答:
You might find this SO answer helpful: https://stackoverflow.com/a/9899919/5820799

It boils down to not use include_directories(${CMAKE_SOURCE_DIR}/B), but to manually add the -iquote directive instead:

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -iquote ${CMAKE_SOURCE_DIR}/B")

This will generate -iquote <path> instead of -I <path>.
It is not pretty, but does the job. :-)

Title: Handling header dependencies with cmake


问:
Can Objective-C switch on NSString?
Is there a more intelligent way to rewrite this?</p>

```<code>if ([cardName isEqualToString:@"Six"]) {
    [self setValue:6];
} else if ([cardName isEqualToString:@"Seven"]) {
    [self setValue:7];
} else if ([cardName isEqualToString:@"Eight"]) {
    [self setValue:8];
} else if ([cardName isEqualToString:@"Nine"]) {
    [self setValue:9];
}
</code>```

答:
Building on @Graham Perks idea posted earlier, designed a simple class to make switching on strings fairly simple and clean.

```<code>@interface Switcher : NSObject

+ (void)switchOnString:(NSString *)tString
                 using:(NSDictionary<NSString *, CaseBlock> *)tCases
           withDefault:(CaseBlock)tDefaultBlock;

@end

@implementation Switcher

+ (void)switchOnString:(NSString *)tString
                 using:(NSDictionary<NSString *, CaseBlock> *)tCases
           withDefault:(CaseBlock)tDefaultBlock
{
    CaseBlock blockToExecute = tCases[tString];
    if (blockToExecute) {
        blockToExecute();
    } else {
        tDefaultBlock();
    }
}

@end
</code>```

You would use it like this:

```<code>[Switcher switchOnString:someString
                   using:@{
                               @"Spades":
                               ^{
                                   NSLog(@"Spades block");
                               },
                               @"Hearts":
                               ^{
                                   NSLog(@"Hearts block");
                               },
                               @"Clubs":
                               ^{
                                   NSLog(@"Clubs block");
                               },
                               @"Diamonds":
                               ^{
                                   NSLog(@"Diamonds block");
                               }
                           } withDefault:
                               ^{
                                   NSLog(@"Default block");
                               }
 ];
</code>```

The correct block will execute according to the string.

Gist for this solution

Title: Can Objective-C switch on NSString?

Body:
Is there a more intelligent way to rewrite this?

if ([cardName isEqualToString:@"Six"]) {
    [self setValue:6];
} else if ([cardName isEqualToString:@"Seven"]) {
    [self setValue:7];
} else if ([cardName isEqualToString:@"Eight"]) {
    [self setValue:8];
} else if ([cardName isEqualToString:@"Nine"]) {
    [self setValue:9];
}

Body:
Building on @Graham Perks idea posted earlier, designed a simple class to make switching on strings fairly simple and clean.

@interface Switcher : NSObject

+ (void)switchOnString:(NSString *)tString
                 using:(NSDictionary<NSString *, CaseBlock> *)tCases
           withDefault:(CaseBlock)tDefaultBlock;

@end

@implementation Switcher

+ (void)switchOnString:(NSString *)tString
                 using:(NSDictionary<NSString *, CaseBlock> *)tCases
           withDefault:(CaseBlock)tDefaultBlock
{
    CaseBlock blockToExecute = tCases[tString];
    if (blockToExecute) {
        blockToExecute();
    } else {
        tDefaultBlock();
    }
}

@end

You would use it like this:

[Switcher switchOnString:someString
                   using:@{
                               @"Spades":
                               ^{
                                   NSLog(@"Spades block");
                               },
                               @"Hearts":
                               ^{
                                   NSLog(@"Hearts block");
                               },
                               @"Clubs":
                               ^{
                                   NSLog(@"Clubs block");
                               },
                               @"Diamonds":
                               ^{
                                   NSLog(@"Diamonds block");
                               }
                           } withDefault:
                               ^{
                                   NSLog(@"Default block");
                               }
 ];

The correct block will execute according to the string.

Gist for this solution


答:
Firstly this code is logically incorrect if you plan on perhaps changing these lists.

```<code>a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
c = []

cal = min(len(a),len(b))

for d in range(cal):
     if a[d] in b and a[d] not in c:
         c.append(a[d])
print(c)
</code>```

We are checking in the for loop that the element at index d, which takes on every value from 0 to 11, if the element at a[d], which is the dth element in a, is also in b. If it is in b, and already has not been added to the list c, then we add it.

One can do this in many syntactically better ways:

```<code>c = list(set([d for a in d if d in b]))
</code>```

or

```<code>c = filter(set(a).__contains__, b)
</code>```

or

```<code>c = list(set(a).union(b))
</code>```

Title: I want to create a program that returns a list that contains only the elements that are common between the lists (without duplicates)

Body:
Firstly this code is logically incorrect if you plan on perhaps changing these lists.

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
c = []

cal = min(len(a),len(b))

for d in range(cal):
     if a[d] in b and a[d] not in c:
         c.append(a[d])
print(c)

We are checking in the for loop that the element at index d, which takes on every value from 0 to 11, if the element at a[d], which is the dth element in a, is also in b. If it is in b, and already has not been added to the list c, then we add it.

One can do this in many syntactically better ways:

c = list(set([d for a in d if d in b]))

or

c = filter(set(a).__contains__, b)

or

c = list(set(a).union(b))


问:
Sorting in Swift fails
I want to sort my Dictionary itemDictionary which I defined as:

```<code>var itemDictionary  = [String: [Items]]()
itemDictionary = itemDictionary.sorted { $0.0 < $1.0 }
</code>```

But then I'm getting following error code:

Cannot assign value of type '[(key: String, value: [Items])]' to type '[String : [Items]]'

Does anyone have an idea why this might be?

答:
Dictionary is unordered by definition. You can only call sorted on it, because since Swift 4, Dictionary conforms to Collection,but due to the unordered nature of the Dictionary type, the return value of calling sorted on a Dictionary will be Array<(key: Key,value: Value)>, so an array of tuples, where the tuples contain the key-value pairs.

If you need a sorted data-structure, you should consider using a data structure that can actually be ordered.

Title: Sorting in Swift fails

Body:
I want to sort my Dictionary itemDictionary which I defined as:

var itemDictionary  = [String: [Items]]()
itemDictionary = itemDictionary.sorted { $0.0 < $1.0 }

But then I'm getting following error code:

Cannot assign value of type '[(key: String, value: [Items])]' to type '[String : [Items]]'

Does anyone have an idea why this might be?


问:
How to add and get Header values in WebApi
I need to create a POST method in WebApi so I can send data from application to WebApi method. I'm not able to get header value.

Here I have added header values in the application:

```<code>using (var client = new WebClient())
{
    // Set the header so it knows we are sending JSON.
    client.Headers[HttpRequestHeader.ContentType] = "application/json";

    client.Headers.Add("Custom", "sample");
    // Make the request
    var response = client.UploadString(url, jsonObj);
}
</code>```

Following the WebApi post method:

```<code>public string Postsam([FromBody]object jsonData)
{
    HttpRequestMessage re = new HttpRequestMessage();
    var headers = re.Headers;

    if (headers.Contains("Custom"))
    {
       string token = headers.GetValues("Custom").First();
    }
}
</code>```

What is the correct method for getting header values?

Thanks.

答:
In case someone is using ASP.NET Core for model binding,

https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding

There's is built in support for retrieving values from the header using the [FromHeader] attribute

```<code>public string Test([FromHeader]string Host, [FromHeader]string Content-Type )
{
     return $"Host: {Host} Content-Type: {Content-Type}";
}
</code>```

Body:
I need to create a POST method in WebApi so I can send data from application to WebApi method. I'm not able to get header value.

Here I have added header values in the application:

using (var client = new WebClient())
{
    // Set the header so it knows we are sending JSON.
    client.Headers[HttpRequestHeader.ContentType] = "application/json";

    client.Headers.Add("Custom", "sample");
    // Make the request
    var response = client.UploadString(url, jsonObj);
}

Following the WebApi post method:

public string Postsam([FromBody]object jsonData)
{
    HttpRequestMessage re = new HttpRequestMessage();
    var headers = re.Headers;

    if (headers.Contains("Custom"))
    {
       string token = headers.GetValues("Custom").First();
    }
}

What is the correct method for getting header values?

Thanks.

Body:
In case someone is using ASP.NET Core for model binding,

https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding

There's is built in support for retrieving values from the header using the [FromHeader] attribute

public string Test([FromHeader]string Host, [FromHeader]string Content-Type )
{
     return $"Host: {Host} Content-Type: {Content-Type}";
}


问:
BeforeEach, Error: Can't set headers after they are sent
What´s wrong with this code?, it provoke two errors:

Error: Can't set headers after they are sent

TypeError: Cannot read property '_id' of undefined.

I think is because the chaining .then in BeforeEach, but I can't solve it, can somebody help?. Thanks.

```<code>const expect = require('expect');
const request = require('supertest');
const{ObjectID} = require('mongodb');

const {app} = require('./../server');
const {Todo} = require('./../models/todo');

if(!module.parent) {
app.listen();
}

const todos=[{
  _id:new ObjectID(),
  text:"2 test todo"
},
{
_id:new ObjectID(),
text:"1 test todo"
}];

beforeEach((done) => {
  Todo.remove({}).then(() => {
    return Todo.insertMany(todos);
  }).then(() => done());
});

describe('DELETE /todos/:id', () => {
  it('most delete a doc', (done) => {
    let hexId = todos[1]._id.toHexString();

    request(app)
    .delete(`/todos/${hexId}`)
    .expect(200)
    .expect((res) => {
        expect(res.body.todo._id).toBe(hexId);
    })
    .end((err, res) => {
        if(err) return done(err);

    Todo.findById(hexId).then((todo) => {
        expect(todo).toNotExist();
        done();
    }).catch((e) => done(e));

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

答:
Error: Can't set headers after they are sent

-> because callback (done) already called

TypeError: Cannot read property '_id' of undefined.

although i don't know typeError line number but aspect comment is in below code

```<code>beforeEach((done) => {
  Todo.remove({}).then(() => {
    return Todo.insertMany(todos);
  })
  .then(() =>{
    describe('DELETE /todos/:id', () => {
      it('most delete a doc', (done) => {
        let hexId = todos[1]._id.toHexString();

        request(app)
        .delete(`/todos/${hexId}`)
        .expect(200)
        .expect((res) => {
                // make sure you are you getting from req.body
            expect(res.body.todo._id).toBe(hexId);
        })
        .end((err, res) => {
            if(err) return done(err);

        Todo.findById(hexId).then((todo) => {
            expect(todo).toNotExist();
            done();
        }).catch((e) => done(e));

        });
      });
    });

});
</code>```

Body:
What´s wrong with this code?, it provoke two errors:

Error: Can't set headers after they are sent

TypeError: Cannot read property '_id' of undefined.

I think is because the chaining .then in BeforeEach, but I can't solve it, can somebody help?. Thanks.

const expect = require('expect');
const request = require('supertest');
const{ObjectID} = require('mongodb');

const {app} = require('./../server');
const {Todo} = require('./../models/todo');

if(!module.parent) {
app.listen();
}

const todos=[{
  _id:new ObjectID(),
  text:"2 test todo"
},
{
_id:new ObjectID(),
text:"1 test todo"
}];

beforeEach((done) => {
  Todo.remove({}).then(() => {
    return Todo.insertMany(todos);
  }).then(() => done());
});

describe('DELETE /todos/:id', () => {
  it('most delete a doc', (done) => {
    let hexId = todos[1]._id.toHexString();

    request(app)
    .delete(`/todos/${hexId}`)
    .expect(200)
    .expect((res) => {
        expect(res.body.todo._id).toBe(hexId);
    })
    .end((err, res) => {
        if(err) return done(err);

    Todo.findById(hexId).then((todo) => {
        expect(todo).toNotExist();
        done();
    }).catch((e) => done(e));

    });
  });
});

Body:
Error: Can't set headers after they are sent

-> because callback (done) already called

TypeError: Cannot read property '_id' of undefined.

although i don't know typeError line number but aspect comment is in below code

beforeEach((done) => {
  Todo.remove({}).then(() => {
    return Todo.insertMany(todos);
  })
  .then(() =>{
    describe('DELETE /todos/:id', () => {
      it('most delete a doc', (done) => {
        let hexId = todos[1]._id.toHexString();

        request(app)
        .delete(`/todos/${hexId}`)
        .expect(200)
        .expect((res) => {
                // make sure you are you getting from req.body
            expect(res.body.todo._id).toBe(hexId);
        })
        .end((err, res) => {
            if(err) return done(err);

        Todo.findById(hexId).then((todo) => {
            expect(todo).toNotExist();
            done();
        }).catch((e) => done(e));

        });
      });
    });

});


问:
Emacs: `C-h k` is undefined
I am new to EMACS. I want to know the command bound with C-x f, so I type C-h k. But it won't work ,and shows me C-h k is undefined.

And my EMACS version is 26.0.90.

答:
"Answer" because I don't have 50 rep to ask in "comment".

Welcome to Emacs!

Thank you for your version info.  There are other questions which are valuable to the effort to help you.  For example:

What OS are you using?

Are you using a gui or a terminal?

If terminal, which terminal?

Are there errors in the Messages buffer on startup?

Do you see the same problem if you start with "emacs -q"?

Do you see the same problem if you start with "emacs -Q"?

One option you have would be to jump into the emacs chat room at  https://chat.stackexchange.com/rooms/17392/scratch

EDIT:
You may have a problem with C-h being a delete - see https://www.emacswiki.org/emacs/BackspaceKey

To route around, the important help commands are:

```<code>C-h k -> M-x describe-key
C-h f -> M-x describe-function
C-h v -> M-x describe-variable
C-h a -> M-x apropos-command
C-h i -> M-x info
</code>```

Title: Emacs: `C-h k` is undefined

Body:
"Answer" because I don't have 50 rep to ask in "comment".

Welcome to Emacs!

Thank you for your version info.  There are other questions which are valuable to the effort to help you.  For example:

What OS are you using?

Are you using a gui or a terminal?

If terminal, which terminal?

Are there errors in the Messages buffer on startup?

Do you see the same problem if you start with "emacs -q"?

Do you see the same problem if you start with "emacs -Q"?

One option you have would be to jump into the emacs chat room at  https://chat.stackexchange.com/rooms/17392/scratch

EDIT:
You may have a problem with C-h being a delete - see https://www.emacswiki.org/emacs/BackspaceKey

To route around, the important help commands are:

C-h k -> M-x describe-key
C-h f -> M-x describe-function
C-h v -> M-x describe-variable
C-h a -> M-x apropos-command
C-h i -> M-x info


问:
Bootstrap 4 last version Carousal buttons is not working
my next/prev buttons are not working. Can someone help me. Thanks!I am new to coding I have researched a bunch and tried different things but nothing is working.</p>

```<code><section class="section-main">
<div class="container">
    <div class="row">
        <div class="col-md-8">
            <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
                <ol class="carousel-indicators">
                    <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
                    <li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
                    <li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
                </ol>
                <div class="carousel-inner" role="listbox">
                    <div class="carousel-item active">
                        <img class="d-block img-fluid" src="img/slide1.jpg" alt="First slide">
                    </div>
                    <div class="carousel-item">
                        <img class="d-block img-fluid" src="img/slide2.jpg" alt="Second slide">
                    </div>
                    <div class="carousel-item">
                        <img class="d-block img-fluid" src="img/slide3.jpg" alt="Third slide">
                    </div>
                </div>
                <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
                    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                    <span class="sr-only">Previous</span>
                </a>
                <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
                    <span class="carousel-control-next-icon" aria-hidden="true"></span>
                    <span class="sr-only">Next</span>
                </a>
            </div>
            <div class="col-md-4">
            </div>
        </div>
    </div>
</code>```

答:
I created an example on codepen based on bootstrap document

The example demonstrates html, css, js codes to make the carousel work.

```<code>$('.carousel').carousel()
</code>```

Please double check if you add required libraries including

```<code>jquery,
bootstrap.js
bootstrap.css.
</code>```

I added them through Pen Settings.

Body:
my next/prev buttons are not working. Can someone help me. Thanks!I am new to coding I have researched a bunch and tried different things but nothing is working.

                    Previous

                    Next

Body:
I created an example on codepen based on bootstrap document

The example demonstrates html, css, js codes to make the carousel work.

$('.carousel').carousel()

Please double check if you add required libraries including

jquery,
bootstrap.js
bootstrap.css.

I added them through Pen Settings.


问:
`munmap_chunk(): invalid pointer` and SIGABRT in Fortran Fourier transform
For a project in my mater's degree I have to make a program to calculate the Fourier transform of a signal.

I open the data of a .dat file and then I have to use a subroutine to calculate the Fourier transform of my signal and return it in an array. I calculate the real part and the imaginary part of the Fourier transform.

"npts" is the number of points in my sine wave.

"nbft" is the number of frequency of my Fourier transform.

"temps" mean "time" in French.**

"F_reel" if the real part of the Fourier transform.

"F_im" is the imaginary part.

"delta_nu" is the temporal resolution.

"freq" is the frequency.

"signal" is the sine wave value.

I tried to translate the program so you can understand what I try to do.

Everything seems to be fine but I keep getting the error SIGABRT.

I think the problem is in my subroutine, at the step 2 but I am not able to find how to solve the problem.

Here is my code :

```<code>program puissance_sinus1_nom
                    !!!!! MAIN PROGRAM !!!!!

! DECLARATION OF CONSTANTS AND VARIABLES
implicit none
integer :: i, ios=0, npts, nbft
double precision, dimension(:), allocatable :: freq, puis
double precision, dimension(:), allocatable :: temps, signal

! INSTRUCTIONS
! 1. Open the file
open(25, file='sinus1_nom.dat', status='old', &
         action='read', iostat=ios)

! 2. Lines count
read(25,*)npts        ! The number of points (npts) is indicated
                      ! in the 1st line of the file I open
allocate(temps(npts))
allocate(signal(npts))
write(*,*)" "

do i = 1,npts
   read(25,*)temps(i),signal(i)
enddo

if (mod(npts,2) .eq. 0) then
   nbft = npts/2 +1
else
   nbft = (npts +1)/2
endif

write(*,*)"Number of frequencies :",nbft
write(*,*) " "
write(*,*) " "

! 3. Use of subroutine
allocate(freq(nbft))
allocate(puis(nbft))
call calcul_fourier(npts,signal,temps,nbft,freq,puis)

! Close everything
deallocate(freq)
deallocate(puis)
deallocate(temps)
deallocate(signal)

close(25)
end program puissance_sinus1_nom

                    !!!!! SUBROUTINE !!!!!

subroutine calcul_fourier(npts,signal,temps,nbft,freq,puis)
! DECLARATION OF VARIABLES
implicit none
integer :: i, k
double precision :: delta_nu, pi=4*atan(1.)
double precision, dimension(nbft) :: F_reel, F_im

integer, intent(in) :: npts, nbft
double precision, dimension(npts), intent(in) :: temps, signal
double precision, dimension(nbft), intent(out) :: freq, puis

! INSTRUCTIONS
! 1. Frequency resolution calculation
delta_nu = (1./temps(npts))*1.d6
write(*,*)"delta_nu = ",delta_nu," micro Hz"

! 2. Calculation of real and imaginary parts of Fourier transform
do k=1, nbft
   freq(k) = (k-1)*delta_nu
enddo

do k=0, nbft+1
   F_reel(k) = 0
   F_im(k) = 0
   do i=1, npts
   F_reel(k) = F_reel(k) + (2./npts)*signal(i)*cos(2*pi*freq(k)*temps(i))
   F_im(k) = F_im(k) + (2./npts)*signal(i)*sin(2*pi*freq(k)*temps(i))
   enddo
   write(*,*)F_reel(k)    ! display to see if it works
enddo

write(*,*) " "
write(*,*) " "
write(*,*) " "

! 3. power calculation (magnitude^2)
do k=1,nbft
   puis(k) = F_reel(k)**2 + F_im(k)**2
enddo

end subroutine calcul_fourier
</code>```

I use write(*,*)F_reel(k) to display the value of the real part of the Fourier transform to check if the program behave correctly, and I am expecting it to return me all the value it calculates.

However, I keep getting this message:

```<code>*** Error in `./puissance_sinus1_nom.x': munmap_chunk(): invalid pointer: 0x0000000000e07d10 ***

Program received signal SIGABRT: Process abort signal.

Backtrace for this error:
#0  0x7F4E9392D407
#1  0x7F4E9392DA1E
#2  0x7F4E92E4A0DF
#3  0x7F4E92E4A067
#4  0x7F4E92E4B447
#5  0x7F4E92E881B3
#6  0x7F4E92E8D98D
#7  0x4013A6 in calcul_fourier_
#8  0x401C0A in MAIN__ at puissance_sinus1_nom.f90:?
Abandon
</code>```

Obviously I am doing something wrong, but I can't see what it is.

Do you have any idea?

答:
Your loop

```<code>do k=0, nbft+1
   F_reel(k) = 0
   F_im(k) = 0
   do i=1, npts
   F_reel(k) = F_reel(k) + (2./npts)*signal(i)*cos(2*pi*freq(k)*temps(i))
   F_im(k) = F_im(k) + (2./npts)*signal(i)*sin(2*pi*freq(k)*temps(i))
   enddo
   write(*,*)F_reel(k)    ! display to see if it works
enddo
</code>```

accesses indexes 0 and nbft+1, but you arrays are declared from 1 to nbft:

```<code>double precision, dimension(nbft) :: F_reel, F_im
</code>```

That is an error, you cannot access arrays out of bounds.

This error can be found by your compiler. Just enable error checking, use flags such as -Wall -fcheck=all for gfortran or -warn -check for Intel. Consult your compiler's manual.

BTW, computing the Fourier transform from the definition is very inefficient, you should use the Fast Fourier Transform (FFT). There are many libraries you can use.

Body:
For a project in my mater's degree I have to make a program to calculate the Fourier transform of a signal.

I open the data of a .dat file and then I have to use a subroutine to calculate the Fourier transform of my signal and return it in an array. I calculate the real part and the imaginary part of the Fourier transform.

"npts" is the number of points in my sine wave.

"nbft" is the number of frequency of my Fourier transform.

"temps" mean "time" in French.**

"F_reel" if the real part of the Fourier transform.

"F_im" is the imaginary part.

"delta_nu" is the temporal resolution.

"freq" is the frequency.

"signal" is the sine wave value.

I tried to translate the program so you can understand what I try to do.

Everything seems to be fine but I keep getting the error SIGABRT.

I think the problem is in my subroutine, at the step 2 but I am not able to find how to solve the problem.

Here is my code :

program puissance_sinus1_nom
                    !!!!! MAIN PROGRAM !!!!!

! DECLARATION OF CONSTANTS AND VARIABLES
implicit none
integer :: i, ios=0, npts, nbft
double precision, dimension(:), allocatable :: freq, puis
double precision, dimension(:), allocatable :: temps, signal

! INSTRUCTIONS
! 1. Open the file
open(25, file='sinus1_nom.dat', status='old', &
         action='read', iostat=ios)

! 2. Lines count
read(25,*)npts        ! The number of points (npts) is indicated
                      ! in the 1st line of the file I open
allocate(temps(npts))
allocate(signal(npts))
write(*,*)" "

do i = 1,npts
   read(25,*)temps(i),signal(i)
enddo

if (mod(npts,2) .eq. 0) then
   nbft = npts/2 +1
else
   nbft = (npts +1)/2
endif

write(*,*)"Number of frequencies :",nbft
write(*,*) " "
write(*,*) " "

! 3. Use of subroutine
allocate(freq(nbft))
allocate(puis(nbft))
call calcul_fourier(npts,signal,temps,nbft,freq,puis)

! Close everything
deallocate(freq)
deallocate(puis)
deallocate(temps)
deallocate(signal)

close(25)
end program puissance_sinus1_nom

                    !!!!! SUBROUTINE !!!!!

subroutine calcul_fourier(npts,signal,temps,nbft,freq,puis)
! DECLARATION OF VARIABLES
implicit none
integer :: i, k
double precision :: delta_nu, pi=4*atan(1.)
double precision, dimension(nbft) :: F_reel, F_im

integer, intent(in) :: npts, nbft
double precision, dimension(npts), intent(in) :: temps, signal
double precision, dimension(nbft), intent(out) :: freq, puis

! INSTRUCTIONS
! 1. Frequency resolution calculation
delta_nu = (1./temps(npts))*1.d6
write(*,*)"delta_nu = ",delta_nu," micro Hz"

! 2. Calculation of real and imaginary parts of Fourier transform
do k=1, nbft
   freq(k) = (k-1)*delta_nu
enddo

do k=0, nbft+1
   F_reel(k) = 0
   F_im(k) = 0
   do i=1, npts
   F_reel(k) = F_reel(k) + (2./npts)*signal(i)*cos(2*pi*freq(k)*temps(i))
   F_im(k) = F_im(k) + (2./npts)*signal(i)*sin(2*pi*freq(k)*temps(i))
   enddo
   write(*,*)F_reel(k)    ! display to see if it works
enddo

write(*,*) " "
write(*,*) " "
write(*,*) " "

! 3. power calculation (magnitude^2)
do k=1,nbft
   puis(k) = F_reel(k)**2 + F_im(k)**2
enddo

end subroutine calcul_fourier

I use write(*,*)F_reel(k) to display the value of the real part of the Fourier transform to check if the program behave correctly, and I am expecting it to return me all the value it calculates.

However, I keep getting this message:

*** Error in `./puissance_sinus1_nom.x': munmap_chunk(): invalid pointer: 0x0000000000e07d10 ***

Program received signal SIGABRT: Process abort signal.

Backtrace for this error:
#0  0x7F4E9392D407
#1  0x7F4E9392DA1E
#2  0x7F4E92E4A0DF
#3  0x7F4E92E4A067
#4  0x7F4E92E4B447
#5  0x7F4E92E881B3
#6  0x7F4E92E8D98D
#7  0x4013A6 in calcul_fourier_
#8  0x401C0A in MAIN__ at puissance_sinus1_nom.f90:?
Abandon

Obviously I am doing something wrong, but I can't see what it is.

Do you have any idea?

Body:
Your loop

do k=0, nbft+1
   F_reel(k) = 0
   F_im(k) = 0
   do i=1, npts
   F_reel(k) = F_reel(k) + (2./npts)*signal(i)*cos(2*pi*freq(k)*temps(i))
   F_im(k) = F_im(k) + (2./npts)*signal(i)*sin(2*pi*freq(k)*temps(i))
   enddo
   write(*,*)F_reel(k)    ! display to see if it works
enddo

accesses indexes 0 and nbft+1, but you arrays are declared from 1 to nbft:

double precision, dimension(nbft) :: F_reel, F_im

That is an error, you cannot access arrays out of bounds.

This error can be found by your compiler. Just enable error checking, use flags such as -Wall -fcheck=all for gfortran or -warn -check for Intel. Consult your compiler's manual.

BTW, computing the Fourier transform from the definition is very inefficient, you should use the Fast Fourier Transform (FFT). There are many libraries you can use.


问:
Symfony3 FOSuserbundle register form one to one entity
i neeed in my symfony base aplication 4 types of user,one of them is super user and can be just typical fosuserbundle user, but need to admin can add 3 different type of user. So i do a new Client class for one type of user which has 1:1 entity with my base user class

```<code>class Client{
my client class fields
...
   /**
   * @ORM\OneToOne(targetEntity="AppBundle\Entity\User")
   * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
   */
  private $user;
...
}
</code>```

And my User class

```<code>class User extends BaseUser
{......}
</code>```

The Question is how to do a register form for this ? Please help me

Now i have this UserType form

```<code>class UserType extends AbstractType
{
   public function buildForm(FormBuilderInterface $builder, array $options)
   {
       parent::buildForm($builder, $options);
   }

   public function configureOptions(OptionsResolver $resolver)
   {
       $resolver->setDefaults(array(
          'data_class' => User::class,
       ));
   }

   public function getParent()
   {
       return 'FOS\UserBundle\Form\Type\RegistrationFormType';
   }

   public function getBlockPrefix()
   {
       return 'app_user_registration';
   }
}
</code>```

And my clientForm class

```<code>class ClientForm extends AbstractType
{
   public function buildForm(FormBuilderInterface $builder, array $options)
   {
       $builder
           ->add('name', TextType::class)
           ->add('address', TextareaType::class)
           ->add('phone', TextType::class)
           ->add('deliveryAddress', TextareaType::class)
           ->add('user', UserType::class);
   }

   public function getParent()
   {
       return 'FOS\UserBundle\Form\Type\RegistrationFormType';
   }

   public function getBlockPrefix()
   {
       return 'app_user_registration';
   }

   public function configureOptions(OptionsResolver $resolver)
   {
       $resolver->setDefaults([
           'data_class' => Client::class,
       ]);
   }
}
</code>```

But this give me a error

```<code>Neither the property "email" nor one of the methods "getEmail()", "email()", "isEmail()", "hasEmail()", "__get()" exist and have public access in class "AppBundle\Entity\Client".
</code>```

答: Oki, becuse earlier i've try a lot of different way to do this, i just delete getParent and getBlockPrefix from my ClientForm class and all look fine :)</p>

Body:
i neeed in my symfony base aplication 4 types of user,one of them is super user and can be just typical fosuserbundle user, but need to admin can add 3 different type of user. So i do a new Client class for one type of user which has 1:1 entity with my base user class

class Client{
my client class fields
...
   /**
   * @ORM\OneToOne(targetEntity="AppBundle\Entity\User")
   * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
   */
  private $user;
...
}

And my User class

class User extends BaseUser
{......}

The Question is how to do a register form for this ? Please help me

Now i have this UserType form

class UserType extends AbstractType
{
   public function buildForm(FormBuilderInterface $builder, array $options)
   {
       parent::buildForm($builder, $options);
   }

   public function configureOptions(OptionsResolver $resolver)
   {
       $resolver->setDefaults(array(
          'data_class' => User::class,
       ));
   }

   public function getParent()
   {
       return 'FOS\UserBundle\Form\Type\RegistrationFormType';
   }

   public function getBlockPrefix()
   {
       return 'app_user_registration';
   }
}

And my clientForm class

class ClientForm extends AbstractType
{
   public function buildForm(FormBuilderInterface $builder, array $options)
   {
       $builder
           ->add('name', TextType::class)
           ->add('address', TextareaType::class)
           ->add('phone', TextType::class)
           ->add('deliveryAddress', TextareaType::class)
           ->add('user', UserType::class);
   }

   public function getParent()
   {
       return 'FOS\UserBundle\Form\Type\RegistrationFormType';
   }

   public function getBlockPrefix()
   {
       return 'app_user_registration';
   }

   public function configureOptions(OptionsResolver $resolver)
   {
       $resolver->setDefaults([
           'data_class' => Client::class,
       ]);
   }
}

But this give me a error

Neither the property "email" nor one of the methods "getEmail()", "email()", "isEmail()", "hasEmail()", "__get()" exist and have public access in class "AppBundle\Entity\Client".


问:
Launching and Monitoring a job at the same time in Ansible tower CLI
We have installed Ansible Tower and have the CLI tools implemented.  We can launch jobs in the CLI using the following -

tower-cli job launch -J 5

This returns the output like so -

```<code>Resource changed.
=== ============ ======================== ======= =======
id  job_template         created          status  elapsed
=== ============ ======================== ======= =======
119            5 2017-12-05T20:26:31.197Z pending 0.0
=== ============ ======================== ======= =======
</code>```

And then we can monitor the status like this -

tower-cli job monitor 119.

Is it possible to pass the input of ID into the monitor cli argument in some way (or is it possible to run both at the same time)?  Since we have multiple jobs running on the server, we would need to be able to reliably get the job id each time.

I didn't see anything about this when I read over the documentation at http://tower-cli.readthedocs.io/en/latest/cli_ref/index.html.

Thanks.

答:
I fixed this by doing the following - </p>

```<code>OUTPUT="$(tower-cli job launch -J 5 | grep -o '[0-9]*' | head -1 )"
tower-cli monitor $OUTPUT
</code>```

Body:
We have installed Ansible Tower and have the CLI tools implemented.  We can launch jobs in the CLI using the following -

tower-cli job launch -J 5

This returns the output like so -

Resource changed.
=== ============ ======================== ======= =======
id  job_template         created          status  elapsed
=== ============ ======================== ======= =======
119            5 2017-12-05T20:26:31.197Z pending 0.0
=== ============ ======================== ======= =======

And then we can monitor the status like this -

tower-cli job monitor 119.

Is it possible to pass the input of ID into the monitor cli argument in some way (or is it possible to run both at the same time)?  Since we have multiple jobs running on the server, we would need to be able to reliably get the job id each time.

I didn't see anything about this when I read over the documentation at http://tower-cli.readthedocs.io/en/latest/cli_ref/index.html.

Thanks.

Body:
I fixed this by doing the following -

OUTPUT="$(tower-cli job launch -J 5 | grep -o '[0-9]*' | head -1 )"
tower-cli monitor $OUTPUT


问:
how to write css for a specific breakpoint in angular material
I am trying to write CSS for a div, that should apply only when a particular breakpoint is hit, eg. sm, md or lg.

I'm using angular-material (https://material.angularjs.org).

I know that this can be done using media queries @media (max-width: 480px) { ... } but i'm looking for a angular-material way of doing this.

答:
Adding custom css to a tag using material breakpoints, Say suppose i have a custom css like below:

```<code>.textLeft{
text-align: left;
margin-left: 24%;
}
</code>```

and you wanted to add it to a h3 tag if it is a not a mobile device, then follow the below steps.
 1. Add ngMaterial to module.

```<code>var app = angular.module('MyApp',['ngMaterial']);
</code>```

2. inject $mdMedia to controller

```<code>app.controller('TabCtrl', ['$scope','$mdMedia', function($scope,$mdMedia){
  var thisCtrl = this;
  $scope.$mdMedia = $mdMedia;
}]);
</code>```

3. Now use the $mdMedia as described by Rob earlier:

```<code><div ng-controller="TabCtrl" layout="column">
<h3 ng-class="{'textLeft' : $mdMedia('gt-sm')}">
                        {{user.name}}</h3>
</div>
</code>```

Body:
Adding custom css to a tag using material breakpoints, Say suppose i have a custom css like below:

.textLeft{
text-align: left;
margin-left: 24%;
}

and you wanted to add it to a h3 tag if it is a not a mobile device, then follow the below steps.
 1. Add ngMaterial to module.

var app = angular.module('MyApp',['ngMaterial']);

2. inject $mdMedia to controller

app.controller('TabCtrl', ['$scope','$mdMedia', function($scope,$mdMedia){
  var thisCtrl = this;
  $scope.$mdMedia = $mdMedia;
}]);

3. Now use the $mdMedia as described by Rob earlier:

<div ng-controller="TabCtrl" layout="column">
<h3 ng-class="{'textLeft' : $mdMedia('gt-sm')}">
                        {{user.name}}</h3>
</div>


答:
let's break done the code

```<code>range(integer_value)
</code>```

Returns a list of elements from 0 to integer_value -1 that's why you can iter over it

with this said:

```<code>#this is returning the longitude of the list
cal = len(a)
#this is iterating over a list of [0,1,2,3... until len -1)
for d in range(cal):
    #this checks if the value of a in the position d is in the list called b
    #this is also checking that it's not in c to avoid duplication,
    #but you could use a set which is a "list" that doesn't accept duplicates
    if a[d] in b and a[d] not in c:
         c.append(a[d])
</code>```

Body:
Below is the code:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
c = []

cal = len(a)

for d in range(cal):
     if a[d] in b and a[d] not in c:
         c.append(a[d])
print(c)

Below is the output:

[1, 2, 3, 5, 8, 13]

Process finished with exit code 0

I was not able to make the logic myself so I had looked at the solution but still didn't get the concept behind the code. The point where I am getting confused is that in cal I am storing the length of a which is 11, then I am doing a for loop 11 times(I am not sure why this is being done and what will we get from this part), then then finally conditional using "a[d]". It just doesnt makes sense to me.

Body:
let's break done the code

range(integer_value)

Returns a list of elements from 0 to integer_value -1 that's why you can iter over it

with this said:

#this is returning the longitude of the list
cal = len(a)
#this is iterating over a list of [0,1,2,3... until len -1)
for d in range(cal):
    #this checks if the value of a in the position d is in the list called b
    #this is also checking that it's not in c to avoid duplication,
    #but you could use a set which is a "list" that doesn't accept duplicates
    if a[d] in b and a[d] not in c:
         c.append(a[d])


问:
Save data from activity other than main
I have a question. I have an android application in which I use several activities, in addition to the main, in some of these I have forms to record data in a sqlite database. the problem is that when trying to store the information through a button I do not get any response from the application. It does not present any errors but neither does it create the database or execute the method. It's as if he had not pressed the button. I am using Android Studio 3.0.1 and SQLite. Please, I hope you can guide me. Thank you.

I attach the code used in one of the activities for the data registration.

```<code>/*SQLite class*/
public class SqlDB extends SQLiteOpenHelper {

  private static final int version=1;
  private static final String name="DB_Proyecto";

  public SqlDB(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, name, factory, version);
  }

  public SqlDB(Context context){
    super(context, name, null, version);
  }

  @Override
  public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE IF NOT EXISTS Ars (idArs INT PRIMARY KEY AUTOINCREMENT NOT NULL, NameArs TEXT)");

  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

  }
}
</code>```

/*AddArs class. From this i try insert data in db... */

```<code>public class AddArs extends AppCompatActivity implements View.OnClickListener {

EditText et1;
Button bt1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_ars);

    et1 = (EditText)findViewById(R.id.etNombre);
    bt1 = (Button)findViewById(R.id.btEnvia);

    bt1.setOnClickListener(this);
}

public void GrabaDatos(){
    String nombreArs = et1.getText().toString();
    SqlDB sqlDB = new SqlDB(this, "DB_Proyecto", null, 1);

    SQLiteDatabase dbase = sqlDB.getWritableDatabase();
    if(dbase !=null){
        ContentValues nuevoRegistro = new ContentValues();
        nuevoRegistro.put("NameArs", nombreArs);

        dbase.insert("Ars", null, nuevoRegistro);
        Toast.makeText(this, "Registro Creado.", Toast.LENGTH_SHORT).show();
    }
}

@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.bt1:
            GrabaDatos();
            break;
        /*case by other buttons*/
    }
}
}
</code>```

答:
You're not referencing the button ID correctly.

The correct ID is R.id.btEnvia:

```<code>@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.btEnvia:
            GrabaDatos();
            break;
        /*case by other buttons*/
    }
}
</code>```

Title: Save data from activity other than main

Body:
I have a question. I have an android application in which I use several activities, in addition to the main, in some of these I have forms to record data in a sqlite database. the problem is that when trying to store the information through a button I do not get any response from the application. It does not present any errors but neither does it create the database or execute the method. It's as if he had not pressed the button. I am using Android Studio 3.0.1 and SQLite. Please, I hope you can guide me. Thank you.

I attach the code used in one of the activities for the data registration.

/*SQLite class*/
public class SqlDB extends SQLiteOpenHelper {

  private static final int version=1;
  private static final String name="DB_Proyecto";

  public SqlDB(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, name, factory, version);
  }

  public SqlDB(Context context){
    super(context, name, null, version);
  }

  @Override
  public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE IF NOT EXISTS Ars (idArs INT PRIMARY KEY AUTOINCREMENT NOT NULL, NameArs TEXT)");

  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

  }
}

/*AddArs class. From this i try insert data in db... */

public class AddArs extends AppCompatActivity implements View.OnClickListener {

EditText et1;
Button bt1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_ars);

    et1 = (EditText)findViewById(R.id.etNombre);
    bt1 = (Button)findViewById(R.id.btEnvia);

    bt1.setOnClickListener(this);
}

public void GrabaDatos(){
    String nombreArs = et1.getText().toString();
    SqlDB sqlDB = new SqlDB(this, "DB_Proyecto", null, 1);

    SQLiteDatabase dbase = sqlDB.getWritableDatabase();
    if(dbase !=null){
        ContentValues nuevoRegistro = new ContentValues();
        nuevoRegistro.put("NameArs", nombreArs);

        dbase.insert("Ars", null, nuevoRegistro);
        Toast.makeText(this, "Registro Creado.", Toast.LENGTH_SHORT).show();
    }
}

@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.bt1:
            GrabaDatos();
            break;
        /*case by other buttons*/
    }
}
}

Body:
You're not referencing the button ID correctly.

The correct ID is R.id.btEnvia:

@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.btEnvia:
            GrabaDatos();
            break;
        /*case by other buttons*/
    }
}


问:
Returning error when trying to insert document with non-existent field in elasticsearch
For example, I want to insert a new document which consists of two strings into myindex/mytype

{ "name" : "joe", "city": "ny" }

BUT mytype consist only of one string field: "name"

In this case, I want the indexing to fail, and that elasticsearch will return an error. How do I do that?
Right now, it creates a new document :frowning:

Thanks for your help!

答:
You can use dynamic setting of mapping.

```<code>PUT /my_index
{
    "mappings": {
        "my_type": {
            "dynamic":      "strict",
            "properties": {
                "name":  { "type": "string"}
            }
        }
    }
}
</code>```

If you set true, which is the default, adding new fields dynamically.

If you set false, ignoring new fields.

If you set strict, elasticsearch throw an exception if an unknown field is encountered.

Source : https://www.elastic.co/guide/en/elasticsearch/guide/current/dynamic-mapping.html

Body:
You can use dynamic setting of mapping.

PUT /my_index
{
    "mappings": {
        "my_type": {
            "dynamic":      "strict",
            "properties": {
                "name":  { "type": "string"}
            }
        }
    }
}

If you set true, which is the default, adding new fields dynamically.

If you set false, ignoring new fields.

If you set strict, elasticsearch throw an exception if an unknown field is encountered.

Source : https://www.elastic.co/guide/en/elasticsearch/guide/current/dynamic-mapping.html


问:
How to center everything inside navbar
I want to center everything in bootstrap navbar, it's my code:

```<code>    <nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="navbar-header">
      <a class="navbar-brand" href="#">WebSiteName</a>
    </div>
    <ul class="nav navbar-nav">
      <li class="active"><a href="#">Home</a></li>
      <li><a href="#">Page 1</a></li>
      <li><a href="#">Page 2</a></li>
      <li><a href="#">Page 3</a></li>
    </ul>
  </div>
</nav>
</code>```

I want to center div with class "container-fluid", I've tried adding "margin: 0 auto; float:none" to this div, but It doesn't work
I added this:

```<code>.container-fluid {
      margin: 0 auto !important;
      float: none !important;
    }
</code>```

still doesn't work

答:
You can add .navbar { display: flex; }
(No need for the other CSS then)

https://codepen.io/anon/pen/YEbrPz

Title: How to center everything inside navbar

Body:
I want to center everything in bootstrap navbar, it's my code:

      WebSiteName

Home

Page 1

Page 2

Page 3

I want to center div with class "container-fluid", I've tried adding "margin: 0 auto; float:none" to this div, but It doesn't work
I added this:

.container-fluid {
      margin: 0 auto !important;
      float: none !important;
    }

still doesn't work


问:
Copy cells and paste them in all those that are empty
I need a macro that, (at it says in the title) copy the two last cells, in this case A419 and B419, and paste their value until it find others that contain information.

In example:

As you can see in the image, there's the Value 1004-004 and 36300025 and a lot of empty cells below. And more below theres 1004-005 and 36300026 Something like from 420 to 434. And then select 1004-005 and 36300026 and repeat the process.

This:

To this:

Well, that's all, i don't really know how to do it, so i'll be very grateful if you can help me out guys.

答:
use a basic formula on the blank cells. convert the formula results to values if you wish.</p>

```<code>with worksheets("sheet1")
    with intersect(.columns("a:b"), .usedrange)
        .specialcells(xlcelltypeblanks).formular1c1 = "=r[-1]c"
        .value = .value2
    end with
end with
</code>```

Body:
use a basic formula on the blank cells. convert the formula results to values if you wish.

with worksheets("sheet1")
    with intersect(.columns("a:b"), .usedrange)
        .specialcells(xlcelltypeblanks).formular1c1 = "=r[-1]c"
        .value = .value2
    end with
end with


问:
Not matched rows in B join with some row in A
Example data:

```<code>Table1     Table2
x | y      x | y
-----      -----
1 | A      1 | A
1 | B      1 | D
1 | C      2 | M
1 | null   2 | N
2 | M      2 | M
2 | N      1 | A
</code>```

I want to count number of x's in Table2 and join it with Table1. But in Table2 I can have y's which doesn't match to y's in Table1. In this case I want to join them with row with null in y column in Table1.
In an example Table2.1-D should be joined with Tabl1.1-null

For given example I expect the result:

```<code>x | y    | count
-----------------
1 | A    | 2
1 | B    | 0
1 | C    | 0
1 | null | 1 (because D doesn't match to anything else in Table1)
2 | M    | 2
2 | N    | 1
</code>```

答:
Thank you for all answers.
They were very helpful.
Here is my solution, with counts in proper way all rows from Table2 and match it by x to row in table1 with y == null.
I know that I can wright better subquery in left join.

Of course the real problem is much complicated and the question is simplified version of it.

I you find how I can improve the query then please, let me know :)

```<code>;with T2Count as
(
    select x, y, count(*) cnt from @t2 group by x, y
)
/*
select t1.x, t1.y, isnull(t2.cnt, 0)
from @T1 t1
left join T2Count t2 on t1.x = t2.x and t1.y = t2.y
where t1.y is not null
*/
select t1.x, t1.y, isnull(AllCounts.cnt, 0) cnt from @t1 t1
left join (
    select * from T2Count -- I know that here I'will take too much data 1-D, 2-Q, but those data will not natch in last join (AllCounts...)
union all
    select t2.x, null, sum(cnt) cnt
    from T2Count t2
    left join @t1 t1 on t1.x = t2.x and t1.y = t2.y
    where t1.x is null
    group by t2.x
) as AllCounts on t1.x = AllCounts.x and (t1.y = AllCounts.y or (t1.y is null and AllCounts.y is null))
</code>```

Body:
Example data:

Table1     Table2
x | y      x | y
-----      -----
1 | A      1 | A
1 | B      1 | D
1 | C      2 | M
1 | null   2 | N
2 | M      2 | M
2 | N      1 | A

I want to count number of x's in Table2 and join it with Table1. But in Table2 I can have y's which doesn't match to y's in Table1. In this case I want to join them with row with null in y column in Table1.
In an example Table2.1-D should be joined with Tabl1.1-null

For given example I expect the result:

x | y    | count
-----------------
1 | A    | 2
1 | B    | 0
1 | C    | 0
1 | null | 1 (because D doesn't match to anything else in Table1)
2 | M    | 2
2 | N    | 1

Body:
Thank you for all answers.
They were very helpful.
Here is my solution, with counts in proper way all rows from Table2 and match it by x to row in table1 with y == null.
I know that I can wright better subquery in left join.

Of course the real problem is much complicated and the question is simplified version of it.

I you find how I can improve the query then please, let me know :)

;with T2Count as
(
    select x, y, count(*) cnt from @t2 group by x, y
)
/*
select t1.x, t1.y, isnull(t2.cnt, 0)
from @T1 t1
left join T2Count t2 on t1.x = t2.x and t1.y = t2.y
where t1.y is not null
*/
select t1.x, t1.y, isnull(AllCounts.cnt, 0) cnt from @t1 t1
left join (
    select * from T2Count -- I know that here I'will take too much data 1-D, 2-Q, but those data will not natch in last join (AllCounts...)
union all
    select t2.x, null, sum(cnt) cnt
    from T2Count t2
    left join @t1 t1 on t1.x = t2.x and t1.y = t2.y
    where t1.x is null
    group by t2.x
) as AllCounts on t1.x = AllCounts.x and (t1.y = AllCounts.y or (t1.y is null and AllCounts.y is null))


问:
while EOF in JAVA?
Following to some forums answers I'm using this:

```<code>    while (fileReader.nextLine() != null) {
        String line = fileReader.nextLine();
        System.out.println(line);
    }
</code>```

... but it throws exception at the end anyway
(Exception in thread "main" java.util.NoSuchElementException: No line found)

答:
```<code>while(inFile.hasNext())
</code>```

This is correct in java programming language

Title: while EOF in JAVA?

Body:
Following to some forums answers I'm using this:

    while (fileReader.nextLine() != null) {
        String line = fileReader.nextLine();
        System.out.println(line);
    }

... but it throws exception at the end anyway
(Exception in thread "main" java.util.NoSuchElementException: No line found)

Body:
while(inFile.hasNext())

This is correct in java programming language


问:
What filetypes can Crafter Search index?
Crafter search can index attached files. For example, I can search the contents of an attached PDF...

However, is it compatible with Docx?
and image metadata? (for example jpg)
Is there a compatibility list somewhere?

I'm having issues getting docx and a jpg indexed, although a PDF is working perfectly

答:
Crafter Search relies on Solr that uses the Apache Tika library to index binary documents. You can find the list of compatible formats here: https://tika.apache.org/1.16/formats.html (for CrafterCMS 3.0) and https://tika.apache.org/1.5/formats.html (for CrafterCMS 2.x)

For proprietary formats such as docx you need to check the compatibility and the supported fields in the library documentation.


问:
Order graph by count not alphabetically
My data is as follows:

```<code>        channel    ter   Id
0       BWM        A     6
1       IND        A     15
2       RIA        C     2
3       BWM        B     7
4       IND        B     5
5       RIA        A     4
6       BWM        C     3
7       IND        C     33
8       RIA        B     21
</code>```

When I plot it:

```<code>sns.set(style='darkgrid')
sns.barplot(x='channel', y='Id', hue='ter', data=df, palette='Set2')
plt.show()
</code>```

It is ordered by alphabet on the x axis, so channel is BWM->IND->RIA.
However, what I need is for it to be sorted by count (ie. Id value), so IND is first.

I tried adding order = df['channel'].value_counts().index inside barplot() but didn't help.

I Would also like to have the ability to order ter according to count as well, per channel, but don't have to if too much effort.

Thank you!

答:
Since each channel contains multiple IDs, simply "sorted by ID" is not well-defined; you would have to specify something like the sum of IDs, the greatest ID within the group, or something else. If you want to order the bars by the greatest ID sum,

```<code>sns.barplot(x='channel', y='Id', hue='ter', data=df, palette='Set2', order=df.groupby('channel').Id.sum().sort_values(ascending=False).index)
</code>```

does the job.

Title: Order graph by count not alphabetically

Body:
My data is as follows:

        channel    ter   Id
0       BWM        A     6
1       IND        A     15
2       RIA        C     2
3       BWM        B     7
4       IND        B     5
5       RIA        A     4
6       BWM        C     3
7       IND        C     33
8       RIA        B     21

When I plot it:

sns.set(style='darkgrid')
sns.barplot(x='channel', y='Id', hue='ter', data=df, palette='Set2')
plt.show()

It is ordered by alphabet on the x axis, so channel is BWM->IND->RIA.
However, what I need is for it to be sorted by count (ie. Id value), so IND is first.

I tried adding order = df['channel'].value_counts().index inside barplot() but didn't help.

I Would also like to have the ability to order ter according to count as well, per channel, but don't have to if too much effort.

Thank you!

Body:
Since each channel contains multiple IDs, simply "sorted by ID" is not well-defined; you would have to specify something like the sum of IDs, the greatest ID within the group, or something else. If you want to order the bars by the greatest ID sum,

sns.barplot(x='channel', y='Id', hue='ter', data=df, palette='Set2', order=df.groupby('channel').Id.sum().sort_values(ascending=False).index)

does the job.


问:
Gradle won't work with android studio 3.0
When I try to debug an Android app with Android Studio 3.0.1, it generates following error:

Information:Gradle tasks [:app:generateDebugSources, :app:generateDebugAndroidTestSources, :app:mockableAndroidJar]
Error:java.util.concurrent.ExecutionException: java.lang.RuntimeException: No server to serve request. Check logs for details.
Error:Execution failed for task ':app:mergeDebugResources'.
> Error: java.util.concurrent.ExecutionException: java.lang.RuntimeException: No server to serve request. Check logs for details.
Information:BUILD FAILED in 6s
Information:2 errors
Information:0 warnings
Information:See complete output in console
```

<p>Any idea to get rid of that?</p>

<p>The last lines of Gradle console shows following:</p>

<pre class="lang-none prettyprint-override"><code>:app:mergeDebugResources
Error: java.util.concurrent.ExecutionException: java.lang.RuntimeException: No server to serve request. Check logs for details.
:app:mergeDebugResources FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:mergeDebugResources'.
> Error: java.util.concurrent.ExecutionException: java.lang.RuntimeException: No server to serve request. Check logs for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 6s

15 actionable tasks: 14 executed, 1 up-to-date
</code>```

答:
You may try this :

Update the gradle and than,

Go to --> gradle.wrapper.properties

and replace the distribution Url with this :

distributionUrl=https://services.gradle.org/distributions/gradle-3.4.1-all.zip
   You can replace "gradle-3.4.1" with the latest version of gradle for android studio.

Make sure your plugins are updated.

While following these steps make sure you have a working internet connection so that gradle as well as the plugins can be updated.

Hope this helps !

Body:
When I try to debug an Android app with Android Studio 3.0.1, it generates following error:

Information:Gradle tasks [:app:generateDebugSources, :app:generateDebugAndroidTestSources, :app:mockableAndroidJar]
Error:java.util.concurrent.ExecutionException: java.lang.RuntimeException: No server to serve request. Check logs for details.
Error:Execution failed for task ':app:mergeDebugResources'.
> Error: java.util.concurrent.ExecutionException: java.lang.RuntimeException: No server to serve request. Check logs for details.
Information:BUILD FAILED in 6s
Information:2 errors
Information:0 warnings
Information:See complete output in console

Any idea to get rid of that?

The last lines of Gradle console shows following:

:app:mergeDebugResources
Error: java.util.concurrent.ExecutionException: java.lang.RuntimeException: No server to serve request. Check logs for details.
:app:mergeDebugResources FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:mergeDebugResources'.
> Error: java.util.concurrent.ExecutionException: java.lang.RuntimeException: No server to serve request. Check logs for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 6s

15 actionable tasks: 14 executed, 1 up-to-date