问:
How to make bootstrap navbar work in my Rails movie review application
I included all the files that are needed to run the bootstrap, but the navbar is not working, it looks like normal HTML.

gemfile:

```<code>source 'https://rubygems.org'

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.2', '>= 5.2.4.2'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use Puma as the app server
gem 'puma', '~> 3.7'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  # Adds support for Capybara system testing and selenium driver
  gem 'capybara', '>= 2.15'
  gem 'selenium-webdriver'
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console', '>= 3.3.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
gem 'devise', '~> 4.7', '>= 4.7.1'
gem 'paperclip', '~> 6.1'
gem 'bootstrap-sass', '~> 3.4', '>= 3.4.1'
gem 'jquery-rails', '~> 4.4'
gem 'jquery-turbolinks', '~> 2.1'
gem 'rails-ujs', '~> 0.1.0'
gem 'sassc-rails', '~> 2.1', '>= 2.1.2'
</code>```

application.js:

```<code>//= require rails-ujs
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require_tree .
</code>```

application.scss:

```<code>@import "bootstrap-sprockets";
@import "bootstrap";
</code>```

This is the header file that I used for Navbar, _header.html.erb:

```<code><nav class="navbar" navbar-default role="navigation">
  <div class="container">
  <div class="navbar-header">
    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
      <span class="sr-only"> Toggle Navigation</span>
      <span class="icon-bar"> </span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>
    <%= link_to "Movies Reviews", root_path, class: "navbar-brand" %>
  </div>

  <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
    <ul class="nav navbar-nav">
    <% if user_signed_in? %>
      <li><%= link_to "New Movie" , new_movie_path, class: "active" %> </li>
      <li> <%= link_to "Account", edit_user_registration_path %></li>
      <% else %>
        <li> <%= link_to "Sign Up", new_user_registration_path, class: "active" %></li>
        <li> <%= link_to "Sign In", new_user_session_path, class: "active" %></li>
      <% end %>
    </ul>
    <form class="navbar-form navbar-right">
      <div class="form_group">
        <input type="text" class="form-control" placeholder="search">
      </div>
      <button type="submit" class="btn btn-default">Submit</button>
    </form>
  </div>
  </div>
</nav>
</code>```

And application.html.erb:

```<code><!DOCTYPE html>
<html>
  <head>
    <title>Moviereview</title>
    <%= csrf_meta_tags %>

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

  <body>
    <%= render 'layouts/header' %>
    <% flash.each do |name, msg|%>
    <%= content_tag(:div ,msg, class:"alert alert_info")%>
    <% end %>
    <%= yield %>
  </body>
</html>
</code>```

I saw the same question and applied all the answers in that but don't get the proper result. Here is the output I am getting:

答:
Installing bootstrap in Ruby on Rails 6:

```<code>https://getbootstrap.com/
https://github.com/twbs/bootstrap-rubygem
// Gemfile.rb
gem 'bootstrap', '~> 4.4.1'
gem 'jquery-rails'

// Console
bundle install
yarn add bootstrap@4.3.1 jquery popper.js

// application.scss
@import "bootstrap";

// config/webpack/environment.js
const { environment } = require('@rails/webpacker')
const webpack = require("webpack")
environment.plugins.append("Provide", new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
Popper: ['popper.js', 'default']
}))
module.exports = environment

// packs/application.js
import "bootstrap"
</code>```

Source:
https://gist.github.com/yshmarov/758a04798c3400cf125de27659dab43e/#file-gem-bootstrap

Body:
I included all the files that are needed to run the bootstrap, but the navbar is not working, it looks like normal HTML.

gemfile:

source 'https://rubygems.org'

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.2', '>= 5.2.4.2'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use Puma as the app server
gem 'puma', '~> 3.7'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  # Adds support for Capybara system testing and selenium driver
  gem 'capybara', '>= 2.15'
  gem 'selenium-webdriver'
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console', '>= 3.3.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
gem 'devise', '~> 4.7', '>= 4.7.1'
gem 'paperclip', '~> 6.1'
gem 'bootstrap-sass', '~> 3.4', '>= 3.4.1'
gem 'jquery-rails', '~> 4.4'
gem 'jquery-turbolinks', '~> 2.1'
gem 'rails-ujs', '~> 0.1.0'
gem 'sassc-rails', '~> 2.1', '>= 2.1.2'

application.js:

//= require rails-ujs
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require_tree .

application.scss:

@import "bootstrap-sprockets";
@import "bootstrap";

This is the header file that I used for Navbar, _header.html.erb:

    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
       Toggle Navigation

    </button>
    <%= link_to "Movies Reviews", root_path, class: "navbar-brand" %>

    <% if user_signed_in? %>

<%= link_to "New Movie" , new_movie_path, class: "active" %>

 <%= link_to "Account", edit_user_registration_path %>

      <% else %>

 <%= link_to "Sign Up", new_user_registration_path, class: "active" %>

 <%= link_to "Sign In", new_user_session_path, class: "active" %>

      <% end %>

    <form class="navbar-form navbar-right">

        <input type="text" class="form-control" placeholder="search">

      <button type="submit" class="btn btn-default">Submit</button>
    </form>

And application.html.erb:

<!DOCTYPE html>

    <title>Moviereview</title>
    <%= csrf_meta_tags %>

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>

    <%= render 'layouts/header' %>
    <% flash.each do |name, msg|%>
    <%= content_tag(:div ,msg, class:"alert alert_info")%>
    <% end %>
    <%= yield %>

I saw the same question and applied all the answers in that but don't get the proper result. Here is the output I am getting:

Body:
Installing bootstrap in Ruby on Rails 6:

https://getbootstrap.com/
https://github.com/twbs/bootstrap-rubygem
// Gemfile.rb
gem 'bootstrap', '~> 4.4.1'
gem 'jquery-rails'

// Console
bundle install
yarn add bootstrap@4.3.1 jquery popper.js

// application.scss
@import "bootstrap";

// config/webpack/environment.js
const { environment } = require('@rails/webpacker')
const webpack = require("webpack")
environment.plugins.append("Provide", new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
Popper: ['popper.js', 'default']
}))
module.exports = environment

// packs/application.js
import "bootstrap"

Source:
https://gist.github.com/yshmarov/758a04798c3400cf125de27659dab43e/#file-gem-bootstrap


来源: stackexchange

问:
What is the difference between passing"this" and "activity!!" as a ViewModelStoreOwner while creating ViewModelProvider instance
Hi I am a Kotlin learner, wanted to understand the difference between passing"this" and "activity!!" as a ViewModelStoreOwner while creating ViewModelProvider instance in a fragment for ex

```<code> viewModel = ViewModelProvider(
        this,
        InventoryDetailsFragmentViewModelFactory.getInstance(activity!!.application)
    )
        .get(InventoryDetailsFragmentViewModel::class.java)
</code>```

when I am using this as owner sometimes observer is not working
Please help me to understand difference in using this and activity!!

答:
You are able to pass either this (a Fragment) or activity!! (a FragmentActivity) to the ViewModelProvider constructor because both implement the ViewModelStoreOwner interface.

The role of a ViewModelStoreOwner is to be able to provide a ViewModelStore, when needed, where the ViewModelStore represents a collection of existing viewmodels:

If you use this and pass a Fragment to the ViewModelProvider constructor, the ViewModelStore will be tied to that Fragment. This fragment and child fragments might share viewmodels, but those viewmodels should not be shared with other peer fragments or parents.

If you use activity!! and pass a FragmentActivity to the ViewModelProvider constructor, the ViewModelStore will be tied to that FragmentActivity. Not only can this activity use the viewmodel, but any fragments used in that activity could also share that viewmodel.

You need to decide what the proper scope is of your InventoryDetailsFragmentViewModel.

ContentLicense: CC BY-SA 4.0

Body:
Hi I am a Kotlin learner, wanted to understand the difference between passing"this" and "activity!!" as a ViewModelStoreOwner while creating ViewModelProvider instance in a fragment for ex

 viewModel = ViewModelProvider(
        this,
        InventoryDetailsFragmentViewModelFactory.getInstance(activity!!.application)
    )
        .get(InventoryDetailsFragmentViewModel::class.java)

when I am using this as owner sometimes observer is not working
Please help me to understand difference in using this and activity!!


问:
JPA Criteria query group by and get last record
this entity employee

```<code>@Entity
@Table(name="employee")
@IdClass(EmployeeKey.class)
public class Employee implements Serializable{
    private static final long serialVersionUID = -4060941180859761486L;

    @Id @Column(name ="DATA_DT")
    private Date registDate;
    @Id @Column(name ="EMPE_NO")
    private String empeId;

    @Column(name ="TTL_NM_TH")
    private String titleNameTh;
    @Column(name ="TTL_NM_EN")
    private String titleNameEn;
    @Column(name ="EMPE_NM_TH")
    private String empeNameTh;
    @Column(name ="EMPE_LST_NM_TH")
    private String empeLastNameTh;
    @Column(name ="EMPE_POS")
    private String empePosition;

    @ManyToOne
    @JoinColumn(name = "DEPT_CODE" , nullable = true)
    @NotFound(action = NotFoundAction.IGNORE)
    private OrganizationUnit empeDeptCode;

//get set

}
</code>```

this entity ou

```<code>@Entity
@Table(name="ou")
public class OrganizationUnit implements Serializable{
    private static final long serialVersionUID = -4038118923332034407L;
    @Id
    @Column(name ="OU_CODE")
    private String ouCode;
    @Column(name ="OU_TP_CODE")
    private String ouTpCode;
    @Column(name ="OU_NM")
    private String ouName;
    @Column(name ="BR_GRP")
    private String ouBusinessGroup;
    @Column(name ="GRP_OU_CODE")
    private String groupOUCode;
    @Column(name ="SCTR_OU_CODE")
    private String sctrOUCode;
    @Column(name ="DEPT_OU_CODE")
    private String departmentOUCode;
    @Column(name ="EFF_DT")
    private Date effectiveDate;
    @Column(name ="END_DT")
    private Date endDate;

//get set

}
</code>```

Now i create a criteria query like this. i try to create search function from criteria-Api. my table employee has two id every day i will insert data in employee . search function need to show last record .

```<code>public List<Employee> findByAvanceSearch(SearchEmpRequestModel data) {
    // TODO Auto-generated method stub
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Employee> cq = cb.createQuery(Employee.class);

    Root<Employee> employee = cq.from(Employee.class);
    List<javax.persistence.criteria.Predicate> predicates = new ArrayList<>();

    if(data.getEmpNumber() != null) {

        //predicates.add( cb.and(cb.equal(employee.get("empeId"), data.getEmpNumber()), cb.greatest(employee.get("registDate"))));
        predicates.add(cb.equal(employee.get("empeId"), data.getEmpNumber()));
    }
    if(data.getEmpThainame()!=null) {

        predicates.add(cb.like(employee.get("titleNameTh"), "%"+data.getEmpThainame()+"%"));
    }
    if(data.getEmpDept()!=null) {

        predicates.add(cb.like(employee.get("empeDeptCode").get("departmentOUCode"), "%"+data.getEmpDept()+"%"));

    }
    if(data.getEmpGrp()!=null) {

        predicates.add(cb.like(employee.get("empeDeptCode").get("sctrOUCode"), "%"+data.getEmpGrp()+"%"));

    }
    if(data.getEmpSctr()!=null) {

        predicates.add(cb.like(employee.get("empeDeptCode").get("groupOUCode"), "%"+data.getEmpSctr()+"%"));

    }

    cq.orderBy(cb.asc(employee.get("registDate"))).groupBy(employee.get("empeId")).where((javax.persistence.criteria.Predicate[]) predicates.toArray(new javax.persistence.criteria.Predicate[0]));
    return em.createQuery(cq).getResultList();
}
</code>```

I need to get last record from group by but  from this code i get frist record.
Any one knows what should I use in the hibernate criteria .?
Thank.

答:
I think , This one will solve your problemGet record with max id, using Hibernate Criteria
</p>

Body:
this entity employee

@Entity
@Table(name="employee")
@IdClass(EmployeeKey.class)
public class Employee implements Serializable{
    private static final long serialVersionUID = -4060941180859761486L;

    @Id @Column(name ="DATA_DT")
    private Date registDate;
    @Id @Column(name ="EMPE_NO")
    private String empeId;

    @Column(name ="TTL_NM_TH")
    private String titleNameTh;
    @Column(name ="TTL_NM_EN")
    private String titleNameEn;
    @Column(name ="EMPE_NM_TH")
    private String empeNameTh;
    @Column(name ="EMPE_LST_NM_TH")
    private String empeLastNameTh;
    @Column(name ="EMPE_POS")
    private String empePosition;

    @ManyToOne
    @JoinColumn(name = "DEPT_CODE" , nullable = true)
    @NotFound(action = NotFoundAction.IGNORE)
    private OrganizationUnit empeDeptCode;

//get set

}

this entity ou

@Entity
@Table(name="ou")
public class OrganizationUnit implements Serializable{
    private static final long serialVersionUID = -4038118923332034407L;
    @Id
    @Column(name ="OU_CODE")
    private String ouCode;
    @Column(name ="OU_TP_CODE")
    private String ouTpCode;
    @Column(name ="OU_NM")
    private String ouName;
    @Column(name ="BR_GRP")
    private String ouBusinessGroup;
    @Column(name ="GRP_OU_CODE")
    private String groupOUCode;
    @Column(name ="SCTR_OU_CODE")
    private String sctrOUCode;
    @Column(name ="DEPT_OU_CODE")
    private String departmentOUCode;
    @Column(name ="EFF_DT")
    private Date effectiveDate;
    @Column(name ="END_DT")
    private Date endDate;

//get set

}

Now i create a criteria query like this. i try to create search function from criteria-Api. my table employee has two id every day i will insert data in employee . search function need to show last record .

public List<Employee> findByAvanceSearch(SearchEmpRequestModel data) {
    // TODO Auto-generated method stub
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Employee> cq = cb.createQuery(Employee.class);

    Root<Employee> employee = cq.from(Employee.class);
    List<javax.persistence.criteria.Predicate> predicates = new ArrayList<>();

    if(data.getEmpNumber() != null) {

        //predicates.add( cb.and(cb.equal(employee.get("empeId"), data.getEmpNumber()), cb.greatest(employee.get("registDate"))));
        predicates.add(cb.equal(employee.get("empeId"), data.getEmpNumber()));
    }
    if(data.getEmpThainame()!=null) {

        predicates.add(cb.like(employee.get("titleNameTh"), "%"+data.getEmpThainame()+"%"));
    }
    if(data.getEmpDept()!=null) {

        predicates.add(cb.like(employee.get("empeDeptCode").get("departmentOUCode"), "%"+data.getEmpDept()+"%"));

    }
    if(data.getEmpGrp()!=null) {

        predicates.add(cb.like(employee.get("empeDeptCode").get("sctrOUCode"), "%"+data.getEmpGrp()+"%"));

    }
    if(data.getEmpSctr()!=null) {

        predicates.add(cb.like(employee.get("empeDeptCode").get("groupOUCode"), "%"+data.getEmpSctr()+"%"));

    }

    cq.orderBy(cb.asc(employee.get("registDate"))).groupBy(employee.get("empeId")).where((javax.persistence.criteria.Predicate[]) predicates.toArray(new javax.persistence.criteria.Predicate[0]));
    return em.createQuery(cq).getResultList();
}

I need to get last record from group by but  from this code i get frist record.
Any one knows what should I use in the hibernate criteria .?
Thank.


问:
Java Class turns invalid after a method call
I have a class that interfaces with an RPGLE program.

The client will hold a reference to the class and perform certain operations.  Calling methods etc.

After a call to a particular method - endDocument(), the class is then is an invalid state because I call destroy() on a number of objects (which is required by the API).

Other than having a boolean member flag "illigalState" and at the top of every method checking it, throwing an IllegalStateException(), how might I handle this problem?

I don't want the user to be able to use the class after it is in this illegal state, but they have a reference to it.

答: A more OO way would be to use the State pattern. You could have two object states; valid (which contains the logic) and invalid which throws IllegalStateExceptions. Object state would need to be changed in the endDocument method</p>

ContentLicense: CC BY-SA 3.0


问:
How to get the member count in discord.py rewrite?
I wanted to make an command to show the membercount but it doesn't work.

This is what I have:

```<code>@bot.command(name='membercount')
async def membercount(ctx):
    await ctx.send(len(guild.member_count))
</code>```

and this is the error i get:
Module 'discord.guild' has no 'member_count' member

I tried searching on the internet but didn't find a working option.

答:
Simple for loop should work.

```<code>member_count = 0;

for member in ctx.guild.members:
    member_count += 1
await ctx.send(member_count)
</code>```

Body:
I wanted to make an command to show the membercount but it doesn't work.

This is what I have:

@bot.command(name='membercount')
async def membercount(ctx):
    await ctx.send(len(guild.member_count))

and this is the error i get:
Module 'discord.guild' has no 'member_count' member

I tried searching on the internet but didn't find a working option.

Body:
Simple for loop should work.

member_count = 0;

for member in ctx.guild.members:
    member_count += 1
await ctx.send(member_count)


问:
query selector find dynamic elements
iam trying to fetch my .btn-viewdetail buttons with the query selector.But only the button i created manually is fetched by the function, not the dynamically created ones. I dont know why, they all have the same class name.

Is it becuase if the , I warp the input buttons in?

does anyone has a solution to this problem?

```<code>window.onload=function(){
    this.getPerson();
    this.document.getElementById('getPerson').addEventListener('click', this.getPerson);
    //this.document.getElementById('deletePerson').addEventListener('click', this.deletePerson);
}

function createNode(element) {
    return document.createElement(element);
}

function append(parent, el) {
  return parent.appendChild(el);
}

const ul = document.getElementById('person');
const url ='http://localhost:8080/person';
var x = 1;

function getPerson(){
//addButton.value = "+";
//addButton.class = "btn btn-success";
$("#output1 tbody tr").remove();
fetch(url)
    .then(res => res.json())
    .then(data => {

        //console.log(data);

        var temp = "";
        data.forEach((person) => {
            temp += "<tr>";
            temp += "<td>" +person.id+"</td>";
            //console.log(person.id);
            temp += "<td>" +person.vorname+"</td>";
            temp += "<td>" +person.nachname+"</td>";
            temp += "<td>"
            person.projectList.forEach((project) => {
              temp += project.name+"<br>";
            });
            temp += "</td>"

            temp += "<td>"
            person.technoList.forEach((techno) => {
              temp += techno.name+"<br>";
            });
            temp += "</td>"

            /*id='addButton" + x + "'*/

            temp += "<td>" + addButton(person.id)+ "</td>"
             //this.parentElement.appendChild(this)
             x++;

            //document.getElementById('personDetail_Button').addEventListener('click', this.personDetail(person.id));
            temp += "</tr>"

        });

        document.getElementById("tableOutput").innerHTML= temp;

    });
}

function addButton(person_id){
  var element = document.createElement("input");
  element.type = 'button';
  element.value = 'test123';
  element.setAttribute("data-person_id",person_id);
  element.setAttribute("class","btn-viewdetail btn btn-primary");

  var _wrap = document.createElement("div");
  _wrap.appendChild(element);

 return _wrap.innerHTML;

}

document.body.innerHTML += addButton(4);

function personDetail(person_id_request){
 //console.log(person_id_request);
 fetch('http://localhost:8080/person/' + person_id_request)
    .then(res => res.json())
    .then(data => {

     console.log(data);
   });
}

function deletePerson(){
var id = document.getElementById('id_delete').value;
var id_input = document.getElementById('id_delete');
fetch('http://localhost:8080/person/' + id, {
    method: 'DELETE',
    })
    .then(res => {
        console.log(res.status)
        if(res.status == 200){
            alert("Die Person mit der ID " +id +" wurde gelöscht");
            getPerson();
            }else{
                alert("Leider konnten wir die Person nicht löschen, hast du vielleicht die falsche ID angegeben? " + res.status)

            }
        res.json();
        $('#id_delete').reset;
    })
    .then((data) => {
    })
}

var _btns = document.querySelectorAll(".btn-viewdetail");
console.log(_btns);
_btns.forEach(function (el) {
  el.addEventListener('click',function(evt){
    console.log(evt.target.getAttribute("data-person_id"));
    personDetail(evt.target.getAttribute("data-person_id"));
  });
});
</code>```

答:
You have to get the parent element(the container of all buttons) by id first:

var parentEl = document.getElementById('parentEl')

and then:

var _btns = parentEl.querySelectorAll(".btn-viewdetail");

Title: query selector find dynamic elements

Body:
iam trying to fetch my .btn-viewdetail buttons with the query selector.But only the button i created manually is fetched by the function, not the dynamically created ones. I dont know why, they all have the same class name.

Is it becuase if the , I warp the input buttons in?

does anyone has a solution to this problem?

window.onload=function(){
    this.getPerson();
    this.document.getElementById('getPerson').addEventListener('click', this.getPerson);
    //this.document.getElementById('deletePerson').addEventListener('click', this.deletePerson);
}

function createNode(element) {
    return document.createElement(element);
}

function append(parent, el) {
  return parent.appendChild(el);
}

const ul = document.getElementById('person');
const url ='http://localhost:8080/person';
var x = 1;

function getPerson(){
//addButton.value = "+";
//addButton.class = "btn btn-success";
$("#output1 tbody tr").remove();
fetch(url)
    .then(res => res.json())
    .then(data => {

        //console.log(data);

        var temp = "";
        data.forEach((person) => {
            temp += "
";
            temp += "" +person.id+"	";
            //console.log(person.id);
            temp += "" +person.vorname+"	";
            temp += "" +person.nachname+"	";
            temp += ""
            person.projectList.forEach((project) => {
              temp += project.name+"
";
            });
            temp += "	"

            temp += ""
            person.technoList.forEach((techno) => {
              temp += techno.name+"
";
            });
            temp += "	"

            /*id='addButton" + x + "'*/

            temp += "" + addButton(person.id)+ "	"
             //this.parentElement.appendChild(this)
             x++;

            //document.getElementById('personDetail_Button').addEventListener('click', this.personDetail(person.id));
            temp += "
"

        });

        document.getElementById("tableOutput").innerHTML= temp;

    });
}

function addButton(person_id){
  var element = document.createElement("input");
  element.type = 'button';
  element.value = 'test123';
  element.setAttribute("data-person_id",person_id);
  element.setAttribute("class","btn-viewdetail btn btn-primary");

  var _wrap = document.createElement("div");
  _wrap.appendChild(element);

 return _wrap.innerHTML;

}

document.body.innerHTML += addButton(4);

function personDetail(person_id_request){
 //console.log(person_id_request);
 fetch('http://localhost:8080/person/' + person_id_request)
    .then(res => res.json())
    .then(data => {

     console.log(data);
   });
}

function deletePerson(){
var id = document.getElementById('id_delete').value;
var id_input = document.getElementById('id_delete');
fetch('http://localhost:8080/person/' + id, {
    method: 'DELETE',
    })
    .then(res => {
        console.log(res.status)
        if(res.status == 200){
            alert("Die Person mit der ID " +id +" wurde gelöscht");
            getPerson();
            }else{
                alert("Leider konnten wir die Person nicht löschen, hast du vielleicht die falsche ID angegeben? " + res.status)

            }
        res.json();
        $('#id_delete').reset;
    })
    .then((data) => {
    })
}

var _btns = document.querySelectorAll(".btn-viewdetail");
console.log(_btns);
_btns.forEach(function (el) {
  el.addEventListener('click',function(evt){
    console.log(evt.target.getAttribute("data-person_id"));
    personDetail(evt.target.getAttribute("data-person_id"));
  });
});


问:
Getting Errors from Entity Framework Core for a List contains another List
I have a List of SkillIDs, and I want to include the records from database that have that list in their skills:

```<code>List<int> skillIDs = skills.Where(s => s.Checked == true)?.Select(s => s.Id)?.ToList<int>() ?? new List<int>();
if (skillIDs.Count() > 0)
{
    jobSeekers = jobSeekers.Where(js => js.ProfileJobs
         .Where(pj => skillIDs.All(s => pj.ProfileJobSkills.Select(pjs => pjs.SkillId).Contains(s))).Any());
         //.Where(pj => pj.ProfileJobSkills.Select(pjs => pjs.SkillId).Intersect(skillIDs).Count() == skillIDs.Count()).Any());
}
</code>```

I either Get "Bug or Limitation" Error from Entity Framework core for the intersect and except or I get "Can't translate and use client evaluation" Error from EF Core, Ofcourse I don't want to use client evaluation since data is large, What do I do?

For the not commented code I get:

selector: (p2) => p2.SkillId), \r\n            item: s)))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync().

and For the commented code I get:

{"Processing of the LINQ expression 'Intersect(\r\n ...  by 'NavigationExpandingExpressionVisitor' failed. This may indicate either a bug or a limitation in EF Core.

答:
You can try something like this:

```<code>List<int> skillIDs = skills.Where(s => s.Checked == true)
     .Select(s => s.Id)
     .ToList<int>() ?? new List<int>();

if (skillIDs.Count() > 0)
{
    jobSeekers = jobSeekers
      .Where(js =>
         js.ProfileJobs != null &&
         js.ProfileJobs.Any(pj =>
              pj.ProfileJobSkills != null &&
              pj.ProfileJobSkills.Any(pjs =>
                   skillIds.Contains(pjs.SkillId))
     );
 }
</code>```

Because you have multiple layers in your table relationships, you can't obtain the cleanest query.  Something like this should work though.

Body:
I have a List of SkillIDs, and I want to include the records from database that have that list in their skills:

List<int> skillIDs = skills.Where(s => s.Checked == true)?.Select(s => s.Id)?.ToList<int>() ?? new List<int>();
if (skillIDs.Count() > 0)
{
    jobSeekers = jobSeekers.Where(js => js.ProfileJobs
         .Where(pj => skillIDs.All(s => pj.ProfileJobSkills.Select(pjs => pjs.SkillId).Contains(s))).Any());
         //.Where(pj => pj.ProfileJobSkills.Select(pjs => pjs.SkillId).Intersect(skillIDs).Count() == skillIDs.Count()).Any());
}

I either Get "Bug or Limitation" Error from Entity Framework core for the intersect and except or I get "Can't translate and use client evaluation" Error from EF Core, Ofcourse I don't want to use client evaluation since data is large, What do I do?

For the not commented code I get:

selector: (p2) => p2.SkillId), \r\n            item: s)))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync().

and For the commented code I get:

{"Processing of the LINQ expression 'Intersect(\r\n ...  by 'NavigationExpandingExpressionVisitor' failed. This may indicate either a bug or a limitation in EF Core.

Body:
You can try something like this:

List<int> skillIDs = skills.Where(s => s.Checked == true)
     .Select(s => s.Id)
     .ToList<int>() ?? new List<int>();

if (skillIDs.Count() > 0)
{
    jobSeekers = jobSeekers
      .Where(js =>
         js.ProfileJobs != null &&
         js.ProfileJobs.Any(pj =>
              pj.ProfileJobSkills != null &&
              pj.ProfileJobSkills.Any(pjs =>
                   skillIds.Contains(pjs.SkillId))
     );
 }

Because you have multiple layers in your table relationships, you can't obtain the cleanest query.  Something like this should work though.


问:
Visual Studio with GitHub: Invalid URI: The URI scheme is not valid
I want to clone my repository to compile and improve it, with Visual Studio Community 2017.

On command line I would type git clone git@github.com:aegif/CmisSync.git

Visual Studio has a Team Explorer view with a Clone button, but it does not seem to work as I would expect, it shows errors:

So I specified a scheme:

So I specify a port:

... which I guess is caused by Visual Studio trying to connect without bothering to authenticate me or creating SSH keys first.

What am I doing wrong?

答: I had this problem when I try to clone a repo from bitbucket. I just open sourcetree and cloned it. Then switched to Visual Studio 2019 to open it.</p>


问:
Control Go package version
I am looking for a way to control a go package version on github, something similar to the "version" key in a package.json file (for nodejs packages).

In a package.json

```<code>{
  "version": "1.0.1"
}
</code>```

I want to import my package in another one, both use go modules. In my second package, my go.mod file looks like this :

module myPackage

go 1.14

require(
  github.com/myAwesomePackage v0.0.0-20200531102207-93175fe4ed5f
)
```

<p>Now I'd like to make changes to myAwesomePackage, so I can rewrite myPackage mod file like this :</p>

<pre class="lang-golang prettyprint-override"><code>module myPackage

go 1.14

require(
  github.com/myAwesomePackage v1.1.0
)
</code>```

I tried git tag 1.1.0 and git tag v1.1.0 in myAwesomePackage, but
myPackage gives the following error when trying to update :

```<code>invalid version: unknown revision v1.1.0
</code>```

UPDATE

git tag actually worked, the issue seemed to come from my Ide (GoLand). Just rewriting version in go.mod file didn't worked, I had to remove the
entire line in require statement, then let IntelliJ sync again the
dependencies. Now myAwesomePackage is imported with the correct version.

答: It's unclear whether you're publishing a Go module, or whether you're depending on one. Either way, it's simple enough; if you're publishing one, you can just tag a version using git tag. If you're depending on one and would like to lock to a specific version, you can simply modify your project's go.mod file and choose a version.

Title: Control Go package version

Body:
I am looking for a way to control a go package version on github, something similar to the "version" key in a package.json file (for nodejs packages).

In a package.json

{
  "version": "1.0.1"
}

I want to import my package in another one, both use go modules. In my second package, my go.mod file looks like this :

module myPackage

go 1.14

require(
  github.com/myAwesomePackage v0.0.0-20200531102207-93175fe4ed5f
)

Now I'd like to make changes to myAwesomePackage, so I can rewrite myPackage mod file like this :

module myPackage

go 1.14

require(
  github.com/myAwesomePackage v1.1.0
)

I tried git tag 1.1.0 and git tag v1.1.0 in myAwesomePackage, but
myPackage gives the following error when trying to update :

invalid version: unknown revision v1.1.0

UPDATE

git tag actually worked, the issue seemed to come from my Ide (GoLand). Just rewriting version in go.mod file didn't worked, I had to remove the
entire line in require statement, then let IntelliJ sync again the
dependencies. Now myAwesomePackage is imported with the correct version.


问:
Carthage on macOS 10.15 Catalina
Has anyone managed to install Carthage on macOS 10.15 Catalina (Beta)?

I tried to install Carthage using HomeBrew:

```<code>brew install Carthage
</code>```

I get the following error message:

```<code>Error: You are using macOS 10.15.
We do not provide support for this pre-release version.
You will encounter build failures with some formulae.
Please create pull requests instead of asking for help on Homebrew's Github.
Discourse, Twitter or IRC. You are responsible for resolving any issues you experience, as you are running this pre-release version.
</code>```

Now, I do understand that there might be some issues, I am using these beta softwares on my secondary MacBook Pro, so no worries but I can't install it and any tips would be much appreciated.

答:
I run these commands on macOS 10.15.4 Catalina and worked for me.

```<code>ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" < /dev/null 2> /dev/null
</code>```

```<code>sudo chown -R $(whoami) /usr/local/*
</code>```

```<code>/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
</code>```

```<code>brew install carthage
</code>```

Title: Carthage on macOS 10.15 Catalina

Body:
Has anyone managed to install Carthage on macOS 10.15 Catalina (Beta)?

I tried to install Carthage using HomeBrew:

brew install Carthage

I get the following error message:

Error: You are using macOS 10.15.
We do not provide support for this pre-release version.
You will encounter build failures with some formulae.
Please create pull requests instead of asking for help on Homebrew's Github.
Discourse, Twitter or IRC. You are responsible for resolving any issues you experience, as you are running this pre-release version.

Now, I do understand that there might be some issues, I am using these beta softwares on my secondary MacBook Pro, so no worries but I can't install it and any tips would be much appreciated.

Body:
I run these commands on macOS 10.15.4 Catalina and worked for me.

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" < /dev/null 2> /dev/null

sudo chown -R $(whoami) /usr/local/*

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

brew install carthage


问:
How can we create asynchronous API in django?
I want to create a third party chatbot API which is asynchronous and replies "ok" after 10 seconds pause.

```<code>import time

def wait():
    time.sleep(10)
    return "ok"

# views.py
def api(request):
    return wait()
</code>```

I have tried celery for the same as follows where I am waiting for celery response in view itself:

```<code>import time
from celery import shared_task

@shared_task
def wait():
    time.sleep(10)
    return "ok"

# views.py
def api(request):
    a = wait.delay()
    work = AsyncResult(a.id)
    while True:
        if work.ready():
           return work.get(timeout=1)
</code>```

But this solution works synchronously and makes no difference. How can we make it asynchronous without asking our user to keep on requesting until the result is received?

答:
Checkout Django 3 ASGI (Asynchronous Server Gateway Interface) support:

https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/

Body:
I want to create a third party chatbot API which is asynchronous and replies "ok" after 10 seconds pause.

import time

def wait():
    time.sleep(10)
    return "ok"

# views.py
def api(request):
    return wait()

I have tried celery for the same as follows where I am waiting for celery response in view itself:

import time
from celery import shared_task

@shared_task
def wait():
    time.sleep(10)
    return "ok"

# views.py
def api(request):
    a = wait.delay()
    work = AsyncResult(a.id)
    while True:
        if work.ready():
           return work.get(timeout=1)

But this solution works synchronously and makes no difference. How can we make it asynchronous without asking our user to keep on requesting until the result is received?


问:
Can't delete breakpoint at flutter color in Visual Studio Code
I have a color which is set on a button and I had set a breakpoint there in order to see the button being created.

RaisedButton(

color: Colors.blue,   << breakpoint on this line

The color blue is shown as a blue rectangle in the breakpoint column, so when I right click on it to get the breakpoint context menu up, the menu doesn't appear.
To delete the breakpoint, must I delete the line and re-write it?

答:
No, you don't need to delete and rewrite the line, instead,
you can see all your added breakpoints in Visual Studio Code from here and select/unselect them as needed.
Hope this helps. :)


问:
TypeError: can only concatenate str (not "int") to str: What does it mean?
```<code>from tkinter import*
import random
from tkinter import messagebox
window=Tk()
window.title("Random Tools")
window.configure(background="light green")
textvaria = IntVar()
textvaria2 = IntVar()

label0 = Label(window, text = "Min", bg ="light green")
label0.grid(row=1, column=0)

spinboxmin = Spinbox(window, from_=1, to=9999, increment=1, textvariable=textvaria)
spinboxmin.grid(row=2, column=0)
a = spinboxmin.get()

label1 = Label(window, text="Max", bg="light green")
label1.grid(row=3, column=0)

spinboxmax = Spinbox(window, from_=1, to=9999, increment=1, textvariable=textvaria2)
spinboxmax.grid(row = 4, column =0)
b = spinboxmax.get()

def submit2():
    if a <= b:
        answertext.delete('1.0', END)
    else:
        messagebox.showerror("Error", "Max must be greater than min!")

submit = Button(text="Submit", command=submit2)
submit.grid(row=4, column=2)

n = random.randint(a, b+1)

answertext = Text(text=n)
answertext.grid(row=5, column=0)

window.mainloop()
</code>```

I'm doing a GUI for randoming numbers. But when I run this in Python Module, it said:
"TypeError: can only concatenate str (not "int") to str"
Can someone help me with this?
Thank a lot.

答:
You have to replace :

```<code>a  = spinboxmin.get()
b = spinboxmax.get()
</code>```

With:

```<code>a = textvaria.get()
b = textvaria2.get()
</code>```

Body:
from tkinter import*
import random
from tkinter import messagebox
window=Tk()
window.title("Random Tools")
window.configure(background="light green")
textvaria = IntVar()
textvaria2 = IntVar()

label0 = Label(window, text = "Min", bg ="light green")
label0.grid(row=1, column=0)

spinboxmin = Spinbox(window, from_=1, to=9999, increment=1, textvariable=textvaria)
spinboxmin.grid(row=2, column=0)
a = spinboxmin.get()

label1 = Label(window, text="Max", bg="light green")
label1.grid(row=3, column=0)

spinboxmax = Spinbox(window, from_=1, to=9999, increment=1, textvariable=textvaria2)
spinboxmax.grid(row = 4, column =0)
b = spinboxmax.get()

def submit2():
    if a <= b:
        answertext.delete('1.0', END)
    else:
        messagebox.showerror("Error", "Max must be greater than min!")

submit = Button(text="Submit", command=submit2)
submit.grid(row=4, column=2)

n = random.randint(a, b+1)

answertext = Text(text=n)
answertext.grid(row=5, column=0)

window.mainloop()

I'm doing a GUI for randoming numbers. But when I run this in Python Module, it said:
"TypeError: can only concatenate str (not "int") to str"
Can someone help me with this?
Thank a lot.

Body:
You have to replace :

a  = spinboxmin.get()
b = spinboxmax.get()

With:

a = textvaria.get()
b = textvaria2.get()


问:
Challenging MySQL query
I'm working on a blogging app that requires a unique query.

Problem: I need to display one parent post, all it's children posts (up to a certain number before requiring pagination), and up to 5 comments associated with each child post, and the parent.

I wrote this query, but it doesn't work because it will return only 5 comments that belong to the parent post.

```<code>SELECT
    posts.id, posts.postTypeId, posts.parentId, posts.ownerUserId, posts.body
, users.id AS authorId, users.displayname AS authorDisplayName
, comments.id AS commentId, comments.text AS commentText
, comments.commentOwnerUserId, comments.commentOwnerDisplayName
FROM posts
JOIN users ON posts.owneruserid = users.id
LEFT JOIN ( SELECT comments.id, comments.postId, comments.text, commenters.id AS commentOwnerUserId, commenters.displayname AS commentOwnerDisplayName
        FROM comments
        JOIN users AS commenters ON comments.userid = commenters.id
        ORDER BY comments.createdat ASC
        LIMIT 0,5 ) AS comments ON comments.postid = posts.id
WHERE posts.id = @postId OR posts.parentId = @postId
ORDER BY posts.posttypeid, posts.createdAt
</code>```

The query returns the parent post, all it's children, and the first 5 comments it encounters, (usually they belong to the parent because we are ordering by postTypeId, and the parent is the first post). If the first post doesn't have 5 comments, it moves on the next post and returns those comments, until the 5 limit is reached.

What I need is to return one parent post and all it's children posts, and up to 5 comments for each child, the parent. I also need the owner data for each post and comment.

UPDATE I'm open to doing this with more than one query if it will scale well. The only condition is that the parent and children posts retrieval happens in the same query.

Any idea how I can write such a query? I included my schema below.

```<code>/* Posts table */
CREATE TABLE `posts` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `posttypeid` int(10) NOT NULL,
  `parentid` int(10) DEFAULT NULL,
  `body` text NOT NULL,
  `userid` int(10) NOT NULL,
  `createdat` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
KEY `parentId` (`parentid`)
KEY `userId` (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=572 DEFAULT CHARSET=utf8

/* Comments table */
CREATE TABLE `comments` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `postid` int(10) NOT NULL,
  `userid` int(10) NOT NULL,
  `text` text NOT NULL,
  `createdat` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `postId` (`postid`),
  KEY `userId` (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8

/* users table */
CREATE TABLE `users` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `email` varchar(50) NOT NULL,
  `displayname` varchar(50) NOT NULL,
  `createdat` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`),
) ENGINE=InnoDB AUTO_INCREMENT=66 DEFAULT CHARSET=utf8
</code>```

答:
I assume you will have paging of some sort to restrict the amount of top level posts.

You would also need some summary information on the number of comments, childposts in the posts table or a post summary table.

The comments table would need sequence column by post

1: Get all parent posts, (parentId = 0) & construct an IN clause of postids

2: Get all children posts by passing the postids obtained in 1, order by postid which will help in segregation. Add these posts to the overall IN clause
   Get comments by passing the postids from 1 & 2.
   Restrict the number of comments by using the number of comments & the sequence column
   For ex:  join comments & post_summary where post_comment_seq between (noofcommentsforthepost - 5) and noofcommentsforthepost

You can look at in clause performance here Performance of MYSQL "IN"

Title: Challenging MySQL query

Body:
I'm working on a blogging app that requires a unique query.

Problem: I need to display one parent post, all it's children posts (up to a certain number before requiring pagination), and up to 5 comments associated with each child post, and the parent.

I wrote this query, but it doesn't work because it will return only 5 comments that belong to the parent post.

SELECT
    posts.id, posts.postTypeId, posts.parentId, posts.ownerUserId, posts.body
, users.id AS authorId, users.displayname AS authorDisplayName
, comments.id AS commentId, comments.text AS commentText
, comments.commentOwnerUserId, comments.commentOwnerDisplayName
FROM posts
JOIN users ON posts.owneruserid = users.id
LEFT JOIN ( SELECT comments.id, comments.postId, comments.text, commenters.id AS commentOwnerUserId, commenters.displayname AS commentOwnerDisplayName
        FROM comments
        JOIN users AS commenters ON comments.userid = commenters.id
        ORDER BY comments.createdat ASC
        LIMIT 0,5 ) AS comments ON comments.postid = posts.id
WHERE posts.id = @postId OR posts.parentId = @postId
ORDER BY posts.posttypeid, posts.createdAt

The query returns the parent post, all it's children, and the first 5 comments it encounters, (usually they belong to the parent because we are ordering by postTypeId, and the parent is the first post). If the first post doesn't have 5 comments, it moves on the next post and returns those comments, until the 5 limit is reached.

What I need is to return one parent post and all it's children posts, and up to 5 comments for each child, the parent. I also need the owner data for each post and comment.

UPDATE I'm open to doing this with more than one query if it will scale well. The only condition is that the parent and children posts retrieval happens in the same query.

Any idea how I can write such a query? I included my schema below.

/* Posts table */
CREATE TABLE `posts` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `posttypeid` int(10) NOT NULL,
  `parentid` int(10) DEFAULT NULL,
  `body` text NOT NULL,
  `userid` int(10) NOT NULL,
  `createdat` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
KEY `parentId` (`parentid`)
KEY `userId` (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=572 DEFAULT CHARSET=utf8

/* Comments table */
CREATE TABLE `comments` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `postid` int(10) NOT NULL,
  `userid` int(10) NOT NULL,
  `text` text NOT NULL,
  `createdat` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `postId` (`postid`),
  KEY `userId` (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8

/* users table */
CREATE TABLE `users` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `email` varchar(50) NOT NULL,
  `displayname` varchar(50) NOT NULL,
  `createdat` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`),
) ENGINE=InnoDB AUTO_INCREMENT=66 DEFAULT CHARSET=utf8


问:
Elasticsearch partial search of words | Angular
i am working on a search service for an angular project. I can search for usernames and i want to enable partial search, for example Username: "Brown" should be found while searching for "brow". If possible i want to do that with the URL only, without changing too much. http://URL:9200/users/_doc/_search?q=username:'; this is what i used for my GET requests and then added the written text from the search bar to it and got all informations from the database. </p>

答:
You can use a query string query with a wildcard.</p>

```<code>curl -XGET http://127.0.0.1:9200/users/doc/_search -d '{"query":{"query_string":{"query":"brow*", "fields":["username"]}}}'
</code>```

Body:
You can use a query string query with a wildcard.

curl -XGET http://127.0.0.1:9200/users/doc/_search -d '{"query":{"query_string":{"query":"brow*", "fields":["username"]}}}'


问:
How to get all contracts with SendindBlue's API?
I'm getting the contracts belongs to certain list with the code below. But they have 500 contacts per page limit and I have 5000. How can I loop with an offset?</p>

```<code>$limit = 500; // int | Number of documents per page
$offset = 0; // int | Index of the first document of the page

try {
    $result = $apiInstance->getContactsFromList($listId, $modifiedSince, $limit, $offset);
    print_r($result);
} catch (Exception $e) {
    echo 'Exception when calling ContactsApi->getContactsFromList: ', $e->getMessage(), PHP_EOL;
}
</code>```

答:
I think this is what you need, basically it reads the data in chunks (specified by $limit) and each time it reads a full chunk, it adjusts the offset to read the next page...

```<code>$limit = 500; // int | Number of documents per page
$offset = 0; // int | Index of the first document of the page

try {
    do {
        $result = $apiInstance->getContactsFromList($listId, $modifiedSince, $limit, $offset);
        // How much data has been passed back,
        $received = count($result);
        // Just to see each page being received
        echo $received.PHP_EOL;
        // Move offset on by entries in this page
        $offset += $received;
    }
    // Carry on while a full page has been retrieved
    while ($received == $limit);
} catch (Exception $e) {
    echo 'Exception when calling ContactsApi->getContactsFromList: ', $e->getMessage(), PHP_EOL;
}
</code>```

I'm assuming that

```<code>$received = count($result);
</code>```

will work.

Body:
I'm getting the contracts belongs to certain list with the code below. But they have 500 contacts per page limit and I have 5000. How can I loop with an offset?

$limit = 500; // int | Number of documents per page
$offset = 0; // int | Index of the first document of the page

try {
    $result = $apiInstance->getContactsFromList($listId, $modifiedSince, $limit, $offset);
    print_r($result);
} catch (Exception $e) {
    echo 'Exception when calling ContactsApi->getContactsFromList: ', $e->getMessage(), PHP_EOL;
}

Body:
I think this is what you need, basically it reads the data in chunks (specified by $limit) and each time it reads a full chunk, it adjusts the offset to read the next page...

$limit = 500; // int | Number of documents per page
$offset = 0; // int | Index of the first document of the page

try {
    do {
        $result = $apiInstance->getContactsFromList($listId, $modifiedSince, $limit, $offset);
        // How much data has been passed back,
        $received = count($result);
        // Just to see each page being received
        echo $received.PHP_EOL;
        // Move offset on by entries in this page
        $offset += $received;
    }
    // Carry on while a full page has been retrieved
    while ($received == $limit);
} catch (Exception $e) {
    echo 'Exception when calling ContactsApi->getContactsFromList: ', $e->getMessage(), PHP_EOL;
}

I'm assuming that

$received = count($result);

will work.


问:
How to count unique values over multiple columns using R?
Let's say I have the following df:

```<code>1               2                    3
home, work      work, home           home, work
leisure, work   work, home, leisure  work, home
home, leisure   work, home           home, work
</code>```

I want to count all unique variables over the entire data.frame (not by columns or row, I'm interested in the cell values)

So the output should look like this:

```<code>                    freq
home, work          3
leisure, work       1
home, leisure       1
work, home          3
work, home, leisure 1
</code>```

I have not found a way to do that. The count() function seems to work only with single columns.

Thank you very much for the help:)

答:
You could unlist and use table to get count in base R :

```<code>stack(table(unlist(df)))
#Same as
#stack(table(as.matrix(df)))
</code>```

If you prefer tidyverse get data in long format using pivot_longer and count.

```<code>df %>%
  tidyr::pivot_longer(cols = everything()) %>%
  dplyr::count(value)

# A tibble: 5 x 2
#  value                 n
#  <chr>             <int>
#1 home,leisure          1
#2 home,work             3
#3 leisure,work          1
#4 work,home             3
#5 work,home,leisure     1
</code>```

data

```<code>df <- structure(list(X1 = c("home,work", "leisure,work", "home,leisure"
), X2 = c("work,home", "work,home,leisure", "work,home"), X3 = c("home,work",
"work,home", "home,work")), class = "data.frame", row.names = c(NA, -3L))
</code>```

Body:
Let's say I have the following df:

1               2                    3
home, work      work, home           home, work
leisure, work   work, home, leisure  work, home
home, leisure   work, home           home, work

I want to count all unique variables over the entire data.frame (not by columns or row, I'm interested in the cell values)

So the output should look like this:

                    freq
home, work          3
leisure, work       1
home, leisure       1
work, home          3
work, home, leisure 1

I have not found a way to do that. The count() function seems to work only with single columns.

Thank you very much for the help:)

Body:
You could unlist and use table to get count in base R :

stack(table(unlist(df)))
#Same as
#stack(table(as.matrix(df)))

If you prefer tidyverse get data in long format using pivot_longer and count.

df %>%
  tidyr::pivot_longer(cols = everything()) %>%
  dplyr::count(value)

# A tibble: 5 x 2
#  value                 n
#  <chr>             <int>
#1 home,leisure          1
#2 home,work             3
#3 leisure,work          1
#4 work,home             3
#5 work,home,leisure     1

data

df <- structure(list(X1 = c("home,work", "leisure,work", "home,leisure"
), X2 = c("work,home", "work,home,leisure", "work,home"), X3 = c("home,work",
"work,home", "home,work")), class = "data.frame", row.names = c(NA, -3L))


问:
Finding grok pattern for file with varying structure
I have a log file where not all the lines are in the same format. How do I find the correct grok pattern for such a file.

```<code>[15:37:20:030|1] [TdmUtil.c: 1534:fnTDM_LoadLocalFoo] F_LAA       : 1
[15:37:20:032|1] [TdmUtil.c: 1281:fnTDM_GetPreDef]  pdeGetData : MAX_IRAT_NBR_PER_SERVED_CELL_SYS = 256
[15:37:20:091|1] [TdmUtil.c:  293:fnTDM_PrtIndexKey] fnTDM_GetIndexKeyNum Error!!
</code>```

In this way few of the lines are in the format of line1, few in the format of line2 and so on. I could write a grok pattern for each of these lines, but I have no idea how to combine them. Is there any way to solve this ?

答:
I have put something together for you. but before I share it with you I suggest you to work with online GROK debugger in order to write your GROK pattern (there is 1 inside Kibana if you are working with it under Dev Tools -> GROK debugger).
You should also check out the available GROK patterns.

I see all 3 lines has the same prefix which is [time|num] [class: line number: function name] log text I have created a GROK patter for that. if you want to break down the log text further you can do so by uncomment the second match over the text field and provide the needed grok patter.

NOTE: you can add as many more match sections as you want, but beware that it will try to run the match on all of them. try using if else statements to navigate through for high complexity- usually it is not needed.

```<code>input {
    file {
        path => "C:/work/elastic/logstash-6.5.0/config/test.txt"
        start_position => "beginning"
        codec => multiline {
            pattern => "^\[%{TIME}\|"
            negate => true
            what => "previous"
        }
        type => "whatever"
    }
}
filter {
    if [type] == "whatever" {
        grok {
            break_on_match => false
            match => { "message" => "^\[%{TIME:time}\|%{NUMBER:num}\]%{SPACE}\[%{DATA:class}:%{SPACE}%{NUMBER:linenumber:int}:%{DATA:function}\]%{GREEDYDATA:text}$"}
            #match => { "text" => ""}
        }
    }
}

output {
    elasticsearch {
        hosts => ["http://localhost:9200"]
        index => "test"
    }
}
</code>```

The above configuration file will provide you with the following fields in Kibana:

Body:
I have a log file where not all the lines are in the same format. How do I find the correct grok pattern for such a file.

[15:37:20:030|1] [TdmUtil.c: 1534:fnTDM_LoadLocalFoo] F_LAA       : 1
[15:37:20:032|1] [TdmUtil.c: 1281:fnTDM_GetPreDef]  pdeGetData : MAX_IRAT_NBR_PER_SERVED_CELL_SYS = 256
[15:37:20:091|1] [TdmUtil.c:  293:fnTDM_PrtIndexKey] fnTDM_GetIndexKeyNum Error!!

In this way few of the lines are in the format of line1, few in the format of line2 and so on. I could write a grok pattern for each of these lines, but I have no idea how to combine them. Is there any way to solve this ?

Body:
I have put something together for you. but before I share it with you I suggest you to work with online GROK debugger in order to write your GROK pattern (there is 1 inside Kibana if you are working with it under Dev Tools -> GROK debugger).
You should also check out the available GROK patterns.

I see all 3 lines has the same prefix which is [time|num] [class: line number: function name] log text I have created a GROK patter for that. if you want to break down the log text further you can do so by uncomment the second match over the text field and provide the needed grok patter.

NOTE: you can add as many more match sections as you want, but beware that it will try to run the match on all of them. try using if else statements to navigate through for high complexity- usually it is not needed.

input {
    file {
        path => "C:/work/elastic/logstash-6.5.0/config/test.txt"
        start_position => "beginning"
        codec => multiline {
            pattern => "^\[%{TIME}\|"
            negate => true
            what => "previous"
        }
        type => "whatever"
    }
}
filter {
    if [type] == "whatever" {
        grok {
            break_on_match => false
            match => { "message" => "^\[%{TIME:time}\|%{NUMBER:num}\]%{SPACE}\[%{DATA:class}:%{SPACE}%{NUMBER:linenumber:int}:%{DATA:function}\]%{GREEDYDATA:text}$"}
            #match => { "text" => ""}
        }
    }
}

output {
    elasticsearch {
        hosts => ["http://localhost:9200"]
        index => "test"
    }
}

The above configuration file will provide you with the following fields in Kibana:


问:
How to create a dictionary from 2 lists and other dictionary in Python?
Answer here.

1.First I created variables POWER, gandalf and saruman as seen above in the code then a variable called spells to store the number of spells that the sorcerers cast.

code

```<code>POWER = {
    'Fireball': 50,
    'Lightning bolt': 40,
    'Magic arrow': 10,
    'Black Tentacles': 25,
    'Contagion': 45
}

gandalf = ['Fireball', 'Lightning bolt', 'Lightning bolt', 'Magic arrow', 'Fireball',
           'Magic arrow', 'Lightning bolt', 'Fireball', 'Fireball', 'Fireball']
saruman = ['Contagion', 'Contagion', 'Black Tentacles', 'Fireball', 'Black Tentacles',
           'Lightning bolt', 'Magic arrow', 'Contagion', 'Magic arrow', 'Magic arrow']
spells=10

</code>```

Then created two variables called gandalf_wins and saruman_wins. Set both of them to 0.

```<code>gandalf_wins=0
saruman_wins=0
</code>```

And Lastly two variables called gandalf_power and saruman_power to store the list of spell powers of each sorcerer.

```<code>gandalf_power=[]
saruman_power=[]
</code>```

The battle starts! Using the variables you've created above, code the execution of spell clashes. Remember that a sorcerer wins if he succeeds in winning 3 spell clashes in a row.
If a clash ends up in a tie, the counter of wins in a row is not restarted to 0. Remember to print who is the winner of the battle.

I am stucked here because I don't know how to create a dictionary for each with the spells and the power of this spells. Then, how should I compare them? Thanks in advance!

答:
I think the steps are instructed pretty clear, using a for loop is enough to solve the 3rd part.

For the 4th part, you can use zip, to iterrate both list at the same time.

```<code>for gandalf_pow, saruman_pow in zip(gandalf_power, saruman_power):
    # compare
</code>```

Body:
Answer here.

1.First I created variables POWER, gandalf and saruman as seen above in the code then a variable called spells to store the number of spells that the sorcerers cast.

code

POWER = {
    'Fireball': 50,
    'Lightning bolt': 40,
    'Magic arrow': 10,
    'Black Tentacles': 25,
    'Contagion': 45
}

gandalf = ['Fireball', 'Lightning bolt', 'Lightning bolt', 'Magic arrow', 'Fireball',
           'Magic arrow', 'Lightning bolt', 'Fireball', 'Fireball', 'Fireball']
saruman = ['Contagion', 'Contagion', 'Black Tentacles', 'Fireball', 'Black Tentacles',
           'Lightning bolt', 'Magic arrow', 'Contagion', 'Magic arrow', 'Magic arrow']
spells=10

Then created two variables called gandalf_wins and saruman_wins. Set both of them to 0.

gandalf_wins=0
saruman_wins=0

And Lastly two variables called gandalf_power and saruman_power to store the list of spell powers of each sorcerer.

gandalf_power=[]
saruman_power=[]

The battle starts! Using the variables you've created above, code the execution of spell clashes. Remember that a sorcerer wins if he succeeds in winning 3 spell clashes in a row.
If a clash ends up in a tie, the counter of wins in a row is not restarted to 0. Remember to print who is the winner of the battle.

I am stucked here because I don't know how to create a dictionary for each with the spells and the power of this spells. Then, how should I compare them? Thanks in advance!

Body:
I think the steps are instructed pretty clear, using a for loop is enough to solve the 3rd part.

For the 4th part, you can use zip, to iterrate both list at the same time.

for gandalf_pow, saruman_pow in zip(gandalf_power, saruman_power):
    # compare


问:
A specified logon session does not exist. it may already have been terminated outlook 365 error
Unable to configure profile after installing Outlook 365.

It throws the error: A specified logon session does not exist. it may already have been terminated

Problem background:

I had a working Outlook 2016 which I uninstalled and installed the new Office 365 Outlook after which I'm unable to configure my Outlook profile.

答:
Disclaimer: Answering my own question, so that others shall not get stuck where I did.

This error occurs due to conflict with previous left-over older Outlook configurations with the new Office365 Outlook.

I had to follow all these steps in the given order to resolve the issue.

STEP - 1:

Delete old Outlook profile (Warning: You'll lose the local copy of all emails, on removing the profile)

Go to "Control Panel" --> "Mail" option.

Click on "Show Profiles"

Remove all profiles from there.

STEP - 2:

Delete all files from the Accounts folder.

C:\Users\rlal1\AppData\Local\Packages\Microsoft.AAD.BrokerPlugin_cw5n1h2txyewy\AC\TokenBroker\Accounts

Delete everything present in the above directory. Restart your PC and try logging in to Outlook.

If it doesn't works follow the next steps.

STEP - 3:

Create a new Registry key

Open Registry Editor and navigate to below registry path.

HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Common\Identity

Switch to the right-panel window and create a new key (DWORD 32-Bit value) with the following name  DisableADALatopWAMOverride.

Double-click on the value to change its Value Data from ‘0’ to ‘1’.

Now, create another new key (DWORD 32-Bit value) with the following name  EnableADAL.

Double-click the entry and set its value to ‘0’.

Finally, restart Windows and try to create a new Outlook profile again.


问:
how to check if given variable is a collection of html elements?
For example a type of data that getElementsByClassName or getElementsByTagName produces.

答:
Try this:

```<code>function isCollection(input)
{
    return input.item != undefined;
}
</code>```

But beware any other objects with the method item defined.

Body:
Try this:

function isCollection(input)
{
    return input.item != undefined;
}

But beware any other objects with the method item defined.


问:
Python class scope and threading
I am a little confused about python class scope. Also about its relation to threading. Below is a minimal working example. I created an instance of B and passed it to the instance of A.

The way I understand it A should be making its own local copy of B_instance. Apparently this is not happening since every time I modify an attribute of B_instance by any imaginable means I see the change in both A_instance and B_instance (prints 1 -6). Does this mean that A_instance.other_class is regarded as global? Is there a way to make A_instance.other_class local? so that modifying it wouldn´t change B_instance itself.

The second part of the question is related to threading. I know that access to class attributes is not thread-safe so I am using locks. However if you take a look at the print statements I would expect "lock released" to be printed before "modified by main thread". What am I missing? Both locks seem to be locking something else because apparently the lock in the main thread can be acquired even though the one in A_instance is still in effect. I feel like this contradicts my findings from the first part.

Is it possible to acquire a lock for the whole object, not just its attribute or method?

```<code>class A:

    def __init__(self, other_class):
        self.lock = threading.Lock()
        self.other_class = other_class

    def increment_B(self):
        self.other_class.B_attr_1 += 1

    def set_B(self):
        self.other_class.B_attr_1 = 10

    def thread_modify_attr(self):
        self.lock.acquire()
        self.other_class.B_attr_1 = "modified by class"
        time.sleep(10)
        self.lock.release()
        print("lock released")

class B:

    def __init__(self):
        self.B_attr_1 = 0

if __name__ == "__main__":

    B_instance = B()

    A_instance = A(B_instance)

    print("1:", B_instance.B_attr_1)

    A_instance.other_class.B_attr_1 += 1
    print("2:", B_instance.B_attr_1)

    A_instance.other_class.B_attr_1 = 10
    print("3:", B_instance.B_attr_1)

    A_instance.increment_B()
    print("4:", B_instance.B_attr_1)

    A_instance.set_B()
    print("5:", B_instance.B_attr_1)

    B_instance.B_attr_1 = 0
    print("6:", A_instance.other_class.B_attr_1)

    lock = threading.Lock()

    t = threading.Thread(target=A_instance.thread_modify_attr)
    t.start()
    print("thread started")

    print(B_instance.B_attr_1)

    lock.acquire()
    B_instance.B_attr_1 = "modified by main thread"
    lock.release()

    print(B_instance.B_attr_1)
    print("done")

    t.join()
</code>```

Results:

```<code>1: 0
2: 1
3: 10
4: 11
5: 10
6: 0
thread started
modified by class
modified by main thread
done
lock released
</code>```

If somebody knows about some good place to read about details of python scoping I would appreciate it.

答:
Just an extension to @Gil's answer above

You can see a visual explanation of how Python deals with your classes, their instances and the references to them on this PythonTutor snippet I created for you.

Lock can operate as a context manager, so you can use it in a with statement, and it gets released automatically when the with block exits for any reason (e.g. an exception).

```<code>def thread_modify_attr(self):
    with self.lock:
        self.other_class.B_attr_1 = "modified by class"
        time.sleep(10)
    print("lock released")
</code>```

Note: In case the link above has gone dead, just go to PythonTutor.com directly and copy and paste this modified version of your code. The only change is that I removed everything to do with Threading, as that is not supported by the site.

```<code>class A:

    def __init__(self, other_class):
        self.other_class = other_class

    def increment_B(self):
        self.other_class.B_attr_1 += 1

    def set_B(self):
        self.other_class.B_attr_1 = 10

class B:

    def __init__(self):
        self.B_attr_1 = 0

if __name__ == "__main__":

    B_instance = B()

    A_instance = A(B_instance)

    print("1:", B_instance.B_attr_1)

    A_instance.other_class.B_attr_1 += 1
    print("2:", B_instance.B_attr_1)

    A_instance.other_class.B_attr_1 = 10
    print("3:", B_instance.B_attr_1)

    A_instance.increment_B()
    print("4:", B_instance.B_attr_1)

    A_instance.set_B()
    print("5:", B_instance.B_attr_1)

    B_instance.B_attr_1 = 0
    print("6:", A_instance.other_class.B_attr_1)

    print(B_instance.B_attr_1)
    print("done")
</code>```

Title: Python class scope and threading

Body:
I am a little confused about python class scope. Also about its relation to threading. Below is a minimal working example. I created an instance of B and passed it to the instance of A.

The way I understand it A should be making its own local copy of B_instance. Apparently this is not happening since every time I modify an attribute of B_instance by any imaginable means I see the change in both A_instance and B_instance (prints 1 -6). Does this mean that A_instance.other_class is regarded as global? Is there a way to make A_instance.other_class local? so that modifying it wouldn´t change B_instance itself.

The second part of the question is related to threading. I know that access to class attributes is not thread-safe so I am using locks. However if you take a look at the print statements I would expect "lock released" to be printed before "modified by main thread". What am I missing? Both locks seem to be locking something else because apparently the lock in the main thread can be acquired even though the one in A_instance is still in effect. I feel like this contradicts my findings from the first part.

Is it possible to acquire a lock for the whole object, not just its attribute or method?

class A:

    def __init__(self, other_class):
        self.lock = threading.Lock()
        self.other_class = other_class

    def increment_B(self):
        self.other_class.B_attr_1 += 1

    def set_B(self):
        self.other_class.B_attr_1 = 10

    def thread_modify_attr(self):
        self.lock.acquire()
        self.other_class.B_attr_1 = "modified by class"
        time.sleep(10)
        self.lock.release()
        print("lock released")

class B:

    def __init__(self):
        self.B_attr_1 = 0

if __name__ == "__main__":

    B_instance = B()

    A_instance = A(B_instance)

    print("1:", B_instance.B_attr_1)

    A_instance.other_class.B_attr_1 += 1
    print("2:", B_instance.B_attr_1)

    A_instance.other_class.B_attr_1 = 10
    print("3:", B_instance.B_attr_1)

    A_instance.increment_B()
    print("4:", B_instance.B_attr_1)

    A_instance.set_B()
    print("5:", B_instance.B_attr_1)

    B_instance.B_attr_1 = 0
    print("6:", A_instance.other_class.B_attr_1)

    lock = threading.Lock()

    t = threading.Thread(target=A_instance.thread_modify_attr)
    t.start()
    print("thread started")

    print(B_instance.B_attr_1)

    lock.acquire()
    B_instance.B_attr_1 = "modified by main thread"
    lock.release()

    print(B_instance.B_attr_1)
    print("done")

    t.join()

Results:

1: 0
2: 1
3: 10
4: 11
5: 10
6: 0
thread started
modified by class
modified by main thread
done
lock released

If somebody knows about some good place to read about details of python scoping I would appreciate it.

Body:
Just an extension to @Gil's answer above

You can see a visual explanation of how Python deals with your classes, their instances and the references to them on this PythonTutor snippet I created for you.

Lock can operate as a context manager, so you can use it in a with statement, and it gets released automatically when the with block exits for any reason (e.g. an exception).

def thread_modify_attr(self):
    with self.lock:
        self.other_class.B_attr_1 = "modified by class"
        time.sleep(10)
    print("lock released")

Note: In case the link above has gone dead, just go to PythonTutor.com directly and copy and paste this modified version of your code. The only change is that I removed everything to do with Threading, as that is not supported by the site.

class A:

    def __init__(self, other_class):
        self.other_class = other_class

    def increment_B(self):
        self.other_class.B_attr_1 += 1

    def set_B(self):
        self.other_class.B_attr_1 = 10

class B:

    def __init__(self):
        self.B_attr_1 = 0

if __name__ == "__main__":

    B_instance = B()

    A_instance = A(B_instance)

    print("1:", B_instance.B_attr_1)

    A_instance.other_class.B_attr_1 += 1
    print("2:", B_instance.B_attr_1)

    A_instance.other_class.B_attr_1 = 10
    print("3:", B_instance.B_attr_1)

    A_instance.increment_B()
    print("4:", B_instance.B_attr_1)

    A_instance.set_B()
    print("5:", B_instance.B_attr_1)

    B_instance.B_attr_1 = 0
    print("6:", A_instance.other_class.B_attr_1)

    print(B_instance.B_attr_1)
    print("done")


问:
pthread RWlock quesion
I am using a translator because I am not good at English.

```<code>#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <fcntl.h>
#include <unistd.h>

pthread_rwlock_t R_Lock;
int ac=0;

void* RD_LOCK(void* arg) {
    pthread_rwlock_rdlock(&R_Lock);
    printf("%d\n",ac); // ac is global variable 0
    sleep(1);
    pthread_rwlock_unlock(&R_Lock);
}
void* WR_LOCK(void* arg) {
    pthread_rwlock_wrlock(&R_Lock);
    printf("RW LCOK\n");
    ac++;
    printf("%d\n",ac);
    sleep(1);
    pthread_rwlock_unlock(&R_Lock);
}
void DO_RW_LCOK(){
    pthread_t RW[3];
    pthread_rwlock_init(&R_Lock, NULL);
    pthread_create(&RW[0], NULL, RD_LOCK,NULL); //==0 thread
    pthread_create(&RW[1], NULL, RD_LOCK,NULL); //==1 thread
    pthread_create(&RW[2], NULL, WR_LOCK,NULL); //==2 thread
    pthread_rwlock_destroy(&R_Lock);
    for(int i=0; i<3;i++)
    pthread_join(RW[i],NULL);
}
int main(){
    DO_RW_LCOK();
    return 0;
}

void* RD_LOCK(void* arg) {

  pthread_rwlock_rdlock(&R_Lock);
  printf("%d\n",ac); // ac is global variable 0
  sleep(1);
  pthread_rwlock_unlock(&R_Lock); }

void* WR_LOCK(void* arg) {

  pthread_rwlock_wrlock(&R_Lock);
  ac++;
  printf("%d\n",ac);
  sleep(1);
  pthread_rwlock_unlock(&R_Lock);
}
int main(){
  DO_RW_LOCK();
  return 0;
}
</code>```

I tried to execute 3 threads.

0,1 thread used readlock and 2 thread used writelcok.

My prediction after the program runs After the 0,1 thread, 2 thread was executed.

However, the run order is 2thread,0thread,1thread

I don't understand this.

答:
Threads are always unpredictable. So the order may really change and be unexpected.
In order to guarantee that your threads will be in the order that you want them to be, add a wait option which will make the thread wait if the other threads are not done. Just use wait and notify.
I did not get which thread type you are using but here is a pseudocode.</p>

```<code>Lock waitAndNotify;
int rdDone = 0;
void* RD_LOCK(void* arg) {
  pthread_rwlock_rdlock(&R_Lock);
  rdDone++;
  notify(waitAndNotify);
  printf("%d\n",ac); // ac is global variable 0
  sleep(1);
  pthread_rwlock_unlock(&R_Lock); }

void* WR_LOCK(void* arg) {

  pthread_rwlock_wrlock(&R_Lock);
  if(rdDone!=2)
    wait(waitAndNotify);
  ac++;
  printf("%d\n",ac);
  sleep(1);
  pthread_rwlock_unlock(&R_Lock);
}
</code>```

Title: pthread RWlock quesion

Body:
I am using a translator because I am not good at English.

#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <fcntl.h>
#include <unistd.h>

pthread_rwlock_t R_Lock;
int ac=0;

void* RD_LOCK(void* arg) {
    pthread_rwlock_rdlock(&R_Lock);
    printf("%d\n",ac); // ac is global variable 0
    sleep(1);
    pthread_rwlock_unlock(&R_Lock);
}
void* WR_LOCK(void* arg) {
    pthread_rwlock_wrlock(&R_Lock);
    printf("RW LCOK\n");
    ac++;
    printf("%d\n",ac);
    sleep(1);
    pthread_rwlock_unlock(&R_Lock);
}
void DO_RW_LCOK(){
    pthread_t RW[3];
    pthread_rwlock_init(&R_Lock, NULL);
    pthread_create(&RW[0], NULL, RD_LOCK,NULL); //==0 thread
    pthread_create(&RW[1], NULL, RD_LOCK,NULL); //==1 thread
    pthread_create(&RW[2], NULL, WR_LOCK,NULL); //==2 thread
    pthread_rwlock_destroy(&R_Lock);
    for(int i=0; i<3;i++)
    pthread_join(RW[i],NULL);
}
int main(){
    DO_RW_LCOK();
    return 0;
}

void* RD_LOCK(void* arg) {

  pthread_rwlock_rdlock(&R_Lock);
  printf("%d\n",ac); // ac is global variable 0
  sleep(1);
  pthread_rwlock_unlock(&R_Lock); }

void* WR_LOCK(void* arg) {

  pthread_rwlock_wrlock(&R_Lock);
  ac++;
  printf("%d\n",ac);
  sleep(1);
  pthread_rwlock_unlock(&R_Lock);
}
int main(){
  DO_RW_LOCK();
  return 0;
}

I tried to execute 3 threads.

0,1 thread used readlock and 2 thread used writelcok.

My prediction after the program runs After the 0,1 thread, 2 thread was executed.

However, the run order is 2thread,0thread,1thread

I don't understand this.

Body:
Threads are always unpredictable. So the order may really change and be unexpected.
In order to guarantee that your threads will be in the order that you want them to be, add a wait option which will make the thread wait if the other threads are not done. Just use wait and notify.
I did not get which thread type you are using but here is a pseudocode.

Lock waitAndNotify;
int rdDone = 0;
void* RD_LOCK(void* arg) {
  pthread_rwlock_rdlock(&R_Lock);
  rdDone++;
  notify(waitAndNotify);
  printf("%d\n",ac); // ac is global variable 0
  sleep(1);
  pthread_rwlock_unlock(&R_Lock); }

void* WR_LOCK(void* arg) {

  pthread_rwlock_wrlock(&R_Lock);
  if(rdDone!=2)
    wait(waitAndNotify);
  ac++;
  printf("%d\n",ac);
  sleep(1);
  pthread_rwlock_unlock(&R_Lock);
}


问:
AWS RDS MySQL performance
I am running MySQL 8 on AWS RDS, I have an InnoDB type table with 260,000 rows inside, no extraordinary data size.

My development server features 1GB RAM, 1vCPU, and my AWS RDS server is t3.small.

SELECT Count operations take too long (average 33 seconds) and my data tables in my Laravel project time out, what could be the problem?

```<code>select count('special_cargo_id') from special_cargos
</code>```

33seconds

答:
Is special_cargo_id your PK, what is it's type, and does it fit into innodb_buffer_pool_size?

Run:

```<code>select count(1) from special_cargos;
</code>```

a few times. Does it run quickly after the first time? If it does, then the reason it slows down sometimes is because you are memory starved and other data pushes your PK on that table out of the innodb_buffer_pool. If it is always slow, the PK most likely never fits into the buffer pool.

Title: AWS RDS MySQL performance

Body:
I am running MySQL 8 on AWS RDS, I have an InnoDB type table with 260,000 rows inside, no extraordinary data size.

My development server features 1GB RAM, 1vCPU, and my AWS RDS server is t3.small.

SELECT Count operations take too long (average 33 seconds) and my data tables in my Laravel project time out, what could be the problem?

select count('special_cargo_id') from special_cargos

33seconds

Body:
Is special_cargo_id your PK, what is it's type, and does it fit into innodb_buffer_pool_size?

Run:

select count(1) from special_cargos;

a few times. Does it run quickly after the first time? If it does, then the reason it slows down sometimes is because you are memory starved and other data pushes your PK on that table out of the innodb_buffer_pool. If it is always slow, the PK most likely never fits into the buffer pool.


问:
Call immediately executing function from outside
I've got an immediately executing function and I need to call it from outside:

```<code>(function myFunc(){
  console.log("Hello from myFunc");
})();
</code>```

I'm using named function because I'm doing a recursion in it so I can reference it. but at some point recursion stops. and I need to invoke this function once again.

答:
Is there a reason you have to wrap it like that? Why don't you just make a normal named function and call it:</p>

```<code>function myFunc(){
  console.log("Hello from myFunc");
}
myfunc();
</code>```

Body:
I've got an immediately executing function and I need to call it from outside:

(function myFunc(){
  console.log("Hello from myFunc");
})();

I'm using named function because I'm doing a recursion in it so I can reference it. but at some point recursion stops. and I need to invoke this function once again.

Body:
Is there a reason you have to wrap it like that? Why don't you just make a normal named function and call it:

function myFunc(){
  console.log("Hello from myFunc");
}
myfunc();


答:
You can use Conditional Aggregation through GROUPing BY mydate,shift :

```<code>SELECT mydate,shift,
       SUM(CASE WHEN mass > 3 THEN 1 ELSE 0 END) AS "mass>3",
       SUM(CASE WHEN mass >10 THEN 1 ELSE 0 END) AS "mass>10"
  FROM t
 GROUP BY mydate,shift
 ORDER BY mydate,shift;
</code>```

By the way( as you asked for it within a comment ), you can also use DECODE() function :

```<code>SELECT mydate,shift,
       SUM(DECODE(SIGN(mass-3),1,1,0)) AS "mass>3",
       SUM(DECODE(SIGN(mass-10),1,1,0)) AS "mass>10"
  FROM t
 GROUP BY mydate,shift
 ORDER BY mydate,shift
</code>```

Demo

Title: How to Use Group By on the Basis of Column Value?

Body:
I am trying to use Group By but unable to achieve the output
I want to Group by with Date, shift and with Mass.

Data is like :

date     | shift | mass
---------+-------+------
01-05-20 | A     | 5
01-05-20 | B     | 3
01-05-20 | B     | 3
02-05-20 | A     | 11
02-05-20 | A     | 5
02-05-20 | C     | 12
02-05-20 | C     | 12
02-05-20 | B     | 5

OutPut which i want

date     | shift | mass>3 | mass>10
---------+-------+--------+--------
01-05-20 | A     | 1      | 0
01-05-20 | B     | 2      | 0
02-05-20 | A     | 1      | 1
02-05-20 | B     | 1      | 0
02-05-20 | C     | 0      | 2

Body:
You can use Conditional Aggregation through GROUPing BY mydate,shift :

SELECT mydate,shift,
       SUM(CASE WHEN mass > 3 THEN 1 ELSE 0 END) AS "mass>3",
       SUM(CASE WHEN mass >10 THEN 1 ELSE 0 END) AS "mass>10"
  FROM t
 GROUP BY mydate,shift
 ORDER BY mydate,shift;

By the way( as you asked for it within a comment ), you can also use DECODE() function :

SELECT mydate,shift,
       SUM(DECODE(SIGN(mass-3),1,1,0)) AS "mass>3",
       SUM(DECODE(SIGN(mass-10),1,1,0)) AS "mass>10"
  FROM t
 GROUP BY mydate,shift
 ORDER BY mydate,shift

Demo


问:
Spring boot interceptor, intercept the problem of returning Chinese garbled characters
Spring boot interceptor, intercept the problem of returning Chinese garbled characters.

Code structure as shown

code show as below

demoFilter

```<code>public class demoFilter extends GenericFilterBean {

  @Override
  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;

    response.getWriter().write("您好");
    return;

  }
}
</code>```

FilterConfig

```<code>@Configuration
public class FilterConfig {

  @Bean
  public FilterRegistrationBean jwtFilter() {
    final FilterRegistrationBean registrationBean = new FilterRegistrationBean();
    registrationBean.setFilter(new demoFilter());
    registrationBean.addUrlPatterns("/*");
    return registrationBean;
  }

}

</code>```

controller

```<code>@RestController
public class Demo {

  @RequestMapping(value = "demo", method = RequestMethod.GET)
  public String getStr(HttpServletRequest request, HttpServletResponse response) {
    return "demo";
  }
}
</code>```

SpringApplication

```<code>@SpringBootApplication
public class DemoApplication {

  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }
}
</code>```

Project start, visit http://localhost:8080/demo

Actual return:??

Expected return:您好

I added the following configuration to application.properties:

```<code>spring.http.encoding.force=true
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
server.tomcat.uri-encoding=UTF-8
</code>```

Browser access, return:

Postman visits and returns correct results.

I would like to ask, how to solve this problem perfectly, so that the browser returns the correct Chinese.

答:
It has been solved, and the following code is added to solve the problem:

response.setContentType("text/html;charset=UTF-8");
```

Body:
Spring boot interceptor, intercept the problem of returning Chinese garbled characters.

Code structure as shown

code show as below

demoFilter

public class demoFilter extends GenericFilterBean {

  @Override
  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;

    response.getWriter().write("您好");
    return;

  }
}

FilterConfig

@Configuration
public class FilterConfig {

  @Bean
  public FilterRegistrationBean jwtFilter() {
    final FilterRegistrationBean registrationBean = new FilterRegistrationBean();
    registrationBean.setFilter(new demoFilter());
    registrationBean.addUrlPatterns("/*");
    return registrationBean;
  }

}

controller

@RestController
public class Demo {

  @RequestMapping(value = "demo", method = RequestMethod.GET)
  public String getStr(HttpServletRequest request, HttpServletResponse response) {
    return "demo";
  }
}

SpringApplication

@SpringBootApplication
public class DemoApplication {

  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }
}

Project start, visit http://localhost:8080/demo

Actual return:??

Expected return:您好

I added the following configuration to application.properties:

spring.http.encoding.force=true
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
server.tomcat.uri-encoding=UTF-8

Browser access, return:

Postman visits and returns correct results.

I would like to ask, how to solve this problem perfectly, so that the browser returns the correct Chinese.


问:
MYSQL Query Date Between
What is wrong with this query </p>

```<code>select  a.TESTDATE  from testr a,XREFRTGTE b where a.id = b.id and a.TESTDATE between BETWEEN STR_TO_DATE('2011-05-26 12:22:33','YYYY-MM-DD HH:MM:SS') AND STR_TO_DATE('2011-06-02 12:22:33','YYYY-MM-DD HH:MM:SS') limit 200
</code>```

<p>Please help </p>

答:
I can see two between used in the query:

```<code>... between BETWEEN ...
</code>```

Try dropping one.

Title: MYSQL Query Date Between

Body:
What is wrong with this query

select  a.TESTDATE  from testr a,XREFRTGTE b where a.id = b.id and a.TESTDATE between BETWEEN STR_TO_DATE('2011-05-26 12:22:33','YYYY-MM-DD HH:MM:SS') AND STR_TO_DATE('2011-06-02 12:22:33','YYYY-MM-DD HH:MM:SS') limit 200

Please help

Body:
I can see two between used in the query:

... between BETWEEN ...

Try dropping one.


答:
The below is using zip to loop through the spells and compares each rounds spell power.</p>

```<code>POWER = {
    'Fireball': 50,
    'Lightning bolt': 40,
    'Magic arrow': 10,
    'Black Tentacles': 25,
    'Contagion': 45
}

gandalf = ['Fireball', 'Lightning bolt', 'Lightning bolt', 'Magic arrow', 'Fireball', 'Magic arrow', 'Lightning bolt', 'Fireball', 'Fireball', 'Fireball']
saruman = ['Contagion', 'Contagion', 'Black Tentacles', 'Fireball', 'Black Tentacles', 'Lightning bolt', 'Magic arrow', 'Contagion', 'Magic arrow', 'Magic arrow']
spells=10

gandalf_wins=0
saruman_wins=0

for gandalf_spell, saruman_spell in zip(gandalf,saruman):
    if POWER[gandalf_spell] > POWER[saruman_spell]:
        gandalf_wins+=1
    elif POWER[saruman_spell] > POWER[gandalf_spell]:
        saruman_wins+=1

print(f"Gandalf won {gandalf_wins} times, Saruman won {saruman_wins} times")
</code>```

Title: How to create a dictionary from 2 lists and other dictionary in Python?

Body:
The below is using zip to loop through the spells and compares each rounds spell power.

POWER = {
    'Fireball': 50,
    'Lightning bolt': 40,
    'Magic arrow': 10,
    'Black Tentacles': 25,
    'Contagion': 45
}

gandalf = ['Fireball', 'Lightning bolt', 'Lightning bolt', 'Magic arrow', 'Fireball', 'Magic arrow', 'Lightning bolt', 'Fireball', 'Fireball', 'Fireball']
saruman = ['Contagion', 'Contagion', 'Black Tentacles', 'Fireball', 'Black Tentacles', 'Lightning bolt', 'Magic arrow', 'Contagion', 'Magic arrow', 'Magic arrow']
spells=10

gandalf_wins=0
saruman_wins=0

for gandalf_spell, saruman_spell in zip(gandalf,saruman):
    if POWER[gandalf_spell] > POWER[saruman_spell]:
        gandalf_wins+=1
    elif POWER[saruman_spell] > POWER[gandalf_spell]:
        saruman_wins+=1

print(f"Gandalf won {gandalf_wins} times, Saruman won {saruman_wins} times")


答:
you should refer Python Dictionaries. They are just like lists and tuples only the difference is that they are like database's table where you have rows and columns for storing different values

https://www.w3schools.com/python/python_dictionaries.asp
Refer this for help

Body:
Answer here.

1.First I created variables POWER, gandalf and saruman as seen above in the code then a variable called spells to store the number of spells that the sorcerers cast.

code

POWER = {
    'Fireball': 50,
    'Lightning bolt': 40,
    'Magic arrow': 10,
    'Black Tentacles': 25,
    'Contagion': 45
}

gandalf = ['Fireball', 'Lightning bolt', 'Lightning bolt', 'Magic arrow', 'Fireball',
           'Magic arrow', 'Lightning bolt', 'Fireball', 'Fireball', 'Fireball']
saruman = ['Contagion', 'Contagion', 'Black Tentacles', 'Fireball', 'Black Tentacles',
           'Lightning bolt', 'Magic arrow', 'Contagion', 'Magic arrow', 'Magic arrow']
spells=10

Then created two variables called gandalf_wins and saruman_wins. Set both of them to 0.

gandalf_wins=0
saruman_wins=0

And Lastly two variables called gandalf_power and saruman_power to store the list of spell powers of each sorcerer.

gandalf_power=[]
saruman_power=[]

The battle starts! Using the variables you've created above, code the execution of spell clashes. Remember that a sorcerer wins if he succeeds in winning 3 spell clashes in a row.
If a clash ends up in a tie, the counter of wins in a row is not restarted to 0. Remember to print who is the winner of the battle.

I am stucked here because I don't know how to create a dictionary for each with the spells and the power of this spells. Then, how should I compare them? Thanks in advance!