问:
Gradle inject root project class path to dependencies
I am building a library, which has separate entry points (like server, gui), with different dependencies. Each entry point is in a separate sub project with its own dependencies.

In the root project, where I start the build from, I want to select the entry point, and only build with that dependencies. That is working.

But I want to instantiate a class (eg MainClass) of the root project from the library entry point and I cant add the root projects class path to the dependency. (Diagram)

Root projects build file looks like this now:

```<code>dependencies{
    implementation project(':server')
}
</code>```

答:
It seems to me that it would be easier to understand and clearer if the entry point projects depended on the core API instead of vice versa.
You could have project structure like:

```<code>settings.gradle
core/
  build.gradle
  src/
server/
  build.gradle
  src/
gui
  build.gradle
  src/
</code>```

server and gui project build.gradle files should contain:

```<code>dependencies {
  implementation project(':core')
}
</code>```

The project that uses the library could depend on Server and/or GUI projects and instantiate the necessary class (ServerEntry or GuiEntry) directly.

If you want to be able to switch between different entry point implementations without changing the code in the project that uses the entry point instance I'd suggest using a dependency injection framework (Spring, Guice, Dagger). Dependency injection would help to separate configuration (binding interfaces to classes) from the actual application.

Body:
I am building a library, which has separate entry points (like server, gui), with different dependencies. Each entry point is in a separate sub project with its own dependencies.

In the root project, where I start the build from, I want to select the entry point, and only build with that dependencies. That is working.

But I want to instantiate a class (eg MainClass) of the root project from the library entry point and I cant add the root projects class path to the dependency. (Diagram)

Root projects build file looks like this now:

dependencies{
    implementation project(':server')
}

Body:
It seems to me that it would be easier to understand and clearer if the entry point projects depended on the core API instead of vice versa.
You could have project structure like:

settings.gradle
core/
  build.gradle
  src/
server/
  build.gradle
  src/
gui
  build.gradle
  src/

server and gui project build.gradle files should contain:

dependencies {
  implementation project(':core')
}

The project that uses the library could depend on Server and/or GUI projects and instantiate the necessary class (ServerEntry or GuiEntry) directly.

If you want to be able to switch between different entry point implementations without changing the code in the project that uses the entry point instance I'd suggest using a dependency injection framework (Spring, Guice, Dagger). Dependency injection would help to separate configuration (binding interfaces to classes) from the actual application.


来源: stackexchange

问:
Issues with csrf token field being empty
I'm pretty brand new to php/laravel (bear with me!) and am having some issues with csrf tokens for one of my forms. I've included the code to the entire view, but the form I'm having issues with is the #editActionDueDate modal. When hitting edit on the modal form, it returns a 419 error. I've tried passing the csrf token with every way I can think of, but I can't get the token through. It just passes an empty value for that token parameter.

Every other form on my site is working just fine, so I'm a little confused.

The only difference I can think of with this form is that it has a modified script to pass the information of the current due_date to the form itself - everything else is identical and from what I've asked some of our developers, this should not affect it.

Also, if I exclude this uri from the csrf verification middleware, it works fine.

Any ideas of what could be causing the token field to be empty?

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>View Action Details</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}"></script>

    <script>
    // Open "edit due date" modal and pass due_date info
    $(document).ready(function() {
        $('#editActionDueDate').on('show.bs.modal', function (event) {

        var button = $(event.relatedTarget) // Button that triggered the modal
        var due_date = button.data('due_date') // Extract info from data-* attributes
        var modal = $(this)

        modal.find('.modal-body input').val(due_date)
        });
    })
    </script>
    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">
    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
    @include('nav')
    <div>

        @foreach($action as $act)
        <a href="{{ route('patient', $act->patient_id) }}">Return to patient profile</a>
        @endforeach

        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#insertActionNote">
            + Action Note
        </button>

    </div>
    <div>
        <h3>Action View</h3>
        @foreach($action as $act)
        <table class="table">
            <tr>
                <th>Action ID</th>
                <th>Patient</th>
                <th>Created Date</th>
                <th>Last Modified Date</th>
            </tr>
            <tr>
                <td>{{ $act->action_id}}</td>
                <td>{{ $act->first_name.' '.$act->last_name}}</td>
                <td>{{ $act->created_at}}</td>
                <td>{{ $act->updated_at}}</td>
            </tr>
            <tr>
                <th>Action</th>
                <th>Status</th>
                <th>Due Date</th>
            </tr>
            <tr>
                <td>{{ $act->option_text}}</td>
                <td>{{ $act->action_status_name}}</td>
                <td>{{ $act->due_date}}</td>
                <td><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#editActionDueDate" data-due_date="{{ $act->due_date }}">Edit</button></td>
            </tr>
        </table>
        @endforeach
    </div>
    <div>
    <h3>Notes</h3>
    <table class="table">
        @foreach($notes as $note)
        <tr>
            <td><strong>Date: {{$note->created_at}}</strong></td>
            <td><strong>Submitted By: {{$note->user_name}}</strong></td>
        </tr>
        <tr>
            <td>{{$note->note_text}}</td>
        </tr>
        @endforeach
    </table>

    {{ $notes->links() }}

    </div>

    <!-- This modal form works fine -->
    <div class="modal fade" id="insertActionNote" tabindex="-1" role="dialog" aria-labelledby="insertActionNoteLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="insertActionNoteLabel">Add New Note</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form method="POST" action="{{ route('addActionNote') }}">
                    {{ csrf_field() }}

                    <input id="user_id" type="hidden" name="user_id" value="{{ Auth::user()->user_id }}" >
                    <input id="action_id" type="hidden" name="action_id" value="{{ $act->action_id }}" >

                    <div class="form-group row">
                        <label for="note_text" class="col-md-2 col-form-label text-md-right">{{ __('Note') }}</label>

                        <div class="col-md-10">
                            <textarea id="note_text" name="note_text" type="text" class="form-control @error('note_text') is-invalid @enderror" rows="4" value="{{ old('note_text') }}" required autofocus></textarea>

                            @error('note_text')
                                <span class="invalid-feedback" role="alert">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror
                        </div>
                    </div>

                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary">
                            {{ __('Add Note') }}
                        </button>
                    </div>
                    </form>
                </div>

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

    <!-- This modal form is passing an empty token-->
    <div class="modal fade" id="editActionDueDate" tabindex="-1" role="dialog" aria-labelledby="editActionDueDateLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editActionDueDateLabel">Edit Due Date</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form method="POST" action="{{ route('editActionDueDate') }}">
                        {!! csrf_field() !!}

                    <input id="action_id" type="hidden" name="action_id" value="{{ $act->action_id }}" >

                    <div class="form-group row">
                        <label for="note_text" class="col-md-4 col-form-label text-md-right">{{ __('Due Date') }}</label>

                        <div class="col-md-6">
                            <input id="due_date" type="text" class="form-control @error('due_date') is-invalid @enderror" name="due_date" value="{{ old('due_date') }}" placeholder="MM/DD/YYYY" autofocus>

                            @error('due_date')
                                <span class="invalid-feedback" role="alert">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror
                        </div>
                    </div>

                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary">
                            {{ __('Edit Due Date') }}
                        </button>
                    </div>
                    </form>
                </div>

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

</body>
</html>
</code>```

```<code><?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

use App\Http\Controllers\PatientController;

Route::get('/', function () {
    return view('welcome');
});

Route::get('/home', 'HomeController@index')->name('home');

Route::post('/addAction', 'ActionController@store')->name('addAction');
Route::post('/addPatientNote', 'PatientNoteController@store')->name('addPatientNote');
Route::post('/addActionNote', 'ActionNoteController@store')->name('addActionNote');
Route::post('/editActionDueDate/{action_id}', 'ActionController@editActionDueDate')->name('editActionDueDate');

Auth::routes();

Route::get('/registerPatient', 'PatientController@showPatientRegistrationForm')->name('registerPatient');
Route::post('/registerPatient', 'PatientController@store');
Route::post('/editPatient', 'PatientController@update')->name('editPatient');
Route::get('/patient/{patient_id}', 'PatientController@show')->name('patient');

Route::get('/viewAction/{action_id}', 'ActionController@show')->name('viewAction');

Route::get('dashboard', 'ActionController@index')->name('actions.index');
Route::get('getActions', 'ActionController@getActionsTable')->name('get.actions');

Route::resource('users', 'UserController');

Route::get('/addQuestion', 'QuestionController@showNewQuestions')->name('addQuestion');
Route::post('/addQuestion', 'QuestionController@storeNewQuestionAndOptions');
</code>```

答:
Which version of Laravel are you using? If I've read it correctly, and the form that's failing you is the update, it may be because you're missing the method. In the update form you must put the CSRF token and specify that you will use the put method to update.

You must also pass the id of the element you want to update to the action of the form.

```<code><form method="POST" action="{{ route('editActionDueDate', $act->action_id ) }}">

    @csrf

    @method('PUT')

    // inputs and other stuff

</form>
</code>```

See more:

csfr protection

Method field

ContentLicense: CC BY-SA 4.0

Body:
I'm pretty brand new to php/laravel (bear with me!) and am having some issues with csrf tokens for one of my forms. I've included the code to the entire view, but the form I'm having issues with is the #editActionDueDate modal. When hitting edit on the modal form, it returns a 419 error. I've tried passing the csrf token with every way I can think of, but I can't get the token through. It just passes an empty value for that token parameter.

Every other form on my site is working just fine, so I'm a little confused.

The only difference I can think of with this form is that it has a modified script to pass the information of the current due_date to the form itself - everything else is identical and from what I've asked some of our developers, this should not affect it.

Also, if I exclude this uri from the csrf verification middleware, it works fine.

Any ideas of what could be causing the token field to be empty?

<!DOCTYPE html>

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

    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">

    <link href="{{ asset('css/app.css') }}" rel="stylesheet">

    @include('nav')

        @foreach($action as $act)
        patient_id) }}">Return to patient profile
        @endforeach

        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#insertActionNote">
            + Action Note
        </button>

Action View

        @foreach($action as $act)

                Action ID
                Patient
                Created Date
                Last Modified Date

                {{ $act->action_id}}
                {{ $act->first_name.' '.$act->last_name}}
                {{ $act->created_at}}
                {{ $act->updated_at}}

                Action
                Status
                Due Date

                {{ $act->option_text}}
                {{ $act->action_status_name}}
                {{ $act->due_date}}
                <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#editActionDueDate" data-due_date="{{ $act->due_date }}">Edit</button>

        @endforeach

Notes

        @foreach($notes as $note)

            Date: {{$note->created_at}}
            Submitted By: {{$note->user_name}}

            {{$note->note_text}}

        @endforeach

    {{ $notes->links() }}

Add New Note

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        ×
                    </button>

                    <form method="POST" action="{{ route('addActionNote') }}">
                    {{ csrf_field() }}

                    <input id="user_id" type="hidden" name="user_id" value="{{ Auth::user()->user_id }}" >
                    <input id="action_id" type="hidden" name="action_id" value="{{ $act->action_id }}" >

                        {{ __('Note') }}

                            <textarea id="note_text" name="note_text" type="text" class="form-control @error('note_text') is-invalid @enderror" rows="4" value="{{ old('note_text') }}" required autofocus></textarea>

                            @error('note_text')

                                    {{ $message }}

                            @enderror

                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary">
                            {{ __('Add Note') }}
                        </button>

                    </form>

Edit Due Date

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        ×
                    </button>

                    <form method="POST" action="{{ route('editActionDueDate') }}">
                        {!! csrf_field() !!}

                    <input id="action_id" type="hidden" name="action_id" value="{{ $act->action_id }}" >

                        {{ __('Due Date') }}

                            <input id="due_date" type="text" class="form-control @error('due_date') is-invalid @enderror" name="due_date" value="{{ old('due_date') }}" placeholder="MM/DD/YYYY" autofocus>

                            @error('due_date')

                                    {{ $message }}

                            @enderror

                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary">
                            {{ __('Edit Due Date') }}
                        </button>

                    </form>

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

use App\Http\Controllers\PatientController;

Route::get('/', function () {
    return view('welcome');
});

Route::get('/home', 'HomeController@index')->name('home');

Route::post('/addAction', 'ActionController@store')->name('addAction');
Route::post('/addPatientNote', 'PatientNoteController@store')->name('addPatientNote');
Route::post('/addActionNote', 'ActionNoteController@store')->name('addActionNote');
Route::post('/editActionDueDate/{action_id}', 'ActionController@editActionDueDate')->name('editActionDueDate');

Auth::routes();

Route::get('/registerPatient', 'PatientController@showPatientRegistrationForm')->name('registerPatient');
Route::post('/registerPatient', 'PatientController@store');
Route::post('/editPatient', 'PatientController@update')->name('editPatient');
Route::get('/patient/{patient_id}', 'PatientController@show')->name('patient');

Route::get('/viewAction/{action_id}', 'ActionController@show')->name('viewAction');

Route::get('dashboard', 'ActionController@index')->name('actions.index');
Route::get('getActions', 'ActionController@getActionsTable')->name('get.actions');

Route::resource('users', 'UserController');

Route::get('/addQuestion', 'QuestionController@showNewQuestions')->name('addQuestion');
Route::post('/addQuestion', 'QuestionController@storeNewQuestionAndOptions');

Body:
Which version of Laravel are you using? If I've read it correctly, and the form that's failing you is the update, it may be because you're missing the method. In the update form you must put the CSRF token and specify that you will use the put method to update.

You must also pass the id of the element you want to update to the action of the form.

<form method="POST" action="{{ route('editActionDueDate', $act->action_id ) }}">

    @csrf

    @method('PUT')

    // inputs and other stuff

</form>

See more:

csfr protection

Method field


问:
JSON and ASP.NET WebMethod not firing server side method
I'm trying to pass parameters to my code behind with WebMethod.

I'm reaching the success end of ajax but the method in my aspx.cs code behind doesn't get called and I have error.

Operation failed! Details :'[object Object]

I'm using a masterpage if it makes a difference.

How to do resolve this ?

Please, can you help me ?

Javascript:

```<code><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
<script type="text/javascript">
    $(function () {
        $("[id*=imgfasi]").bind("click", function () {
            var fasi = {};
            fasi.Txseltlc = $("[id*=txseltlc]").val();
            fasi.Txrescldisa = $("[id*=txrescldisa]").val();
            fasi.Ddlauttlc = $("[id*=ddlauttlc]").val();
            $.ajax({
                type: "POST",
                url: "Default.aspx/Savepnfasi",
                data: '{fasi: ' + JSON.stringify(fasi) + '}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (response == "1") {
                        alert("Success!");
                    } else {
                        alert("Operation failed! Details: " + response);
                    }
                }
            });
            return false;
        });
    });
</script>
</code>```

code behind :

```<code>public class pnfasiweb
{
    public string Txseltlc { get; set; }
    public string Txrescldisa { get; set; }
    public string Ddlauttlc { get; set; }
}

[WebMethod]
[ScriptMethod]
public static void Savepnfasi(pnfasiweb fasi)
{
    if (!String.IsNullOrEmpty(HttpContext.Current.Request.QueryString["id"]))
    {
        string ProductID = Mpskmt3.Base64ForUrlDecode(HttpContext.Current.Request.QueryString["id"].ToString());

        string sql = String.Format(@" UPDATE `dotable` ");
        sql += String.Format(" SET ");
        sql += String.Format(" Aut = ?, ");
        sql += String.Format(" Res = ?, ");
        sql += String.Format(" Dur = ?, ");
        sql += String.Format(" Comp = CASE WHEN Comp IS NULL THEN ? ELSE CONCAT(Comp, '; ', ?) END, ");
        sql += String.Format(" doDateHour = CURRENT_TIMESTAMP() ");
        sql += String.Format(" WHERE ID = ?; ");

        using (OdbcConnection cn =
                new OdbcConnection(ConfigurationManager.ConnectionStrings["ConnMySQLlocalhost"].ConnectionString))
        {
            using (OdbcCommand command =
                    new OdbcCommand(sql, cn))
            {
                try
                {
                    command.Connection.Open();
                    command.Parameters.AddWithValue("param1", fasi.Ddlauttlc.ToString());
                    command.Parameters.AddWithValue("param2", Convert.ToInt32(fasi.Txrescldisa.ToString()));
                    command.Parameters.AddWithValue("param3", Convert.ToInt32(fasi.Txseltlc.ToString()));
                    command.Parameters.AddWithValue("param4", Mpskmt3.Container.TheObjectPropertyName);
                    command.Parameters.AddWithValue("param5", Mpskmt3.Container.TheObjectPropertyName);
                    command.Parameters.AddWithValue("param6", ProductID.ToString());
                    command.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    command.Connection.Close();
                }
            }
        }
    }
    else
    {
       //Error
    }
}
</code>```

#Edit01

答:
Try this :</p>

```<code>var qString = "?" + window.location.href.split("?")[1];
var fasi = {};

...

url: "Default.aspx/Savepnfasi" + qString,
data: '{fasi: ' + JSON.stringify(fasi) + '}',
</code>```

Body:
I'm trying to pass parameters to my code behind with WebMethod.

I'm reaching the success end of ajax but the method in my aspx.cs code behind doesn't get called and I have error.

Operation failed! Details :'[object Object]

I'm using a masterpage if it makes a difference.

How to do resolve this ?

Please, can you help me ?

Javascript:

code behind :

public class pnfasiweb
{
    public string Txseltlc { get; set; }
    public string Txrescldisa { get; set; }
    public string Ddlauttlc { get; set; }
}

[WebMethod]
[ScriptMethod]
public static void Savepnfasi(pnfasiweb fasi)
{
    if (!String.IsNullOrEmpty(HttpContext.Current.Request.QueryString["id"]))
    {
        string ProductID = Mpskmt3.Base64ForUrlDecode(HttpContext.Current.Request.QueryString["id"].ToString());

        string sql = String.Format(@" UPDATE `dotable` ");
        sql += String.Format(" SET ");
        sql += String.Format(" Aut = ?, ");
        sql += String.Format(" Res = ?, ");
        sql += String.Format(" Dur = ?, ");
        sql += String.Format(" Comp = CASE WHEN Comp IS NULL THEN ? ELSE CONCAT(Comp, '; ', ?) END, ");
        sql += String.Format(" doDateHour = CURRENT_TIMESTAMP() ");
        sql += String.Format(" WHERE ID = ?; ");

        using (OdbcConnection cn =
                new OdbcConnection(ConfigurationManager.ConnectionStrings["ConnMySQLlocalhost"].ConnectionString))
        {
            using (OdbcCommand command =
                    new OdbcCommand(sql, cn))
            {
                try
                {
                    command.Connection.Open();
                    command.Parameters.AddWithValue("param1", fasi.Ddlauttlc.ToString());
                    command.Parameters.AddWithValue("param2", Convert.ToInt32(fasi.Txrescldisa.ToString()));
                    command.Parameters.AddWithValue("param3", Convert.ToInt32(fasi.Txseltlc.ToString()));
                    command.Parameters.AddWithValue("param4", Mpskmt3.Container.TheObjectPropertyName);
                    command.Parameters.AddWithValue("param5", Mpskmt3.Container.TheObjectPropertyName);
                    command.Parameters.AddWithValue("param6", ProductID.ToString());
                    command.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    command.Connection.Close();
                }
            }
        }
    }
    else
    {
       //Error
    }
}

#Edit01

Body:
Try this :

var qString = "?" + window.location.href.split("?")[1];
var fasi = {};

...

url: "Default.aspx/Savepnfasi" + qString,
data: '{fasi: ' + JSON.stringify(fasi) + '}',


问:
How to to display images according to id (Filters)
I want to display images in a div according to select option (onclick = "DispImg())
I get 2 problem's

I store the images in array and I display all of theme and when you select an option it will automatically display the images that have the correct id .

and this is my script : I want to add to every image an id but the (setAttribute) method dosn't work and when you chose what id the script will display only the images that have the same id .

var imgArray = new Array();

var corp = document.getElementById('range_imgs');

imgArray[0] = new Image();
imgArray[0].src = "https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.futura-sciences.com%2Fsciences%2Fdefinitions%2Funivers-etoile-3730%2F&psig=AOvVaw2EmQPZg6y4m5Ap-jl4oKQv&ust=1582208140734000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKjQluTm3ecCFQAAAAAdAAAAABAD";
imgArray[0].setAttribute("id" , "2");

imgArray[1] = new Image();
imgArray[1].src = "https://www.google.com/url?sa=i&url=http%3A%2F%2Fvivre-marrakech.com%2Fblog%2Ffaire%2Fobserver-les-etoiles-a-marrakech%2F&psig=AOvVaw2EmQPZg6y4m5Ap-jl4oKQv&ust=1582208140734000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKjQluTm3ecCFQAAAAAdAAAAABAI";
imgArray[1].setAttribute("id" , "1");

imgArray[2] = new Image();
imgArray[2].src = "https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.numerama.com%2Fsciences%2F537548-au-lieu-detre-avalee-par-un-trou-noir-cette-etoile-sest-echappee-a-toute-vitesse.html&psig=AOvVaw2EmQPZg6y4m5Ap-jl4oKQv&ust=1582208140734000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKjQluTm3ecCFQAAAAAdAAAAABAN";
imgArray[2].setAttribute("id" , "3");

imgArray[3] = new Image();
imgArray[3].src = "https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.geowiki.fr%2Findex.php%3Ftitle%3D%25C3%2589toile&psig=AOvVaw2EmQPZg6y4m5Ap-jl4oKQv&ust=1582208140734000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKjQluTm3ecCFQAAAAAdAAAAABAS";
imgArray[3].setAttribute("id" , "2");

imgArray[4] = new Image();
imgArray[4].src = "https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.futura-sciences.com%2Fsciences%2Fquestions-reponses%2Fespace-quest-ce-quune-etoile-157%2F&psig=AOvVaw2EmQPZg6y4m5Ap-jl4oKQv&ust=1582208140734000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKjQluTm3ecCFQAAAAAdAAAAABAX";
imgArray[4].setAttribute("id" , "1");

  for(var i=0;i<imgArray.length;i++){
    var imges = document.createElement("img");
      imges.src = imgArray[i].src;
      imges.style.marginRight = "15px";
      corp.appendChild(imges);
  }

  function appFilter(ele){

      var pics = document.querySelectorAll("img");

          if(pics.id == "1"){

          }

  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <select id="allimgs" name="allimmages" >
      <option value="1et" onclick="appfilter(1)">img with id=1</option>
      <option value="2et" onclick="appfilter(2)">img with id=2</option>
      <option value="3et" onclick="appfilter(3)">img with id=3</option>
  </select>
</form>
<div id="range_imgs">
</div></code>```

Thank you !!

答:
I would not use id to store that value, because you are writing those to the DOM and all id properties must be unique.  Use a helper attribute like data-id.

var imgArray = new Array();

imgArray[0] = new Image();
imgArray[0].src = "https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.futura-sciences.com%2Fsciences%2Fdefinitions%2Funivers-etoile-3730%2F&psig=AOvVaw2EmQPZg6y4m5Ap-jl4oKQv&ust=1582208140734000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKjQluTm3ecCFQAAAAAdAAAAABAD";
imgArray[0].setAttribute("data-id", "2");

imgArray[1] = new Image();
imgArray[1].src = "https://www.google.com/url?sa=i&url=http%3A%2F%2Fvivre-marrakech.com%2Fblog%2Ffaire%2Fobserver-les-etoiles-a-marrakech%2F&psig=AOvVaw2EmQPZg6y4m5Ap-jl4oKQv&ust=1582208140734000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKjQluTm3ecCFQAAAAAdAAAAABAI";
imgArray[1].setAttribute("data-id", "1");

imgArray[2] = new Image();
imgArray[2].src = "https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.numerama.com%2Fsciences%2F537548-au-lieu-detre-avalee-par-un-trou-noir-cette-etoile-sest-echappee-a-toute-vitesse.html&psig=AOvVaw2EmQPZg6y4m5Ap-jl4oKQv&ust=1582208140734000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKjQluTm3ecCFQAAAAAdAAAAABAN";
imgArray[2].setAttribute("data-id", "3");

imgArray[3] = new Image();
imgArray[3].src = "https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.geowiki.fr%2Findex.php%3Ftitle%3D%25C3%2589toile&psig=AOvVaw2EmQPZg6y4m5Ap-jl4oKQv&ust=1582208140734000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKjQluTm3ecCFQAAAAAdAAAAABAS";
imgArray[3].setAttribute("data-id", "2");

imgArray[4] = new Image();
imgArray[4].src = "https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.futura-sciences.com%2Fsciences%2Fquestions-reponses%2Fespace-quest-ce-quune-etoile-157%2F&psig=AOvVaw2EmQPZg6y4m5Ap-jl4oKQv&ust=1582208140734000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKjQluTm3ecCFQAAAAAdAAAAABAX";
imgArray[4].setAttribute("data-id", "1");

const corp = document.getElementById('range_imgs');

// set margin
imgArray.forEach(
  img => img.style.setProperty("margin-right", "15px")
);

// append all to document
imgArray.forEach(
  img => corp.appendChild(img)
);

// hide/show functions
const hide = el => el.style.setProperty("display", "none");
const show = el => el.style.setProperty("display", "unset");

// get selected ID
const select = document.getElementById("allimgs");
const getSelectedId = () => select.options[select.selectedIndex].getAttribute("data-id");

// remove all images with non-selected IDs
const filterImages = () => document.querySelectorAll("#range_imgs > img").forEach(
  child => getSelectedId() == child.getAttribute("data-id")
    ? show(child)
    : hide(child)
);

// run on pageload
window.addEventListener("load", filterImages);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <select id="allimgs" name="allimmages" onchange="filterImages(this)">
    <option value="1et" data-id="1">img with id=1</option>
    <option value="2et" data-id="2">img with id=2</option>
    <option value="3et" data-id="3">img with id=3</option>
  </select>
</form>
<div id="range_imgs">
</div></code>```

Body:
I want to display images in a div according to select option (onclick = "DispImg())
I get 2 problem's

I store the images in array and I display all of theme and when you select an option it will automatically display the images that have the correct id .

and this is my script : I want to add to every image an id but the (setAttribute) method dosn't work and when you chose what id the script will display only the images that have the same id .

var imgArray = new Array();

var corp = document.getElementById('range_imgs');

imgArray[0] = new Image();
imgArray[0].src = "https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.futura-sciences.com%2Fsciences%2Fdefinitions%2Funivers-etoile-3730%2F&psig=AOvVaw2EmQPZg6y4m5Ap-jl4oKQv&ust=1582208140734000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKjQluTm3ecCFQAAAAAdAAAAABAD";
imgArray[0].setAttribute("id" , "2");

imgArray[1] = new Image();
imgArray[1].src = "https://www.google.com/url?sa=i&url=http%3A%2F%2Fvivre-marrakech.com%2Fblog%2Ffaire%2Fobserver-les-etoiles-a-marrakech%2F&psig=AOvVaw2EmQPZg6y4m5Ap-jl4oKQv&ust=1582208140734000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKjQluTm3ecCFQAAAAAdAAAAABAI";
imgArray[1].setAttribute("id" , "1");

imgArray[2] = new Image();
imgArray[2].src = "https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.numerama.com%2Fsciences%2F537548-au-lieu-detre-avalee-par-un-trou-noir-cette-etoile-sest-echappee-a-toute-vitesse.html&psig=AOvVaw2EmQPZg6y4m5Ap-jl4oKQv&ust=1582208140734000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKjQluTm3ecCFQAAAAAdAAAAABAN";
imgArray[2].setAttribute("id" , "3");

imgArray[3] = new Image();
imgArray[3].src = "https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.geowiki.fr%2Findex.php%3Ftitle%3D%25C3%2589toile&psig=AOvVaw2EmQPZg6y4m5Ap-jl4oKQv&ust=1582208140734000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKjQluTm3ecCFQAAAAAdAAAAABAS";
imgArray[3].setAttribute("id" , "2");

imgArray[4] = new Image();
imgArray[4].src = "https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.futura-sciences.com%2Fsciences%2Fquestions-reponses%2Fespace-quest-ce-quune-etoile-157%2F&psig=AOvVaw2EmQPZg6y4m5Ap-jl4oKQv&ust=1582208140734000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKjQluTm3ecCFQAAAAAdAAAAABAX";
imgArray[4].setAttribute("id" , "1");

  for(var i=0;i<imgArray.length;i++){
    var imges = document.createElement("img");
      imges.src = imgArray[i].src;
      imges.style.marginRight = "15px";
      corp.appendChild(imges);
  }

  function appFilter(ele){

      var pics = document.querySelectorAll("img");

          if(pics.id == "1"){

          }

  }

<form>
  <select id="allimgs" name="allimmages" >
      <option value="1et" onclick="appfilter(1)">img with id=1</option>
      <option value="2et" onclick="appfilter(2)">img with id=2</option>
      <option value="3et" onclick="appfilter(3)">img with id=3</option>
  </select>
</form>

Thank you !!

Body:
I would not use id to store that value, because you are writing those to the DOM and all id properties must be unique.  Use a helper attribute like data-id.

var imgArray = new Array();

imgArray[0] = new Image();
imgArray[0].src = "https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.futura-sciences.com%2Fsciences%2Fdefinitions%2Funivers-etoile-3730%2F&psig=AOvVaw2EmQPZg6y4m5Ap-jl4oKQv&ust=1582208140734000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKjQluTm3ecCFQAAAAAdAAAAABAD";
imgArray[0].setAttribute("data-id", "2");

imgArray[1] = new Image();
imgArray[1].src = "https://www.google.com/url?sa=i&url=http%3A%2F%2Fvivre-marrakech.com%2Fblog%2Ffaire%2Fobserver-les-etoiles-a-marrakech%2F&psig=AOvVaw2EmQPZg6y4m5Ap-jl4oKQv&ust=1582208140734000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKjQluTm3ecCFQAAAAAdAAAAABAI";
imgArray[1].setAttribute("data-id", "1");

imgArray[2] = new Image();
imgArray[2].src = "https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.numerama.com%2Fsciences%2F537548-au-lieu-detre-avalee-par-un-trou-noir-cette-etoile-sest-echappee-a-toute-vitesse.html&psig=AOvVaw2EmQPZg6y4m5Ap-jl4oKQv&ust=1582208140734000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKjQluTm3ecCFQAAAAAdAAAAABAN";
imgArray[2].setAttribute("data-id", "3");

imgArray[3] = new Image();
imgArray[3].src = "https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.geowiki.fr%2Findex.php%3Ftitle%3D%25C3%2589toile&psig=AOvVaw2EmQPZg6y4m5Ap-jl4oKQv&ust=1582208140734000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKjQluTm3ecCFQAAAAAdAAAAABAS";
imgArray[3].setAttribute("data-id", "2");

imgArray[4] = new Image();
imgArray[4].src = "https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.futura-sciences.com%2Fsciences%2Fquestions-reponses%2Fespace-quest-ce-quune-etoile-157%2F&psig=AOvVaw2EmQPZg6y4m5Ap-jl4oKQv&ust=1582208140734000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCKjQluTm3ecCFQAAAAAdAAAAABAX";
imgArray[4].setAttribute("data-id", "1");

const corp = document.getElementById('range_imgs');

// set margin
imgArray.forEach(
  img => img.style.setProperty("margin-right", "15px")
);

// append all to document
imgArray.forEach(
  img => corp.appendChild(img)
);

// hide/show functions
const hide = el => el.style.setProperty("display", "none");
const show = el => el.style.setProperty("display", "unset");

// get selected ID
const select = document.getElementById("allimgs");
const getSelectedId = () => select.options[select.selectedIndex].getAttribute("data-id");

// remove all images with non-selected IDs
const filterImages = () => document.querySelectorAll("#range_imgs > img").forEach(
  child => getSelectedId() == child.getAttribute("data-id")
    ? show(child)
    : hide(child)
);

// run on pageload
window.addEventListener("load", filterImages);

<form>
  <select id="allimgs" name="allimmages" onchange="filterImages(this)">
    <option value="1et" data-id="1">img with id=1</option>
    <option value="2et" data-id="2">img with id=2</option>
    <option value="3et" data-id="3">img with id=3</option>
  </select>
</form>
<div id="range_imgs">
</div>


问:
generate hash key (unique identifier column in dataframe) in spark dataframe
I have table consisting > 100k rows. I need to generate unique id from the concatenated columns which will be unique. I have tried md5 function, which works fine for less data, but for huge data values are getting duplicated.
Can you please provide any alternate solution or how i can make it proper to 100k data rows.

```<code>val df = Seq(
              ("Veg", "tomato", 1.99),
              ("Veg", "potato", 0.45),
              ("Fruit", "apple", 0.99),
              ("Fruit", "pineapple", 2.59)
               ).toDF("Type", "Item", "Price")

df.withColumn("hash_value",md5(concat($"Type",$"Item",$"Price"))).show(false)

+-----+---------+-----+--------------------------------+
|Type |Item     |Price|hash_value                      |
+-----+---------+-----+--------------------------------+
|Veg  |tomato   |1.99 |82215bc9c2078d2f1e773ad62b4f88c6|
|Veg  |potato   |0.45 |5c68bcadcbfdedf8b8c6edca20fd5126|
|Fruit|apple    |0.99 |830a70f1c16f015aa54ca24d9ea6ce0b|
|Fruit|pineapple|2.59 |1f0974817391905d41224e76735fc5d4|
+-----+---------+-----+--------------------------------+
</code>```

How to create unique identifier for the concatenated column?

答:
I advice you sha 256 or 512 to avoid colision :

df.withColumn(
    "hash_value",
    F.sha2(
        F.concat(*(
            F.col(col).cast("string")
            for col
            in df.columns
        )),
        256
    )
).show()
```

Body:
I have table consisting > 100k rows. I need to generate unique id from the concatenated columns which will be unique. I have tried md5 function, which works fine for less data, but for huge data values are getting duplicated.
Can you please provide any alternate solution or how i can make it proper to 100k data rows.

val df = Seq(
              ("Veg", "tomato", 1.99),
              ("Veg", "potato", 0.45),
              ("Fruit", "apple", 0.99),
              ("Fruit", "pineapple", 2.59)
               ).toDF("Type", "Item", "Price")

df.withColumn("hash_value",md5(concat($"Type",$"Item",$"Price"))).show(false)

+-----+---------+-----+--------------------------------+
|Type |Item     |Price|hash_value                      |
+-----+---------+-----+--------------------------------+
|Veg  |tomato   |1.99 |82215bc9c2078d2f1e773ad62b4f88c6|
|Veg  |potato   |0.45 |5c68bcadcbfdedf8b8c6edca20fd5126|
|Fruit|apple    |0.99 |830a70f1c16f015aa54ca24d9ea6ce0b|
|Fruit|pineapple|2.59 |1f0974817391905d41224e76735fc5d4|
+-----+---------+-----+--------------------------------+

How to create unique identifier for the concatenated column?


问:
SQL show column of number of duplicates
I have a table like this

How could I sum up the number of similar rows and put that into a new column? I tried to use select distinct but did not give the expected result

答:
If I didn't misunderstand your question, a simple count(*) with a group by will do the trick:

```<code>SELECT EXTRACT(MONTH FROM issue_date) AS month,
    EXTRACT(YEAR FROM issue_date) AS year, count(*) as n
FROM ticket
GROUP BY EXTRACT(YEAR FROM issue_date), EXTRACT(MONTH FROM issue_date)
ORDER BY year, month;
</code>```

Title: SQL show column of number of duplicates

Body:
If I didn't misunderstand your question, a simple count(*) with a group by will do the trick:

SELECT EXTRACT(MONTH FROM issue_date) AS month,
    EXTRACT(YEAR FROM issue_date) AS year, count(*) as n
FROM ticket
GROUP BY EXTRACT(YEAR FROM issue_date), EXTRACT(MONTH FROM issue_date)
ORDER BY year, month;


问:
Greatest of 3 numbers code not working for specific numbers
I'm a beginner to Python. I have written code to find the greatest of 3 numbers which is working fine other than these numbers 100,10,20 which are provided as input. I'm getting the output as "The largest number is 20" but my expectation is is should be "The largest number is 100"
My code is as follows:

```<code>a = input("Enter 1st value")
b = input("Enter 2nd value")
c = input("Enter 3rd value")

if (a > b) and (a > c):
    lnum = a

elif (b > a) and (b > c):
    lnum = b

else:
    lnum = c

print("The largest number is", lnum)
</code>```

Can anyone help me to understand why the output is showing 20 as greatest instead of 100?

答:
Your inputs are strings and are sorted by comparing the characters left to right.

Comparing "100" against "20" first compares "1" and "2". "1" is smaller so your code picks "20" as the larger value.

As others have mentioned if you convert the input to integer using int(input('Enter 1st value ') then it will work as you intended and there is a max() function you can use.

Note: There still is another mistake in your code:

```<code>Enter 1st value20
Enter 2nd value20
Enter 3rd value10
('The largest number is', 10)
</code>```

The check for (b > a) is wrong and causes you to output c if a == b.

Body:
I'm a beginner to Python. I have written code to find the greatest of 3 numbers which is working fine other than these numbers 100,10,20 which are provided as input. I'm getting the output as "The largest number is 20" but my expectation is is should be "The largest number is 100"
My code is as follows:

a = input("Enter 1st value")
b = input("Enter 2nd value")
c = input("Enter 3rd value")

if (a > b) and (a > c):
    lnum = a

elif (b > a) and (b > c):
    lnum = b

else:
    lnum = c

print("The largest number is", lnum)

Can anyone help me to understand why the output is showing 20 as greatest instead of 100?

Body:
Your inputs are strings and are sorted by comparing the characters left to right.

Comparing "100" against "20" first compares "1" and "2". "1" is smaller so your code picks "20" as the larger value.

As others have mentioned if you convert the input to integer using int(input('Enter 1st value ') then it will work as you intended and there is a max() function you can use.

Note: There still is another mistake in your code:

Enter 1st value20
Enter 2nd value20
Enter 3rd value10
('The largest number is', 10)

The check for (b > a) is wrong and causes you to output c if a == b.


问:
Problem in Angular 8 iterating non-empty array
I'm having a rather strange problem fetching an array using http requests in Angular 8.
The request looks like this:

```<code>getPort(): any {
return this.http.get(this.portsApiUrl).toPromise().then(data => {
    let masterSchedule = data["masterSchedule"];
          for (const d of masterSchedule as any) {
            this.portList.push(d);
          }
});
</code>```

This code works fine, and it retrieves the list of ports in a timely manner; I then pass it to another component using @Input. The list gets to the component fine; if I log it through the console on the OnInit method of said component, the list is shown correctly.

The problem occurs when I try to iterate over the list using ngFor. Trying to pass the html the {{item.departurePort}} (which is the correct variable name, since I can see the objects in the array and their respective variables' names) will end up throwing an undefined error.
Calling portList.length within the component at any time, however, will show the correct number of elements within the array.
It is very strange, to be honest. Here's the console log of the list being printed in the onInit method:

And here's the error:

Just in case, here's the html code that iterates over the array:

```<code><div class="col-lg-12 col-md-12 col-sm-12 d-flex justify-content-center">
<ul class="flags">
  <li ngFor="let item of portList">
    <p><a style="color: #656D78;">{{item.departurePort}}</a>
        </p>
  </li>
</ul>
</code>```

Any ideas?

答:
It is possible to see what item has properties by using json pipe:

```<code><li *ngFor="let item of portList">
    <p>
        <a style="color: #656D78;">{{item | json}}</a>
    </p>
</li>
</code>```

Based on this you can write desired property. In addition, you can use ?. operator to prevent errors:

```<code><li *ngFor="let item of portList">
    <p>
        <a style="color: #656D78;">{{item?.yourPropertyName }}</a>
    </p>
</code>```

Body:
I'm having a rather strange problem fetching an array using http requests in Angular 8.
The request looks like this:

getPort(): any {
return this.http.get(this.portsApiUrl).toPromise().then(data => {
    let masterSchedule = data["masterSchedule"];
          for (const d of masterSchedule as any) {
            this.portList.push(d);
          }
});

This code works fine, and it retrieves the list of ports in a timely manner; I then pass it to another component using @Input. The list gets to the component fine; if I log it through the console on the OnInit method of said component, the list is shown correctly.

The problem occurs when I try to iterate over the list using ngFor. Trying to pass the html the {{item.departurePort}} (which is the correct variable name, since I can see the objects in the array and their respective variables' names) will end up throwing an undefined error.
Calling portList.length within the component at any time, however, will show the correct number of elements within the array.
It is very strange, to be honest. Here's the console log of the list being printed in the onInit method:

And here's the error:

Just in case, here's the html code that iterates over the array:

{{item.departurePort}}

Any ideas?

Body:
It is possible to see what item has properties by using json pipe:

<li *ngFor="let item of portList">
    <p>
        <a style="color: #656D78;">{{item | json}}</a>
    </p>
</li>

Based on this you can write desired property. In addition, you can use ?. operator to prevent errors:

<li *ngFor="let item of portList">
    <p>
        <a style="color: #656D78;">{{item?.yourPropertyName }}</a>
    </p>


问:
Custom sequence in Hibernate that should reset yearly
I'm working on simple application that uses Spring MVC 3 and hibernate 3.

I have a requirement to generate ID in the following format.

```<code>Month/Year/number(number will increase).
</code>```

Month and year values do change based on the current Date.
Once the year completed, let say after the completion of one financial year the sequence again start from the beginning, like month/Year/number. Hope I'm clear.

Example:

```<code>1st Financial Year:
Mar/2011/001
Jun/2011/002
Dec/2011/003
Feb/2011/004
...
...

2nd Financial Year:
Mar/2012/001
Mar/2012/002
Aug/2012/003
..
..
..
</code>```

How can I approach this problem?
Please help me.

答:
Create a custom sequence generator. You will need to keep somewhere a record that stores the year of the last record saved. Each time you want to gerenate a new identifier check that value and if the last record saved is not from this year update that value and recreate the sequence being used underneath. If that value is not yet set you can calculate it querying the date of the newest record.

A bit of pseudocode :P

```<code>public class CustomSequenceGenerator extends SequenceStyleGenerator {

    private static Integer lastYear = null;

    public CustomSequenceGenerator (){
        super();
    }

    @Override
    public Serializable generate(SessionImplementor sessionImplementator, Object object) throws HibernateException {
        Long id = (Long)super.generate(sessionImplementator, object);
        if (lastYear == null) {
            getYearOfLastRecord();
        }
        if (lastYear != getThisYear() ) {
           recreateDatabaseSequence();
           lastYear = getThisYear();
        }
        String date = generateStringBasedOnDate();
        return date+id.toString;
    }

// Implement missing methods

[....]
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm working on simple application that uses Spring MVC 3 and hibernate 3.

I have a requirement to generate ID in the following format.

Month/Year/number(number will increase).

Month and year values do change based on the current Date.
Once the year completed, let say after the completion of one financial year the sequence again start from the beginning, like month/Year/number. Hope I'm clear.

Example:

1st Financial Year:
Mar/2011/001
Jun/2011/002
Dec/2011/003
Feb/2011/004
...
...

2nd Financial Year:
Mar/2012/001
Mar/2012/002
Aug/2012/003
..
..
..

How can I approach this problem?
Please help me.

Body:
Create a custom sequence generator. You will need to keep somewhere a record that stores the year of the last record saved. Each time you want to gerenate a new identifier check that value and if the last record saved is not from this year update that value and recreate the sequence being used underneath. If that value is not yet set you can calculate it querying the date of the newest record.

A bit of pseudocode :P

public class CustomSequenceGenerator extends SequenceStyleGenerator {

    private static Integer lastYear = null;

    public CustomSequenceGenerator (){
        super();
    }

    @Override
    public Serializable generate(SessionImplementor sessionImplementator, Object object) throws HibernateException {
        Long id = (Long)super.generate(sessionImplementator, object);
        if (lastYear == null) {
            getYearOfLastRecord();
        }
        if (lastYear != getThisYear() ) {
           recreateDatabaseSequence();
           lastYear = getThisYear();
        }
        String date = generateStringBasedOnDate();
        return date+id.toString;
    }

// Implement missing methods

[....]
}


答:
```<code>SELECT DISTINCT EXTRACT(MONTH FROM issue_date) AS month,
    EXTRACT(YEAR FROM issue_date) AS year,
     count(*)
FROM ticket
GROUP BY EXTRACT(MONTH FROM issue_date),EXTRACT(YEAR FROM issue_date)
ORDER BY year, month;
</code>```

Title: SQL show column of number of duplicates

Body:
I have a table like this

How could I sum up the number of similar rows and put that into a new column? I tried to use select distinct but did not give the expected result


问:
How to provide fixed 'key values' within a class?
I'm new to C#, and this is a very simple question, but as I can't figure out the right terminology for what I'm looking for, I'm struggling to google this for the simple answer.

I'd like the user of a class to be able to retrieve certain fixed values by name from within the class. As below:

```<code>byte mode = MyClass.Modes.ModeC;
</code>```

Where ModeC is a specific value of byte that the user will need to use.

I've seen this used everywhere, but I can't figure out what the best way to implement it is.

I've tried:

```<code>public class MyClass
{
    public class Modes
    {
        public static byte ModeA = 0x01;
        public static byte ModeB = 0x03;
        public static byte ModeC = 0x06;
        //etc
    }
}
</code>```

It seems to work.
Is this a sensible way to achieve this? What is this practice called?

Sorry for the very obvious question, but I'd appreciate any help I could get!

答:
Is this what you're looking for?</p>

```<code>using System;

class MainClass {
  public static void Main (string[] args) {
    Console.WriteLine ("Value of " + Modes.ModeC + " is " + (byte)Modes.ModeC);
  }

  public enum Modes : byte {

    ModeA = 0x01,
    ModeB = 0x03,
    ModeC = 0x05

  }
}
</code>```

Body:
I'm new to C#, and this is a very simple question, but as I can't figure out the right terminology for what I'm looking for, I'm struggling to google this for the simple answer.

I'd like the user of a class to be able to retrieve certain fixed values by name from within the class. As below:

byte mode = MyClass.Modes.ModeC;

Where ModeC is a specific value of byte that the user will need to use.

I've seen this used everywhere, but I can't figure out what the best way to implement it is.

I've tried:

public class MyClass
{
    public class Modes
    {
        public static byte ModeA = 0x01;
        public static byte ModeB = 0x03;
        public static byte ModeC = 0x06;
        //etc
    }
}

It seems to work.
Is this a sensible way to achieve this? What is this practice called?

Sorry for the very obvious question, but I'd appreciate any help I could get!

Body:
Is this what you're looking for?

using System;

class MainClass {
  public static void Main (string[] args) {
    Console.WriteLine ("Value of " + Modes.ModeC + " is " + (byte)Modes.ModeC);
  }

  public enum Modes : byte {

    ModeA = 0x01,
    ModeB = 0x03,
    ModeC = 0x05

  }
}


问:
Laravel validations with "or" condition
I'm trying to make an input validation in Laravel with a somewhat complex "or" condition.

I need the validator to validate the input (let it pass) if its value is present in a specific table or if its value is "other".

So far, I have:

```<code>$validator = Validator::make($data, [

    ...

    'doc_organization' => ['required_with:rb_regist,doctor, exists:user_organizations,full_name'], // TODO: must exist in user_organizations table or be "other"
    'doc_custom_organization' => ['required_if:doc_organization,other', 'max:160'],

    ...
</code>```

I took a look at Laravel's custom validation rules, conditionally adding rules, and so forth, as well as these posts:

Laravel Validation with or

Validation rules required_if with other condition (Laravel 5.4)

But I can't seem to come up with a custom rule in which I don't query the whole table to know if the name exists (in case it is not "other"). That would make the rule too complex for its purpose.

The other solution I have is to add an entry named "other" in the user_organizations table, which is not ideal.

Am I missing something?
How can I make the condition I want without a complex custom validation rule?

Thank you very much.

答:
Since "other" is just a value and not a record in your database you can simply "twist it" a bit to something like:

```<code>'doc_organization' => ['nullable|required_with:rb_regist,doctor, exists:user_organizations,full_name'],
</code>```

The twist is that before your Validator you can have a simple check in your requested value like:

```<code>if($request->doc_organization == "other"){
  $request->merge(['doc_organization' => null]);
}
</code>```

And inject null value to the field inside the request.

Having done that you will comply with "nullable" option which will allow you to pass through.

Title: Laravel validations with "or" condition

Body:
I'm trying to make an input validation in Laravel with a somewhat complex "or" condition.

I need the validator to validate the input (let it pass) if its value is present in a specific table or if its value is "other".

So far, I have:

$validator = Validator::make($data, [

    ...

    'doc_organization' => ['required_with:rb_regist,doctor, exists:user_organizations,full_name'], // TODO: must exist in user_organizations table or be "other"
    'doc_custom_organization' => ['required_if:doc_organization,other', 'max:160'],

    ...

I took a look at Laravel's custom validation rules, conditionally adding rules, and so forth, as well as these posts:

Laravel Validation with or

Validation rules required_if with other condition (Laravel 5.4)

But I can't seem to come up with a custom rule in which I don't query the whole table to know if the name exists (in case it is not "other"). That would make the rule too complex for its purpose.

The other solution I have is to add an entry named "other" in the user_organizations table, which is not ideal.

Am I missing something?
How can I make the condition I want without a complex custom validation rule?

Thank you very much.

Body:
Since "other" is just a value and not a record in your database you can simply "twist it" a bit to something like:

'doc_organization' => ['nullable|required_with:rb_regist,doctor, exists:user_organizations,full_name'],

The twist is that before your Validator you can have a simple check in your requested value like:

if($request->doc_organization == "other"){
  $request->merge(['doc_organization' => null]);
}

And inject null value to the field inside the request.

Having done that you will comply with "nullable" option which will allow you to pass through.


问:
log X amount not in a loop
I'm using Javascript trying to log the same string multiple times. Is there a way to do this without iterating through a loop? When I try it with a loop it logs the string 4 times adding to it each time.

I want to log the string once, but with all four items in it.

For example, I want:

```<code>0000
</code>```

and not:

```<code>0
00
000
0000
</code>```

Here's what I've tried:

var string = ''

function zero(x) {
  for (i = 0; i <= 3; i++) {
    console.log(string += x)
  }
}

zero('0')```

Is it possible to skip logging the first three outputs and just log 0000 on one line?

答:
Have log outside the loop. Also it is good practice to use semi-columns</p>

```<code>var string = '';

function zero(x) {
    for (i=0; i<=3; i++) {
       string += x;
    }
   console.log(string);
}

zero('0');
</code>```

Title: log X amount not in a loop

Body:
I'm using Javascript trying to log the same string multiple times. Is there a way to do this without iterating through a loop? When I try it with a loop it logs the string 4 times adding to it each time.

I want to log the string once, but with all four items in it.

For example, I want:

0000

and not:

0
00
000
0000

Here's what I've tried:

var string = ''

function zero(x) {
  for (i = 0; i <= 3; i++) {
    console.log(string += x)
  }
}

zero('0')

Is it possible to skip logging the first three outputs and just log 0000 on one line?

Body:
Have log outside the loop. Also it is good practice to use semi-columns

var string = '';

function zero(x) {
    for (i=0; i<=3; i++) {
       string += x;
    }
   console.log(string);
}

zero('0');


答:
In your template you should use "?" :

```<code><li *ngFor="let item of portList">
    <p><a style="color: #656D78;">{{item?.departurePort}}</a>
        </p>
 </li>
</code>```

also you may want to use Observables instead of promise, it's way more powerful.

Title: Problem in Angular 8 iterating non-empty array

Body:
In your template you should use "?" :

<li *ngFor="let item of portList">
    <p><a style="color: #656D78;">{{item?.departurePort}}</a>
        </p>
 </li>

also you may want to use Observables instead of promise, it's way more powerful.


问:
android:visibility changes to children of MotionLayout
I must be missing something with android:visibility changes within a motion layout. Here’s a simplified version of my layout.

```<code><MotionLayout>
 <ImageView android:id="@+id/HeaderBackground" />
Bunch of image views, Text views that are constrainted to the HeaderBackground.
<RecyclerView android:visibility="visible">
<EditText android:visibility="visible">
<CustomViewGroup1 android:visibility="gone">
</MotionLayout>
</code>```

I have a motionScreen that sets a Transition onswipe based on the recycler view to reduce the height of the HeaderBackground and hide some of the images/text views (i.e a collasping toolbar).
However, if there’s some fatal error, I want to show CustomViewGroup1 on top/infront of the RecyclerView but toggling the visibility of the RecyclerView to gone and CustomViewGroup1 to visible doesn’t make the CustomViewGroup1 show.

I could move the CustomViewGroup group out of the MotionLayout and add a framelayout as the root of the activity and hide the whole MotionLayout. But this is less than ideal as I’d have to copy of the toolbar bar and icons. So I guess the question is about visibility changes and potentially z ordering?

I'm using androidx.constraintlayout:constraintlayout:2.0.0-beta2

答:
My approach is to exclude the view from the motion layout, ignore the visibility from the scene so it can be programmatic and also inherit the constraints in the end constraint set.

The documentation mentioned the app:applyMotionScene="boolean" but it doesn't tell you where. It has to be in a PropertySet

Also visibilityMode only worked for me inside a PropertySet as well

```<code><?xml version="1.0" encoding="utf-8"?>
<MotionScene xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:motion="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <Transition
        ...
    </Transition>

    <ConstraintSet android:id="@+id/start">

        <Constraint android:id="@id/viewId">
            <PropertySet
                app:applyMotionScene="false"
                app:visibilityMode="ignore" />
        </Constraint>

    </ConstraintSet>

    <ConstraintSet
        android:id="@+id/end"
        motion:deriveConstraintsFrom="@id/start">
        ...
    </ConstraintSet>

</MotionScene>
</code>```

Careful with the app namespace auto-import from motion scene, that one is wrong you have to use the same that is used on the layouts.

The benefit of this is:

No width, height or constraints in the scene

No need to repeat the properties since is derived from the start constraint set

Body:
I must be missing something with android:visibility changes within a motion layout. Here’s a simplified version of my layout.

<MotionLayout>
 <ImageView android:id="@+id/HeaderBackground" />
Bunch of image views, Text views that are constrainted to the HeaderBackground.
<RecyclerView android:visibility="visible">
<EditText android:visibility="visible">
<CustomViewGroup1 android:visibility="gone">
</MotionLayout>

I have a motionScreen that sets a Transition onswipe based on the recycler view to reduce the height of the HeaderBackground and hide some of the images/text views (i.e a collasping toolbar).
However, if there’s some fatal error, I want to show CustomViewGroup1 on top/infront of the RecyclerView but toggling the visibility of the RecyclerView to gone and CustomViewGroup1 to visible doesn’t make the CustomViewGroup1 show.

I could move the CustomViewGroup group out of the MotionLayout and add a framelayout as the root of the activity and hide the whole MotionLayout. But this is less than ideal as I’d have to copy of the toolbar bar and icons. So I guess the question is about visibility changes and potentially z ordering?

I'm using androidx.constraintlayout:constraintlayout:2.0.0-beta2

Body:
My approach is to exclude the view from the motion layout, ignore the visibility from the scene so it can be programmatic and also inherit the constraints in the end constraint set.

The documentation mentioned the app:applyMotionScene="boolean" but it doesn't tell you where. It has to be in a PropertySet

Also visibilityMode only worked for me inside a PropertySet as well

<?xml version="1.0" encoding="utf-8"?>
<MotionScene xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:motion="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <Transition
        ...
    </Transition>

    <ConstraintSet android:id="@+id/start">

        <Constraint android:id="@id/viewId">
            <PropertySet
                app:applyMotionScene="false"
                app:visibilityMode="ignore" />
        </Constraint>

    </ConstraintSet>

    <ConstraintSet
        android:id="@+id/end"
        motion:deriveConstraintsFrom="@id/start">
        ...
    </ConstraintSet>

</MotionScene>

Careful with the app namespace auto-import from motion scene, that one is wrong you have to use the same that is used on the layouts.

The benefit of this is:

No width, height or constraints in the scene

No need to repeat the properties since is derived from the start constraint set


问:
Android: ZoomIn but keep scale of element
I'm trying to zoom in on an PDF element inside my view but keep the scale of it. When i try to do a zoom animation it changes the scale of the element and i can't zoom out because of that. When the scale is 1 i can easily zoom in and zoom out from it.

I have tried animations (with Animations and Animator)

I have also tried multiple examples but without success..

The point is: can I zoom in on an element like a pinch zoom but with code without messing up the scale?

Thank You in advance..

答:
You can use this library, first of all you should add this line to gradle,

```<code>implementation 'com.ablanco.zoomy:zoomy:1.1.0'
</code>```

Then you should use this code;

```<code> val builder = Zoomy.Builder(context).
        target(feedDetailImage/* The image you want to zoom */)
        .animateZooming(true)
        .enableImmersiveMode(false)
        .tapListener {
        }
    builder.register()
</code>```

Body:
You can use this library, first of all you should add this line to gradle,

implementation 'com.ablanco.zoomy:zoomy:1.1.0'

Then you should use this code;

 val builder = Zoomy.Builder(context).
        target(feedDetailImage/* The image you want to zoom */)
        .animateZooming(true)
        .enableImmersiveMode(false)
        .tapListener {
        }
    builder.register()


问:
react-native: command not found
I am getting -bash: react-native: command not found error while creating a react-native project.

Below are the additional info

```<code>1. brew --version
   homebrew 0.9.9
2  brew info watchman
   watchman `enter code here`stable 4.50
   /usr/local/Cellar/watchman/4.4.0
3. brew info flow
   stable 0.24.1
   /usr/local/Cellar/flow/0.24.1
4. brew info node
   stable 6.1.0
   /usr/local/Cellar/node/6.1.0
5. npm -version
   3.8.6
6. echo $PATH
/Users/Ashok/.rbenv/shims:/Users/Ashok/.rbenv/shims:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
</code>```

I tried the suggested steps from this link but I am still getting the same error.

I don't have any "npm" directory which they have specified in the solution

```<code>Ashoks-MacBook-Pro:share Ashok$ ls
aclocal     doc     info        ruby-build  zsh
autoconf    emacs       man     systemtap
</code>```

But I found npm file exists in the below location.

```<code>/usr/local/Cellar/node/6.1.0/etc/bash_completion.d
</code>```

I uninstalled react-native and installed it again but I am still facing the same issue.

答:
If you're using yarn, you may have to run commands with yarn in front. Example:

```<code>yarn react-native info
</code>```

Title: react-native: command not found

Body:
I am getting -bash: react-native: command not found error while creating a react-native project.

Below are the additional info

1. brew --version
   homebrew 0.9.9
2  brew info watchman
   watchman `enter code here`stable 4.50
   /usr/local/Cellar/watchman/4.4.0
3. brew info flow
   stable 0.24.1
   /usr/local/Cellar/flow/0.24.1
4. brew info node
   stable 6.1.0
   /usr/local/Cellar/node/6.1.0
5. npm -version
   3.8.6
6. echo $PATH
/Users/Ashok/.rbenv/shims:/Users/Ashok/.rbenv/shims:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin

I tried the suggested steps from this link but I am still getting the same error.

I don't have any "npm" directory which they have specified in the solution

Ashoks-MacBook-Pro:share Ashok$ ls
aclocal     doc     info        ruby-build  zsh
autoconf    emacs       man     systemtap

But I found npm file exists in the below location.

/usr/local/Cellar/node/6.1.0/etc/bash_completion.d

I uninstalled react-native and installed it again but I am still facing the same issue.

Body:
If you're using yarn, you may have to run commands with yarn in front. Example:

yarn react-native info


问:
Jmeter - Russian Characters Encoding Issue
I have an issue with scripting sites that are in dual language - English and Russian.

With Jmeter I post requests to fill a form containing both english and Russian characters, and when I check the application manually, I notice weird ???? symbols everywhere the russian characters are supposed to be.

I have added the utf-8 encoding in jmeter.properties.
sampleresult.default.encoding=UTF-8

Please help suggest.

答:
A simple fix sorted the error :

In the http sampler request, input utf-8(in small characters) against the Content-encoding text window.

Content-Encoding : utf-8

Version: Jmeter 5.2.1
(Left the Port number empty)


问:
Come out of current debug in intellij
I am debugging my java code using intellij-idea.
Is there any way so that after reaching at particular line of code I can come out debug and skip other lines of codes ? (Also my current remote debug connection shouldn't be suspended)
F8 is helping out as its going for next frame.</p>

答:
Remove any breakpoints after a particular code line of yours and use the button "Resume Program"(F9) in Debug window in order to execute the command till the very end. </p>

<p>"View Breakpoints..."(Shift+Ctrl+F8) in that very window is helpful for finding all breakpoints and disabling them.</p>

Title: Come out of current debug in intellij

Body:
Remove any breakpoints after a particular code line of yours and use the button "Resume Program"(F9) in Debug window in order to execute the command till the very end.

"View Breakpoints..."(Shift+Ctrl+F8) in that very window is helpful for finding all breakpoints and disabling them.


问:
How to append a numpy of mixed element types to another array?
I have a numpy array that I am using an if loop to filter out some unwanted entries, and I want to append the entries I want to keep to a new 'filtered array'.

```<code>from astropy.table import Table
import numpy as np

data = '/home/myname/data.fits'
data = Table.read(data, format="fits")

ID = np.array(data['id'])
ID.astype(str)

redshift = np.array(data['z'])
redshift.astype(float)

radius = np.array(data['r'])
radius.astype(float)

mag = np.array(data['magnitude'])
mag.astype(float)

def stack(array1, array2, array3, array4):
    #stacks multiple arrays to have corresponding values next to eachother
    stacked_array = [(array1[i], array2[i], array3[i], array4[i]) for i in range(0, array1.size)]
    stacked_array = np.array(stacked_array)
    return(stacked_array)

stacked = stack(ID, redshift, radius, mag)

filtered_array = np.array([])

for i in stacked:
    if i.any == 'nan':
        np.delete(stacked[i])
    else:
       np.append(filtered_array, stacked[i])
</code>```

When I run this I get the following error:

```<code>IndexError: arrays used as indices must be of integer (or boolean) type
</code>```

Is there any way to append to the new array without getting this error?

答:
I'm a mess turn out I just needed to change the last line from:

```<code>np.append(filtered_array, stacked[i])
</code>```

to

```<code>np.append(filtered_array, i)
</code>```

Body:
I have a numpy array that I am using an if loop to filter out some unwanted entries, and I want to append the entries I want to keep to a new 'filtered array'.

from astropy.table import Table
import numpy as np

data = '/home/myname/data.fits'
data = Table.read(data, format="fits")

ID = np.array(data['id'])
ID.astype(str)

redshift = np.array(data['z'])
redshift.astype(float)

radius = np.array(data['r'])
radius.astype(float)

mag = np.array(data['magnitude'])
mag.astype(float)

def stack(array1, array2, array3, array4):
    #stacks multiple arrays to have corresponding values next to eachother
    stacked_array = [(array1[i], array2[i], array3[i], array4[i]) for i in range(0, array1.size)]
    stacked_array = np.array(stacked_array)
    return(stacked_array)

stacked = stack(ID, redshift, radius, mag)

filtered_array = np.array([])

for i in stacked:
    if i.any == 'nan':
        np.delete(stacked[i])
    else:
       np.append(filtered_array, stacked[i])

When I run this I get the following error:

IndexError: arrays used as indices must be of integer (or boolean) type

Is there any way to append to the new array without getting this error?

Body:
I'm a mess turn out I just needed to change the last line from:

np.append(filtered_array, stacked[i])

to

np.append(filtered_array, i)


问:
Trouble printing float64 value in C
I apologize for any misunderstanding here with data types or the way C operates (I am relatively new to learning still). Can someone explain to me why I am unable to get the desired output (see below)?

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

#define size         10

typedef unsigned int      Uint16;

typedef long double        float64;

Uint16 i;

float64 normalization = 0;

void main() {

  for (i=0;i<size;i++)
  {
     normalization = normalization + i;    // same as "normalization += i;"

     printf("\n --------");
     printf("\n normalization %f", normalization);

  }

  return;
}
</code>```

The console output is the following:

```<code> --------
 normalization 0.000000
 --------
 normalization -0.000000
 --------
 normalization -2.000000
 --------
 normalization -2.000000
 --------
 normalization -0.000000
 --------
 normalization -3105036184601417900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000
 --------
 normalization -0.000000
 --------
 normalization -26815615859885194000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000
 --------
 normalization -0.000000
 --------
 normalization -0.000000
</code>```

I am expecting the output to be:

```<code>normalization = 0
normalization = 1
normalization = 3
normalization = 6
normalization = 10
normalization = 15
// and so forth...
</code>```

答:
A long double cannot be printed with %f. Instead use double, which will work with the printf format specifier %f.

Alternatively, if you really want to use long double, you can use %Lf (case sensitive) to print it.

If you specifically want the output you specified without trailing zeros, you'll have to use %g (for double) or %Lg (for long double; case-sensitive).

Also note that long double is not always 64 bits wide, and unsigned int is not always 16 bits wide. A much better idea than using your float64 and Uint16 would be to simply use the types without typedefs, as you should not assume the widths of the types.

Title: Trouble printing float64 value in C

Body:
I apologize for any misunderstanding here with data types or the way C operates (I am relatively new to learning still). Can someone explain to me why I am unable to get the desired output (see below)?

#include<stdio.h>
#include<math.h>

#define size         10

typedef unsigned int      Uint16;

typedef long double        float64;

Uint16 i;

float64 normalization = 0;

void main() {

  for (i=0;i<size;i++)
  {
     normalization = normalization + i;    // same as "normalization += i;"

     printf("\n --------");
     printf("\n normalization %f", normalization);

  }

  return;
}

The console output is the following:

 --------
 normalization 0.000000
 --------
 normalization -0.000000
 --------
 normalization -2.000000
 --------
 normalization -2.000000
 --------
 normalization -0.000000
 --------
 normalization -3105036184601417900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000
 --------
 normalization -0.000000
 --------
 normalization -26815615859885194000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000
 --------
 normalization -0.000000
 --------
 normalization -0.000000

I am expecting the output to be:

normalization = 0
normalization = 1
normalization = 3
normalization = 6
normalization = 10
normalization = 15
// and so forth...


问:
How to combine types that are being imported from relative path?
I have a project written in TypeScript with custom typings which I'm importing to my .ts modules with import statement:

import { MyCoolInterface } from './types'

When I'm building my project with tsc, I'm getting a declaration file index.d.ts along with index.js and my typings are not getting concatenated with tsc-generated ones. tsc just copies string import { MyCoolInterface } from './types' into the generated declaration file and obviously it's could not be found in my dist directory so typings appears to be broken. Is there a way to concatenate auto-generated types with my own into a single file?

My index.d.ts:

```<code>export interface UmbressOptions {
    isProxyTrusted?: boolean
    rateLimiter?: {
        enabled?: boolean
        requests?: number
        per?: number
        banFor?: number
    }
    clearQueueAfterBan?: boolean
    logs?: boolean
    whitelist?: Array<string>
    blacklist?: Array<string>
    checkSuspiciousAddresses?: {
        enabled?: boolean
        token?: string
        action?: 'block' | 'check'
        banFor?: number
        cookieTtl?: 1
    }
    advancedClientChallenging?: {
        enabled: boolean
        cookieTtl?: number
        content?: string
        userAgentsWhitelist?: RegExp
        cache?: 'redis'
        cacheHost?: string
        cachePort?: number
    }
}
</code>```

Getting merged with tsc-generated index.d.ts:

```<code>/// <reference types="ioredis" />
/// <reference types="express" />
/// <reference types="pug" />
declare module 'abuseipdb' {
    import { UmbressOptions } from './types' // <------------ Import or export declaration in an ambient module declaration cannot reference module through relative module name.ts(2439)
    import { Redis } from 'ioredis'
    export function checkAddress(ip: string, options: UmbressOptions, redis: Redis, jailKey: string): Promise<void>
}
</code>```

答: Change your typings.d.ts file to typings.ts. Typescript ignores .d.ts files when creating the build. For Typescript, all .d.ts are just types declarations, useless to javascript. I hope it helps you!

Body:
I have a project written in TypeScript with custom typings which I'm importing to my .ts modules with import statement:

import { MyCoolInterface } from './types'

When I'm building my project with tsc, I'm getting a declaration file index.d.ts along with index.js and my typings are not getting concatenated with tsc-generated ones. tsc just copies string import { MyCoolInterface } from './types' into the generated declaration file and obviously it's could not be found in my dist directory so typings appears to be broken. Is there a way to concatenate auto-generated types with my own into a single file?

My index.d.ts:

export interface UmbressOptions {
    isProxyTrusted?: boolean
    rateLimiter?: {
        enabled?: boolean
        requests?: number
        per?: number
        banFor?: number
    }
    clearQueueAfterBan?: boolean
    logs?: boolean
    whitelist?: Array<string>
    blacklist?: Array<string>
    checkSuspiciousAddresses?: {
        enabled?: boolean
        token?: string
        action?: 'block' | 'check'
        banFor?: number
        cookieTtl?: 1
    }
    advancedClientChallenging?: {
        enabled: boolean
        cookieTtl?: number
        content?: string
        userAgentsWhitelist?: RegExp
        cache?: 'redis'
        cacheHost?: string
        cachePort?: number
    }
}

Getting merged with tsc-generated index.d.ts:

/// <reference types="ioredis" />
/// <reference types="express" />
/// <reference types="pug" />
declare module 'abuseipdb' {
    import { UmbressOptions } from './types' // <------------ Import or export declaration in an ambient module declaration cannot reference module through relative module name.ts(2439)
    import { Redis } from 'ioredis'
    export function checkAddress(ip: string, options: UmbressOptions, redis: Redis, jailKey: string): Promise<void>
}


问:
Ignore authorization at development environment
I'm recently migrated from ASP .NET Core 2.2 to 3.1, everything works fine but I have an issue with ignoring authorization on Dev environment.

The code that I used in CORE 2.2:

```<code>if (env.IsDevelopment())
{
    //On Development - ignore authorization
    services.AddMvc(opts => { opts.Filters.Add(new AllowAnonymousFilter()); })
       .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
else
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
</code>```

This obviously doesn't work on CORE 3.1 but I can't find any equivalent code that works.

Among other things, I tried to use this code (below) with no result.

```<code> services.AddControllers(opts =>
 {
     if (env.IsDevelopment())
     {
         opts.Filters.Add(new AllowAnonymousFilter());
     }
     else
     {
     }
 });
</code>```

Please help me with this.

My relevant code (CORE 3.1):

```<code>public void InstallServices(IServiceCollection services, IConfiguration configuration, IWebHostEnvironment env, ILogger logger)
{
    services.AddControllers(opts =>
    {
        if (env.IsDevelopment())
        {
            opts.Filters.Add(new AllowAnonymousFilter());
        }
        else
        {
        }
    });

    services.AddAutoMapper(typeof(Startup));
    var jwtSettings = new JwtSettings();
    configuration.Bind(nameof(JwtSettings), jwtSettings);
    services.AddSingleton(jwtSettings);
    var tokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = false,
        ValidateAudience = false,
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = jwtSettings.PrivateSigningSecretKey,
        ValidateLifetime = true,
        ClockSkew = TimeSpan.Zero
    };
    services.AddSingleton(tokenValidationParameters);

    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.SaveToken = true;
            options.TokenValidationParameters = tokenValidationParameters;
        });
    services.AddAuthorization(options =>
    {
        options.AddPolicy(Authorizations.RequireAdminOrManagerRole,
            policy => policy.RequireRole(Authorizations.Admin, Authorizations.Manager));
    });
    //deleted Swagger setup
}
public void InstallConfiguration(IApplicationBuilder app, IWebHostEnvironment env, IConfiguration configuration, ILogger logger)
{
    //deleted Swagger setup
    app.UseHttpsRedirection();
    app.UseMiddleware(typeof(ErrorHandlingMiddleware));
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
</code>```

答:
I found something that works for me.
Let me know if you have a better solution

My Configuration:

```<code>app.UseHttpsRedirection();
app.UseMiddleware(typeof(ErrorHandlingMiddleware));
app.UseRouting();
if (env.IsStaging() || env.IsDevelopment())
{
    //on staging/development dont require authentication
    app.Use(async (context, next) =>
    {
        // Set claims for the test user.
        var claims = new[] { new Claim("role", "Admin"), new Claim("sub", "some guid") };
        var id = new ClaimsIdentity(claims, "DebugAuthorizationMiddleware", "name", "role");
        // Add the test user as Identity.
        context.User.AddIdentity(id);
        // User is now authenticated.
        await next.Invoke();
    });
}
else
    app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
</code>```

Credit:
Programmatically add [AllowAnonymous] attribute to all my controller methods

Body:
I'm recently migrated from ASP .NET Core 2.2 to 3.1, everything works fine but I have an issue with ignoring authorization on Dev environment.

The code that I used in CORE 2.2:

if (env.IsDevelopment())
{
    //On Development - ignore authorization
    services.AddMvc(opts => { opts.Filters.Add(new AllowAnonymousFilter()); })
       .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
else
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

This obviously doesn't work on CORE 3.1 but I can't find any equivalent code that works.

Among other things, I tried to use this code (below) with no result.

 services.AddControllers(opts =>
 {
     if (env.IsDevelopment())
     {
         opts.Filters.Add(new AllowAnonymousFilter());
     }
     else
     {
     }
 });

Please help me with this.

My relevant code (CORE 3.1):

public void InstallServices(IServiceCollection services, IConfiguration configuration, IWebHostEnvironment env, ILogger logger)
{
    services.AddControllers(opts =>
    {
        if (env.IsDevelopment())
        {
            opts.Filters.Add(new AllowAnonymousFilter());
        }
        else
        {
        }
    });

    services.AddAutoMapper(typeof(Startup));
    var jwtSettings = new JwtSettings();
    configuration.Bind(nameof(JwtSettings), jwtSettings);
    services.AddSingleton(jwtSettings);
    var tokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = false,
        ValidateAudience = false,
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = jwtSettings.PrivateSigningSecretKey,
        ValidateLifetime = true,
        ClockSkew = TimeSpan.Zero
    };
    services.AddSingleton(tokenValidationParameters);

    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.SaveToken = true;
            options.TokenValidationParameters = tokenValidationParameters;
        });
    services.AddAuthorization(options =>
    {
        options.AddPolicy(Authorizations.RequireAdminOrManagerRole,
            policy => policy.RequireRole(Authorizations.Admin, Authorizations.Manager));
    });
    //deleted Swagger setup
}
public void InstallConfiguration(IApplicationBuilder app, IWebHostEnvironment env, IConfiguration configuration, ILogger logger)
{
    //deleted Swagger setup
    app.UseHttpsRedirection();
    app.UseMiddleware(typeof(ErrorHandlingMiddleware));
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}

Body:
I found something that works for me.
Let me know if you have a better solution

My Configuration:

app.UseHttpsRedirection();
app.UseMiddleware(typeof(ErrorHandlingMiddleware));
app.UseRouting();
if (env.IsStaging() || env.IsDevelopment())
{
    //on staging/development dont require authentication
    app.Use(async (context, next) =>
    {
        // Set claims for the test user.
        var claims = new[] { new Claim("role", "Admin"), new Claim("sub", "some guid") };
        var id = new ClaimsIdentity(claims, "DebugAuthorizationMiddleware", "name", "role");
        // Add the test user as Identity.
        context.User.AddIdentity(id);
        // User is now authenticated.
        await next.Invoke();
    });
}
else
    app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });

Credit:
Programmatically add [AllowAnonymous] attribute to all my controller methods


问:
Converting all the datetime columns of a variable Pandas DataFrame into a different timezone
I have to deal with a Pandas DataFrame that can be composed by different datetime columns (they can vary, I can have 0..N datetime cols). I know that each datetime column timezone is UTC and I need to convert their data to another timezone. If I do as follows:

```<code>df['a_datetime_column'].dt.tz_localize('UTC').dt.tz_convert('my_timezone')
</code>```

it works but I need to know in advance the datetime column names (ok, I could get them in some way).

Is there a specific way to do this conversion on all the DataFrame at once independently from the composition of its columns?

答:
Check out select_dtypes, you can use it to select only the datetime64[ns] columns and apply your tz_convert to those:

```<code>df.select_dtypes(inlcude=["datetime64[ns]"]).dt.tz_localize('UTC').dt.tz_convert('my_timezone')
</code>```

Body:
I have to deal with a Pandas DataFrame that can be composed by different datetime columns (they can vary, I can have 0..N datetime cols). I know that each datetime column timezone is UTC and I need to convert their data to another timezone. If I do as follows:

df['a_datetime_column'].dt.tz_localize('UTC').dt.tz_convert('my_timezone')

it works but I need to know in advance the datetime column names (ok, I could get them in some way).

Is there a specific way to do this conversion on all the DataFrame at once independently from the composition of its columns?

Body:
Check out select_dtypes, you can use it to select only the datetime64[ns] columns and apply your tz_convert to those:

df.select_dtypes(inlcude=["datetime64[ns]"]).dt.tz_localize('UTC').dt.tz_convert('my_timezone')


答:
The problem here is mismatching format specifier and argument type, leading to undefined behavior.

The format %f (as well as %lf) is for plain double, not long double.

For long double you need to use the printf prefix L for the format, as in %Lf:

```<code>printf("normalization %Lf\n", normalization);
</code>```

On an unrelated note, please make it a habit to have trailing newlines in your output. Because output to stdout (which is where printf writes) by default is line buffered, leading newline could lead to unexpected "missing" output.

Title: Trouble printing float64 value in C

Body:
The problem here is mismatching format specifier and argument type, leading to undefined behavior.

The format %f (as well as %lf) is for plain double, not long double.

For long double you need to use the printf prefix L for the format, as in %Lf:

printf("normalization %Lf\n", normalization);

On an unrelated note, please make it a habit to have trailing newlines in your output. Because output to stdout (which is where printf writes) by default is line buffered, leading newline could lead to unexpected "missing" output.


问:
setImage often without blocking UI thread Android
I have an ImageView. When user presses button I want to change image (it is animation-list) and run this animation. I used to use setImageResource, but it blocks UI thread and causes lags. I can't predict what image I would set befor user presses button. I tried to preload drawables but it causes OOM, because I have about 30 xmls with animation-list. How can I solve It? To sum up, I want to fastly change image in my ImageView and then start frame animation on it.</p>

答: You might look into using a library to load up your images. There is one that is really easy to implement called Picasso. It's been around for a while too, so it should be easy to see some examples. </p>


问:
Create measure based on several filter conditions PowerBI
I want to create a PowerBI measure, to perform some filter tasks.

Basically, I want to create a measure that returns 1 if ColumnA = empty OR column B is empty OR columns C = empty. I'm just getting started with measures and I am getting stuck.

My code attempt:

```<code>M_DataIssues = FILTER(
                      ALL(Table[ColA] ; Table[ColB] ; Table[ColC])
                          Table[ColA] = "" || Table[ColB]= "" || Table[ColC] = "")
</code>```

Any help would be appreciated.

PS. due to my user permissions, I can only create measures. I do not have rights to do other modelling tasks or create columns e.g.

Thanks!!

KR ~M.

答:
will this measure work for you? if yes here is the formula

```<code>Measure = CALCULATE(DISTINCTCOUNT('Table'[ColumA]) || DISTINCTCOUNT('Table'[ColumB]) || DISTINCTCOUNT('Table'[ColumnC]);FILTER('Table';'Table'[ColumA]="" || 'Table'[ColumB]="" || 'Table'[ColumnC]=""))
</code>```

Body:
I want to create a PowerBI measure, to perform some filter tasks.

Basically, I want to create a measure that returns 1 if ColumnA = empty OR column B is empty OR columns C = empty. I'm just getting started with measures and I am getting stuck.

My code attempt:

M_DataIssues = FILTER(
                      ALL(Table[ColA] ; Table[ColB] ; Table[ColC])
                          Table[ColA] = "" || Table[ColB]= "" || Table[ColC] = "")

Any help would be appreciated.

PS. due to my user permissions, I can only create measures. I do not have rights to do other modelling tasks or create columns e.g.

Thanks!!

KR ~M.

Body:
will this measure work for you? if yes here is the formula

Measure = CALCULATE(DISTINCTCOUNT('Table'[ColumA]) || DISTINCTCOUNT('Table'[ColumB]) || DISTINCTCOUNT('Table'[ColumnC]);FILTER('Table';'Table'[ColumA]="" || 'Table'[ColumB]="" || 'Table'[ColumnC]=""))


问:
how to get center of screen Coordinates in android Mapbox
how can i get center of screen
Coordinates in android mapbox</p>

```<code>public void setMarker(double lat,double lng){
        sourceLat = lat;
        sourceLng = lng;
        map.setSourcePin(lat , lng);
        map.flyTo(lat, lng);
    }
</code>```

答:
```<code>double mapLat = mapboxMap.getCameraPosition().target.getLatitude()

double mapLong = mapboxMap.getCameraPosition().target.getLongitude()
</code>```

Edit: The center of the map is the target. The MapboxMap class has a getCameraPosition() method and the Target class within the CameraPosition class.

```<code>LatLng mapLatLng = mapboxMap.getCameraPosition().target;
double mapLat = mapLatLng.getLatitude();
double mapLong = mapLatLng.getLongitude();
</code>```

Body:
how can i get center of screen
Coordinates in android mapbox

public void setMarker(double lat,double lng){
        sourceLat = lat;
        sourceLng = lng;
        map.setSourcePin(lat , lng);
        map.flyTo(lat, lng);
    }

Body:
double mapLat = mapboxMap.getCameraPosition().target.getLatitude()

double mapLong = mapboxMap.getCameraPosition().target.getLongitude()

Edit: The center of the map is the target. The MapboxMap class has a getCameraPosition() method and the Target class within the CameraPosition class.

LatLng mapLatLng = mapboxMap.getCameraPosition().target;
double mapLat = mapLatLng.getLatitude();
double mapLong = mapLatLng.getLongitude();


答:
You can loop over the columns which have datetime type:</p>

```<code>for col,dtyp in df.dtypes.iteritems():
    if dtyp == 'datetime64[ns]':
        df[col] = df[col].dt.tz_localize('UTC').dt.tz_convert('my_timezone')
</code>```

Title: Converting all the datetime columns of a variable Pandas DataFrame into a different timezone

Body:
You can loop over the columns which have datetime type:

for col,dtyp in df.dtypes.iteritems():
    if dtyp == 'datetime64[ns]':
        df[col] = df[col].dt.tz_localize('UTC').dt.tz_convert('my_timezone')