问:
Uploading to Amazon S3 gives 403 error - following example photo album guide
I'm trying to upload a simple image to a S3 bucket, I always get a 403 error when try to upload, but list and createAlbum methods works.

I've followed this guide: Uploading Photos to Amazon S3 from a Browser - AWS SDK for JavaScript

Since the upload of the tutorial don't work for me I've tried to use the S3.upload method without success as follow:

```<code>    S3.upload({
      Key: 'my-album/aqui.png',
      Body: file,
      ACL: 'public-read',
      Bucket: SOUNDS_BUCKET_NAME
      }, function(err, data) {
        if(err) {
          alert('fail')
        } else {
          alert('Successfully Uploaded!');
        }
      }
    );
</code>```

I believe this error was a config on my S3 or my identity pool, but the config is the same as the tutorial:

CORS

```<code><?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>DELETE</AllowedMethod>
    <AllowedMethod>HEAD</AllowedMethod>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
</code>```

Cognito:

S3:

What am I doing wrong?

答:
This is Node.js code to upload files to S3.

Setting up the Environment

AWS Credentials

To get started you need to generate the AWS Security Key Access Credentials first. To do so login to your AWS Management Console.

Click on your username:

Select Access Keys -> Create New Access Key:

After that you can either copy the Access Key ID and Secret Access Key from this window or you can download it as a .CSV file:

Creating an S3 Bucket

Now let's create a AWS S3 Bucket with proper access. We can do this using the AWS management console or by using Node.js.

To create an S3 bucket using the management console, go to the S3 service by selecting it from the service menu:

Select "Create Bucket" and enter the name of your bucket and the region that you want to host your bucket. If you already know from which region the majority of your users will come from, it's wise to select a region as close to their's as possible. This will ensure that the files from the server will be served in a more optimal timeframe.

The name you select for your bucket should be a unique name among all AWS users, so try a new one if the name is not available:

Follow through the wizard and configure permissions and other setting per your requirements.

To create the bucket using Node.js, we'll first have to set up our development environment.

Development Environment

Get started with our example by configuring a new Node.js project:

$ npm init
```

<p>To start using any AWS Cloud Services in Node.js, we have to install the <em>AWS SDK</em> (System Development Kit).</p>

<p>Install it using your preferred package manager - we'll use <code>npm</code>:</p>

<pre class="lang-none prettyprint-override"><code>$ npm i --save aws-sdk
</code>```

Implementation

Creating an S3 Bucket

If you have already created a bucket manually, you may skip this part. But if not, let's create a file, say, create-bucket.js in your project directory.

Import the aws-sdk library to access your S3 bucket:

const AWS = require('aws-sdk');
```

<p>Now, let's define three constants to store <code>ID</code>, <code>SECRET</code>, and <code>BUCKET_NAME</code>. These are used to identify and access our bucket:</p>

<pre class="lang-none prettyprint-override"><code>// Enter copied or downloaded access ID and secret key here
const ID = '';
const SECRET = '';

// The name of the bucket that you have created
const BUCKET_NAME = 'test-bucket';
</code>```

Now we need to initialize the S3 interface by passing our access keys:

const s3 = new AWS.S3({
    accessKeyId: ID,
    secretAccessKey: SECRET
});
```

Source: Uploading Files to AWS S3 with Node.js

Body:
I'm trying to upload a simple image to a S3 bucket, I always get a 403 error when try to upload, but list and createAlbum methods works.

I've followed this guide: Uploading Photos to Amazon S3 from a Browser - AWS SDK for JavaScript

Since the upload of the tutorial don't work for me I've tried to use the S3.upload method without success as follow:

    S3.upload({
      Key: 'my-album/aqui.png',
      Body: file,
      ACL: 'public-read',
      Bucket: SOUNDS_BUCKET_NAME
      }, function(err, data) {
        if(err) {
          alert('fail')
        } else {
          alert('Successfully Uploaded!');
        }
      }
    );

I believe this error was a config on my S3 or my identity pool, but the config is the same as the tutorial:

CORS

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>DELETE</AllowedMethod>
    <AllowedMethod>HEAD</AllowedMethod>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

Cognito:

S3:

What am I doing wrong?

Body:
This is Node.js code to upload files to S3.

Setting up the Environment

AWS Credentials

To get started you need to generate the AWS Security Key Access Credentials first. To do so login to your AWS Management Console.

Click on your username:

Select Access Keys -> Create New Access Key:

After that you can either copy the Access Key ID and Secret Access Key from this window or you can download it as a .CSV file:

Creating an S3 Bucket

Now let's create a AWS S3 Bucket with proper access. We can do this using the AWS management console or by using Node.js.

To create an S3 bucket using the management console, go to the S3 service by selecting it from the service menu:

Select "Create Bucket" and enter the name of your bucket and the region that you want to host your bucket. If you already know from which region the majority of your users will come from, it's wise to select a region as close to their's as possible. This will ensure that the files from the server will be served in a more optimal timeframe.

The name you select for your bucket should be a unique name among all AWS users, so try a new one if the name is not available:

Follow through the wizard and configure permissions and other setting per your requirements.

To create the bucket using Node.js, we'll first have to set up our development environment.

Development Environment

Get started with our example by configuring a new Node.js project:

$ npm init

To start using any AWS Cloud Services in Node.js, we have to install the AWS SDK (System Development Kit).

Install it using your preferred package manager - we'll use npm:

$ npm i --save aws-sdk

Implementation

Creating an S3 Bucket

If you have already created a bucket manually, you may skip this part. But if not, let's create a file, say, create-bucket.js in your project directory.

Import the aws-sdk library to access your S3 bucket:

const AWS = require('aws-sdk');

Now, let's define three constants to store ID, SECRET, and BUCKET_NAME. These are used to identify and access our bucket:

// Enter copied or downloaded access ID and secret key here
const ID = '';
const SECRET = '';

// The name of the bucket that you have created
const BUCKET_NAME = 'test-bucket';

Now we need to initialize the S3 interface by passing our access keys:

const s3 = new AWS.S3({
    accessKeyId: ID,
    secretAccessKey: SECRET
});

Source: Uploading Files to AWS S3 with Node.js


来源: stackexchange

问:
How to retrieve all id of firebase database content using Angular?
I am trying to retrieve all firebase database content with their IDs. Currently I have two functions, getAll() and get(input) which returns one specific product with the given ID. My current implementation gives me all the objects from firebase database without the IDs. What do I need to change to be able to get all objects with their IDs?</p>

```<code>product.service.ts

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';
import { Product } from './admin/product-form/product-interface';

@Injectable({
  providedIn: 'root'
})
export class ProductService {

  constructor(private db: AngularFireDatabase) { }

  create(product){
    return this.db.list('/products').push(product);

  }

  getAll() {
    return this.db.list('/products').valueChanges();

  }

  get(productId){
    return this.db.object('/products/' + productId).valueChanges();
  }
}

product-form.component.ts

import { Product } from './product-interface';
import { ProductService } from './../../product.service';
import { CategoryService } from './../../category.service';
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { take } from 'rxjs/operators';

@Component({
  selector: 'app-product-form',
  templateUrl: './product-form.component.html',
  styleUrls: ['./product-form.component.css']
})

export class ProductFormComponent implements OnInit {
  categories$;
  product = {};
  // product:Product;

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private categoryService: CategoryService,
    private productService: ProductService)
    {

    }

   save(product){
     this.productService.create(product);
     this.router.navigate(['/admin/products']);
   }

  ngOnInit(): void {
    this.categories$ = this.categoryService.getCategories();
    let id = this.route.snapshot.paramMap.get('id');
    this.productService.getAll().subscribe((a) =>
    this.product = a);

  }

}

admin-products.component.ts

import { ProductService } from './../../product.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-admin-products',
  templateUrl: './admin-products.component.html',
  styleUrls: ['./admin-products.component.css']
})
export class AdminProductsComponent implements OnInit {
  products$;
  constructor(private productService: ProductService) {
    this.products$ = this.productService.getAll()
   }

  ngOnInit(): void {
    this.products$.subscribe(p => {
      console.log(p, 'products');
    })
  }

}

admin-products.component.html

<p>
<a routerLink = "/admin/products/new" class="btn btn-primary">New Product</a>
</p>

<table class="table">
    <thead>
        <tr>
            <th>Title</th>
            <th>Price</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let p of products$ | async">
            <td>{{ p.title }}</td>
            <td>{{ p.price}}</td>
            <td>
                <a [routerLink]="['/admin/products/', p.$key]">Edit</a>
            </td>
        </tr>
    </tbody>
</table>

</code>```

答:
You'll need to use snapshotChanges() instead of valueChanges(). valueChanges() only gives you the document data while snapshotChanges() will also give you metadata.

View relevant docs

ContentLicense: CC BY-SA 4.0

Body:
I am trying to retrieve all firebase database content with their IDs. Currently I have two functions, getAll() and get(input) which returns one specific product with the given ID. My current implementation gives me all the objects from firebase database without the IDs. What do I need to change to be able to get all objects with their IDs?

product.service.ts

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';
import { Product } from './admin/product-form/product-interface';

@Injectable({
  providedIn: 'root'
})
export class ProductService {

  constructor(private db: AngularFireDatabase) { }

  create(product){
    return this.db.list('/products').push(product);

  }

  getAll() {
    return this.db.list('/products').valueChanges();

  }

  get(productId){
    return this.db.object('/products/' + productId).valueChanges();
  }
}

product-form.component.ts

import { Product } from './product-interface';
import { ProductService } from './../../product.service';
import { CategoryService } from './../../category.service';
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { take } from 'rxjs/operators';

@Component({
  selector: 'app-product-form',
  templateUrl: './product-form.component.html',
  styleUrls: ['./product-form.component.css']
})

export class ProductFormComponent implements OnInit {
  categories$;
  product = {};
  // product:Product;

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private categoryService: CategoryService,
    private productService: ProductService)
    {

    }

   save(product){
     this.productService.create(product);
     this.router.navigate(['/admin/products']);
   }

  ngOnInit(): void {
    this.categories$ = this.categoryService.getCategories();
    let id = this.route.snapshot.paramMap.get('id');
    this.productService.getAll().subscribe((a) =>
    this.product = a);

  }

}

admin-products.component.ts

import { ProductService } from './../../product.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-admin-products',
  templateUrl: './admin-products.component.html',
  styleUrls: ['./admin-products.component.css']
})
export class AdminProductsComponent implements OnInit {
  products$;
  constructor(private productService: ProductService) {
    this.products$ = this.productService.getAll()
   }

  ngOnInit(): void {
    this.products$.subscribe(p => {
      console.log(p, 'products');
    })
  }

}

admin-products.component.html

New Product

            Title
            Price

            {{ p.title }}
            {{ p.price}}

                Edit


问:
calculating in python
What I have done so far:

```<code>import datetime
   distance_tobecovered = float(input("Please enter a number for the startime = input("Please input the time for the alarm in format HH:")
    fixed_charge = 3.5
    perkilo_charge = 2.1 * distance_tobecovered
    valueforall = fixed_charge + perkilo_charge
    v = valueforall + (2 * distance_tobecovered * 0.99
</code>```

)

答: You are comparing input_time.hour to integers. There is no integer N such that 23 <= N <= 6, so the condition in your elif statement will never be true. You should simply replace the elif statement with an else.

Title: calculating in python

Body:
What I have done so far:

import datetime
   distance_tobecovered = float(input("Please enter a number for the startime = input("Please input the time for the alarm in format HH:")
    fixed_charge = 3.5
    perkilo_charge = 2.1 * distance_tobecovered
    valueforall = fixed_charge + perkilo_charge
    v = valueforall + (2 * distance_tobecovered * 0.99

)


问:
Convert string to title case after dash or slash
I use this common function to convert most of my list items to title case with no issues.  I've discovered one place that needs improvement, when there is a dash or slash in the middle, I want the next letter capitalized.

For example Hispanic/latino should be Hispanic/Latino.  Basically capitalize when the first letter or proceeded by a symbol OR a space.

Current code:

```<code>function toTitleCase(str) {
    return str.toLowerCase().replace(/(?:^|\s)\w/g, function (match) {
        return match.toUpperCase();
    });
}
</code>```

答:
Here's a solution that strips the dashes. So for the following input:

```<code>list-item
</code>```

It returns:

```<code>ListItem
</code>```

An extension of Jamiec's solution that will achieve this is:

function toTitleCase(str) {
    return str.toLowerCase().replace(/(?:^|[\s-/])\w/g, function (match) {
        return match.toUpperCase();
    }).replace('-', '');
}
console.log(toTitleCase("list-item"));```

ContentLicense: CC BY-SA 3.0

Body:
I use this common function to convert most of my list items to title case with no issues.  I've discovered one place that needs improvement, when there is a dash or slash in the middle, I want the next letter capitalized.

For example Hispanic/latino should be Hispanic/Latino.  Basically capitalize when the first letter or proceeded by a symbol OR a space.

Current code:

function toTitleCase(str) {
    return str.toLowerCase().replace(/(?:^|\s)\w/g, function (match) {
        return match.toUpperCase();
    });
}

Body:
Here's a solution that strips the dashes. So for the following input:

list-item

It returns:

ListItem

An extension of Jamiec's solution that will achieve this is:

function toTitleCase(str) {
    return str.toLowerCase().replace(/(?:^|[\s-/])\w/g, function (match) {
        return match.toUpperCase();
    }).replace('-', '');
}
console.log(toTitleCase("list-item"));


问:
How to put value of Dash-Plotly dropdown to a python variable?
I was able to print the value of the dropdown using a callback. Is there any way to put this value in a python variable?

I want to use it (turkey) in an API endpoint.

答:
If you have the value in a callback, then it already is a Python variable. I assume you did something similar to this?

@app.callback(
    Output('my-output', 'value')
    Inputs[('my-input', 'value')])
def callback_func(dropdown_value):
    print(dropdown_value)
```

You can use dropdown_value here in that function just like any other Python variable. It is limited to the scope of the function, but you could do things to make it accessible elsewhere, just like with other variables in functions. You could write it to a file, add it to a list or dict from some other context, and so on.

Body:
If you have the value in a callback, then it already is a Python variable. I assume you did something similar to this?

@app.callback(
    Output('my-output', 'value')
    Inputs[('my-input', 'value')])
def callback_func(dropdown_value):
    print(dropdown_value)

You can use dropdown_value here in that function just like any other Python variable. It is limited to the scope of the function, but you could do things to make it accessible elsewhere, just like with other variables in functions. You could write it to a file, add it to a list or dict from some other context, and so on.


问:
Question about the "Getting Started with BigQuery ML" excercise
Did somebody work on this exercise ? It is a way to estimate transaction in JUNE 2017.
https://codelabs.developers.google.com/codelabs/bqml-intro/index.html#0

When we compare orders JUNE 2017 prediction (step6) versus reality (meaning what we have in BQ), the difference is quite important (more than 50%) - do you know why?

答:
Comparing a single datapoint may not be the best way to evaluate the model performance.

Please start with reviewing the output of ML.Evaluate to understand how the model is behaving overall.


问:
How to select values from a CSV file depending on the value of a specific column
Take this csv as an example:

```<code>Col1, Col2
1,3,
0,5,
1,4
0,7
</code>```

Say that I have a list, and I want to append the values of Col2 to the list only if the value of Col1 in the same row is 1. The resulting list should be [3,4].

How can I do this with pandas without using iterrows()?

答:
Assuming you've read in your csv into a dataframe named df, you could use this:

```<code>wanted = df.query('Col1 == 1')['Col2'].values
mylist.extend(wanted)
</code>```

Body:
Take this csv as an example:

Col1, Col2
1,3,
0,5,
1,4
0,7

Say that I have a list, and I want to append the values of Col2 to the list only if the value of Col1 in the same row is 1. The resulting list should be [3,4].

How can I do this with pandas without using iterrows()?

Body:
Assuming you've read in your csv into a dataframe named df, you could use this:

wanted = df.query('Col1 == 1')['Col2'].values
mylist.extend(wanted)


问:
What causes the shape error in numpy.dot when a vector is multiplied with a matrix?
```<code>a= [1, 2, 3, 2.5]
b= [[0.2, 0.8, -0.5, 1.0],
    [0.5, -0.91, 0.26, -0.5],
    [-0.26, -0.27, 0.17, 0.87]]

print(np.dot(b,a))
print(np.dot(a,b))
</code>```

Why does the first line print but the second line cause a shape alignment error?

"ValueError: shapes (4,) and (3,4) not aligned: 4 (dim 0) != 3 (dim 0)"

What calculation is numpy trying to do that will cause that error?

Note - I understand matrix multiplication.

Thanks for any help you can give!

Edit - Fixed some variable names

答:
a is a vector (maybe matrix (1,4), but u should reshape it maybe)

b is a matrix (3,4)

so u can do only (3,4)x(4,1) or (1,4)x(4,3)

try weights * inputs.T or respahe inputs

try inputs * weights.T

Body:
a= [1, 2, 3, 2.5]
b= [[0.2, 0.8, -0.5, 1.0],
    [0.5, -0.91, 0.26, -0.5],
    [-0.26, -0.27, 0.17, 0.87]]

print(np.dot(b,a))
print(np.dot(a,b))

Why does the first line print but the second line cause a shape alignment error?

"ValueError: shapes (4,) and (3,4) not aligned: 4 (dim 0) != 3 (dim 0)"

What calculation is numpy trying to do that will cause that error?

Note - I understand matrix multiplication.

Thanks for any help you can give!

Edit - Fixed some variable names


问:
Reactjs best practice for updating component depending on url
I was wondering what is the best practice in ReactJS to update a component's content depending on the url.
Let say I have a navbar with some buttons in it. I want to display some of the buttons depending on the url.

For exemple, when the url is /home I want my navbar to be:

```<code><nav>
     <button>Button 1</button>
     <button>Button 2</button>
     <button>Button 3</button>
</nav>
</code>```

And when it's /about I want

```<code><nav>
     <button>Button 2</button>
</nav>
</code>```

My main component would be something like:

```<code><Router>
    <Header />
    <Switch>
        <Route path="/home">
            <Home />
        </Route>
        <Route path="/about">
            <About />
        </Route>
     </Switch>
</Router>
</code>```

So my navbar is in the  component.
My first guess would be to use react-router to get the current url and then change what is rendered in the

```<code>render() {
    let buttons
    if(location === "/home") {
        buttons = <button>Button 1</button><button>Button 2</button><button>Button 3</button>
    } else {
        buttons = <button>Button 2</button>
    }
    return (
       <nav>
           {buttons}
       </nav>
    )
}
</code>```

Is it a good practice? Is there a better way? Should I use react-redux for the conditionnal rendering? (I'm new to react-redux and I'm trying to see all the possibilities)

P.S.: the code is not perfect because I typed it quickly direct in the message box sorry for that.

答:
you could use a ternary-operator, although there is nothing wrong with the implementation you have right now

```<code>    import React,{Fragment,Component} from 'react';
    import { useLocation} from "react-router-dom";

    class Header extends Component{
     let location = useLocation();
       render() {
        return (
           <nav>
              {
            location.pathname==='/home'?
             (<Fragment>
              <button>Button 1</button>
              <button>Button 2</button>
              <button>Button 3</button>
             </Fragment>): (<Fragment>
              <button>Button 2</button>
             </Fragment>)
            }
           </nav>
        )
    }
  }
}
</code>```

and in your main component you could also use Route from react-router-dom

```<code> import React,{Component} from 'react';
 import {BrowserRouter as Router,Route,Switch} from "react-router-dom";
 import Home from './Home';
 import About from './About';

  class App extends Component{
  render(){
   return(
      <Router>
       <Header />
       <Switch>
         <Route to="/home" component={Home}/>
         <Route to="/about" component={About}/>
       </Switch>
      </Router>
     );
    }
   }
  }
</code>```

Again, this is just a personal preference rather than anything else,but it certainly cleans things up a little

Body:
I was wondering what is the best practice in ReactJS to update a component's content depending on the url.
Let say I have a navbar with some buttons in it. I want to display some of the buttons depending on the url.

For exemple, when the url is /home I want my navbar to be:

     <button>Button 1</button>
     <button>Button 2</button>
     <button>Button 3</button>

And when it's /about I want

     <button>Button 2</button>

My main component would be something like:

<Router>

    <Switch>
        <Route path="/home">
            <Home />
        </Route>
        <Route path="/about">
            <About />
        </Route>
     </Switch>
</Router>

So my navbar is in the  component.
My first guess would be to use react-router to get the current url and then change what is rendered in the

render() {
    let buttons
    if(location === "/home") {
        buttons = <button>Button 1</button><button>Button 2</button><button>Button 3</button>
    } else {
        buttons = <button>Button 2</button>
    }
    return (

           {buttons}

    )
}

Is it a good practice? Is there a better way? Should I use react-redux for the conditionnal rendering? (I'm new to react-redux and I'm trying to see all the possibilities)

P.S.: the code is not perfect because I typed it quickly direct in the message box sorry for that.

Body:
you could use a ternary-operator, although there is nothing wrong with the implementation you have right now

    import React,{Fragment,Component} from 'react';
    import { useLocation} from "react-router-dom";

    class Header extends Component{
     let location = useLocation();
       render() {
        return (
           <nav>
              {
            location.pathname==='/home'?
             (<Fragment>
              <button>Button 1</button>
              <button>Button 2</button>
              <button>Button 3</button>
             </Fragment>): (<Fragment>
              <button>Button 2</button>
             </Fragment>)
            }
           </nav>
        )
    }
  }
}

and in your main component you could also use Route from react-router-dom

 import React,{Component} from 'react';
 import {BrowserRouter as Router,Route,Switch} from "react-router-dom";
 import Home from './Home';
 import About from './About';

  class App extends Component{
  render(){
   return(
      <Router>
       <Header />
       <Switch>
         <Route to="/home" component={Home}/>
         <Route to="/about" component={About}/>
       </Switch>
      </Router>
     );
    }
   }
  }

Again, this is just a personal preference rather than anything else,but it certainly cleans things up a little


问:
Unable to resolve IDbContext while activating Service
Working in CQRS with MediatR, in Startup I register the DomainEventDispatcher, the Repos, Query- and Eventhandlers and the Services.
The repos work with DbContext and so do my services. Everything CRUD works until I inject my Service in the Controller,
I get the following error:
Unable to resolve service for type 'IDbContext' while attempting to activate 'Service'.

I Find it strange seeing as I

```<code>    services.AddDbContext<DbContext>(options =>
      {
        options.UseLazyLoadingProxies().UseSqlServer(cs);
        options.EnableSensitiveDataLogging(true);
      });
</code>```

before registering the following:

```<code>services
.AddScoped<IDomainEventsDispatcher, DomainEventsDispatcher>()
.AddScoped<IRepo<ToDoItem>, EfCRepo<ToDoItem>>()
.AddMediatR(cfg => cfg.AsScoped(), typeof(ToDoItemsQueryHandler).GetTypeInfo().Assembly)
.AddScoped<INotificationHandler<Event>, EventHandler>()
.AddMediatR(cfg => cfg.AsScoped(), typeof(EventHandler).GetTypeInfo().Assembly);
.AddScoped<IService, Service>()
</code>```

When I try to AddScoped the IDbContext with the

```<code>AddScoped<IDbContext, DbContext>()
</code>```

My Context is empty and cannot Get entities from Db anymore.

I find it strange that I would need to AddScoped the IDbContext for the services,
seeing as the Repos work with the DbContext as well, without needing to resolve service for type IDbContext.

I've looked at MediatR official documentation and couldn't find anything on how to register Services,
and googling 'register services MediatR startup' redirects mostly to other issues,
so any help/insights from you guys is more than welcome!

I've made a new question as I can dependency inject, but somehow seems different for services. Most questions on S/O regarding registering in startup are more generic to my feeling.

Thanks in advance!

答:
For future references:
The solution was indeed to add

```<code>AddScoped<IDbContext, DbContext>()
</code>```

Must have been something else that broke my context

Body:
Working in CQRS with MediatR, in Startup I register the DomainEventDispatcher, the Repos, Query- and Eventhandlers and the Services.
The repos work with DbContext and so do my services. Everything CRUD works until I inject my Service in the Controller,
I get the following error:
Unable to resolve service for type 'IDbContext' while attempting to activate 'Service'.

I Find it strange seeing as I

    services.AddDbContext<DbContext>(options =>
      {
        options.UseLazyLoadingProxies().UseSqlServer(cs);
        options.EnableSensitiveDataLogging(true);
      });

before registering the following:

services
.AddScoped<IDomainEventsDispatcher, DomainEventsDispatcher>()
.AddScoped<IRepo<ToDoItem>, EfCRepo<ToDoItem>>()
.AddMediatR(cfg => cfg.AsScoped(), typeof(ToDoItemsQueryHandler).GetTypeInfo().Assembly)
.AddScoped<INotificationHandler<Event>, EventHandler>()
.AddMediatR(cfg => cfg.AsScoped(), typeof(EventHandler).GetTypeInfo().Assembly);
.AddScoped<IService, Service>()

When I try to AddScoped the IDbContext with the

AddScoped<IDbContext, DbContext>()

My Context is empty and cannot Get entities from Db anymore.

I find it strange that I would need to AddScoped the IDbContext for the services,
seeing as the Repos work with the DbContext as well, without needing to resolve service for type IDbContext.

I've looked at MediatR official documentation and couldn't find anything on how to register Services,
and googling 'register services MediatR startup' redirects mostly to other issues,
so any help/insights from you guys is more than welcome!

I've made a new question as I can dependency inject, but somehow seems different for services. Most questions on S/O regarding registering in startup are more generic to my feeling.

Thanks in advance!

Body:
For future references:
The solution was indeed to add

AddScoped<IDbContext, DbContext>()

Must have been something else that broke my context


问:
Write a script which for any name given as an argument prints the list of paths to home directories of people with the name
I did it in this way and it's working. Is there another way to get the same result?</p>

```<code>!/bin/bash

for name in $@

do

        awk -v n="$name" -F ':' 'BEGIN{IGNORECASE=1};$5~n{print $6}' /etc/passwd | while read line

        do
                echo $line
        done
done
</code>```

答:
You can do it it in pure bash, using its regular expression matching:

```<code>#!/usr/bin/env bash
IFS="|"; command eval 'name="$*"'
getent passwd | while IFS= read line; do
    IFS=: read -a fields <<<"$line"
    if [[ ${fields[4]} =~ $name ]]; then
    echo "${fields[5]}"
    fi
done
</code>```

The IFS="|"; command eval 'name="$*"' line sets name to the command line arguments separated by pipes so they work as alternatives in the regular expression. (See Bash FAQ 104 for details about the syntax of that line and alternatives.)

Example:

```<code>$ bash demo.sh "[Ss]ystemd" "[Rr]oot"
/root
/run/systemd
/run/systemd/netif
/run/systemd/resolve
/run/systemd
</code>```

Body:
I did it in this way and it's working. Is there another way to get the same result?

!/bin/bash

for name in $@

do

        awk -v n="$name" -F ':' 'BEGIN{IGNORECASE=1};$5~n{print $6}' /etc/passwd | while read line

        do
                echo $line
        done
done

Body:
You can do it it in pure bash, using its regular expression matching:

#!/usr/bin/env bash
IFS="|"; command eval 'name="$*"'
getent passwd | while IFS= read line; do
    IFS=: read -a fields <<<"$line"
    if [[ ${fields[4]} =~ $name ]]; then
    echo "${fields[5]}"
    fi
done

The IFS="|"; command eval 'name="$*"' line sets name to the command line arguments separated by pipes so they work as alternatives in the regular expression. (See Bash FAQ 104 for details about the syntax of that line and alternatives.)

Example:

$ bash demo.sh "[Ss]ystemd" "[Rr]oot"
/root
/run/systemd
/run/systemd/netif
/run/systemd/resolve
/run/systemd


问:
How to get Firebase serverTime?
For android:
We can get serverTime by:

```<code>Timestamp.now().getSeconds();
</code>```

Then for iOS we can get serverTime by:

```<code>Timestamp.init().seconds
</code>```

My problem:
Timestamp.now().getSeconds(); is 13 characters long, Timestamp.init().seconds is only 10 characters long.

Is there a way to get the 13 characters serverTime on xCode?

答:
Those lines of code are not getting server time at all.  They're getting local time on the device, in the form of a Timestamp object, converted to seconds.  There's no API to get server time directly and accurately.

The number of seconds is a number.  It's not measured in "number of characters" like a string.  I suggest reading the API documentation for Timestamp to better understand the meaning of the methods you're calling, and choose the one that meets your specific needs.  You might have to do some conversions to get what you want, so be clear to understand what you're getting.

Title: How to get Firebase serverTime?

Body:
For android:
We can get serverTime by:

Timestamp.now().getSeconds();

Then for iOS we can get serverTime by:

Timestamp.init().seconds

My problem:
Timestamp.now().getSeconds(); is 13 characters long, Timestamp.init().seconds is only 10 characters long.

Is there a way to get the 13 characters serverTime on xCode?


问:
Is it possible to combine spring boot @Value with javax.validation.constraints?
I would like to validate values in application.properties.
I use @Value to inject and @NotBlank to validate the method parameter in a class annotated with @Configuration.

```<code>createSslContext(
            @Value("#{systemProperties['javax.net.ssl.trustStore']}")
            @NotBlank(message = "Truststore is needed")
            String path)
</code>```

I have included the hibernate-validator and the hibernate-validator-annotation-processor properties. Using Spring 2.2.0.RELEASE.

It doesn't work. The value is injected, but not validated. What am I missing?

答:
Add @Validated to your configuration class.

```<code>@Configuration
@Validated
public class MyConfig {

    @Bean
    MyClass createSslContext(
        @Value("#{systemProperties['javax.net.ssl.trustStore']}")
        @NotBlank(message = "Truststore is needed") final
        String path) {

        ...
    }

}
</code>```

Body:
I would like to validate values in application.properties.
I use @Value to inject and @NotBlank to validate the method parameter in a class annotated with @Configuration.

createSslContext(
            @Value("#{systemProperties['javax.net.ssl.trustStore']}")
            @NotBlank(message = "Truststore is needed")
            String path)

I have included the hibernate-validator and the hibernate-validator-annotation-processor properties. Using Spring 2.2.0.RELEASE.

It doesn't work. The value is injected, but not validated. What am I missing?

Body:
Add @Validated to your configuration class.

@Configuration
@Validated
public class MyConfig {

    @Bean
    MyClass createSslContext(
        @Value("#{systemProperties['javax.net.ssl.trustStore']}")
        @NotBlank(message = "Truststore is needed") final
        String path) {

        ...
    }

}


问:
How to get rid of \r \n and
 elements in a string
I've web scraped addresses and the address strings have unwanted elements like "\n" and "
", how do I remove them?

```<code>Rosemount Viaduct,<br />\r\nAberdeen<br />\r\n
</code>```

答:
You can clean these html leftovers with a regular expression:</p>

```<code>    import re

    value = "Rosemount Viaduct,<br />\r\nAberdeen<br />\r\n"
    clean_value = re.sub(r'\<br\s\/\>\r\n', r'', value)
</code>```

Title: How to get rid of \r \n and <br /> elements in a string

Body:
I've web scraped addresses and the address strings have unwanted elements like "\n" and "
", how do I remove them?

Rosemount Viaduct,
\r\nAberdeen
\r\n

Body:
You can clean these html leftovers with a regular expression:

    import re

    value = "Rosemount Viaduct,<br />\r\nAberdeen<br />\r\n"
    clean_value = re.sub(r'\<br\s\/\>\r\n', r'', value)


问:
Cypress Sum of two array

hi all, i want to sum of two columns values in a cypress .

i declared  two array variable : quantity and price , and push all columns elements as well.
 if i log the quantity cy.log(quantity) it shows all values in array. but cy.log(quantity[1]) is not working. same in price array.

i don't know why it's not behave like a array.

if i declare , a=[1,2,3,4,5,6] and then cy.log(a[1]) , it's working

i have to sum both of the arrays. tried many approaches.

```<code>var quantity =[]
var price =[]

cy.get('td:nth-child(10) > div > span:visible').each(($el, index, $list) =>
        {
            quantity.push(Number($el.text())).toFixed(4)

        })

        cy.get('td:nth-child(14) > div > span:visible').each(($el, index, $list) =>
        {
            price.push(Number($el.text())).toFixed(4)
        })

     cy.log(quantity) // working
     cy.log(price) // working

     cy.log(quantity[1]) //not working
     cy.log(price[3])  //not working

     // this part is working:
        var a=[1,2,3,4,5,6]
        cy.log(a[3])
</code>```

答:
You can set both the array values within the same then:

```<code>cy.get('tr').then(($trs) => {
    const price = [];
    const quantity = [];
    $trs.each((idx, $el) => {
        const value1 = Number(cy.$$($el).find(':nth-child(10)> div > span:visible').text());
        price.push(Number(value1.toFixed(4)));

        const value2 = Number(cy.$$($el).find(':nth-child(10)> div > span:visible').text());
        quantity.push(Number(value2.toFixed(4)));
    });

    const sum = price.map((p, index) => (p + quantity[index]).toFixed(2));
    cy.log('Price: ' + price);
    cy.log('Quantity: ' + quantity);
    cy.log('price[1]: ' + price[1]);
    cy.log('quantity[1]: ' + quantity[1]);
    cy.log('Sum = ' + sum);
});
</code>```

Screenshot from my test:

Corresponding Markup:

```<code><table>
  <tr>
    <td>5.42342</td>
    <td>2.442</td>
    <td>6.767678</td>
    <td>6767.678</td>
  </tr>
  <tr>
    <td>7.6343543</td>
    <td>8.44</td>
    <td>84.554</td>
    <td>24</td>
  </tr>
</table>
</code>```

Title: Cypress Sum of two array

Body:
hi all, i want to sum of two columns values in a cypress .

i declared  two array variable : quantity and price , and push all columns elements as well.
 if i log the quantity cy.log(quantity) it shows all values in array. but cy.log(quantity[1]) is not working. same in price array.

i don't know why it's not behave like a array.

if i declare , a=[1,2,3,4,5,6] and then cy.log(a[1]) , it's working

i have to sum both of the arrays. tried many approaches.

var quantity =[]
var price =[]

cy.get('td:nth-child(10) > div > span:visible').each(($el, index, $list) =>
        {
            quantity.push(Number($el.text())).toFixed(4)

        })

        cy.get('td:nth-child(14) > div > span:visible').each(($el, index, $list) =>
        {
            price.push(Number($el.text())).toFixed(4)
        })

     cy.log(quantity) // working
     cy.log(price) // working

     cy.log(quantity[1]) //not working
     cy.log(price[3])  //not working

     // this part is working:
        var a=[1,2,3,4,5,6]
        cy.log(a[3])

Body:
You can set both the array values within the same then:

cy.get('tr').then(($trs) => {
    const price = [];
    const quantity = [];
    $trs.each((idx, $el) => {
        const value1 = Number(cy.$$($el).find(':nth-child(10)> div > span:visible').text());
        price.push(Number(value1.toFixed(4)));

        const value2 = Number(cy.$$($el).find(':nth-child(10)> div > span:visible').text());
        quantity.push(Number(value2.toFixed(4)));
    });

    const sum = price.map((p, index) => (p + quantity[index]).toFixed(2));
    cy.log('Price: ' + price);
    cy.log('Quantity: ' + quantity);
    cy.log('price[1]: ' + price[1]);
    cy.log('quantity[1]: ' + quantity[1]);
    cy.log('Sum = ' + sum);
});

Screenshot from my test:

Corresponding Markup:

<table>
  <tr>
    <td>5.42342</td>
    <td>2.442</td>
    <td>6.767678</td>
    <td>6767.678</td>
  </tr>
  <tr>
    <td>7.6343543</td>
    <td>8.44</td>
    <td>84.554</td>
    <td>24</td>
  </tr>
</table>


问:
What is \363\353\377\377\377\177?

(gdb) p (char*)0x7fffffffe9c8
$16 = 0x7fffffffe9c8 "\363\353\377\377\377\177"
```

It doesn't look like ascii nor multibyte,what's that?

答: The part that you asked can be the shell code to that address.</p>

Title: What is \363\353\377\377\377\177?

Body:
(gdb) p (char*)0x7fffffffe9c8
$16 = 0x7fffffffe9c8 "\363\353\377\377\377\177"

It doesn't look like ascii nor multibyte,what's that?


问:
Html.DropdownListFor selected value not being set
How can I set the selected value of a Html.DropDownListFor? I've been having a look online and have seen that it can be achieved by using the fourth parameter so like the below:

```<code>@Html.DropDownListFor(m => m, new SelectList(Model, "Code", "Name", 0),  "Please select a country")
</code>```

My select list then display like this:

```<code><select id="ShipFromCountries" name="ShipFromCountries">
     <option value="">Please select a country</option>
     <option value="GB">United Kingdom</option>
     <option value="US">United States</option>
     ...
</select>
</code>```

But for some reason United Kingdom remains selected but I want "Please select a country" to be selected.

Anyone know how I can achieve this?

EDIT

I've updated my code as there was a slight change in functionality however still seem to be encountering this problem. This is what is in my view:

```<code>@Html.DropDownListFor(n => n.OrderTemplates, new SelectList(Model.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1), "Please select an order template")
</code>```

1 is the Id of the option that I want selected, I have also tried with the text of the option but that also does not work.

Any ideas?

答: This is CSS issues. I don't know why  @Html.DropDownListFor in Bootstrap 4 doest work. Surely this is class design problem. Anyways the work arround is, if your Dropdown input box has CSS Padding: #px, # px; element then disable it. Hope this will work. </p>

Body:
How can I set the selected value of a Html.DropDownListFor? I've been having a look online and have seen that it can be achieved by using the fourth parameter so like the below:

@Html.DropDownListFor(m => m, new SelectList(Model, "Code", "Name", 0),  "Please select a country")

My select list then display like this:

<select id="ShipFromCountries" name="ShipFromCountries">
     <option value="">Please select a country</option>
     <option value="GB">United Kingdom</option>
     <option value="US">United States</option>
     ...
</select>

But for some reason United Kingdom remains selected but I want "Please select a country" to be selected.

Anyone know how I can achieve this?

EDIT

I've updated my code as there was a slight change in functionality however still seem to be encountering this problem. This is what is in my view:

@Html.DropDownListFor(n => n.OrderTemplates, new SelectList(Model.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1), "Please select an order template")

1 is the Id of the option that I want selected, I have also tried with the text of the option but that also does not work.

Any ideas?


问:
The maximum number of apps for free development profiles has been reached
I can't get any apps to run on my iPhone. I have uninstalled the apps on the device and from the window -> Devices section. Does anyone know how else to fix this?

Details

```<code>enter code hereUnable to install "App Name"
Domain: com.apple.dt.MobileDeviceErrorDomain
Code: -402620383
--
The maximum number of apps for free development profiles has been reached.
Domain: com.apple.dt.MobileDeviceErrorDomain
Code: -402620383
User Info: {
    DVTRadarComponentKey = 487925;
    MobileDeviceErrorCode = "(0xE8008021)";
    "com.apple.dtdevicekit.stacktrace" = (
    0   DTDeviceKitBase                     0x00000001253b381a DTDKCreateNSErrorFromAMDErrorCode + 233
    1   DTDeviceKitBase                     0x00000001253f4f70 __90-[DTDKMobileDeviceToken installApplicationBundleAtPath:withOptions:andError:withCallback:]_block_invoke + 155
    2   DVTFoundation                       0x000000010c117155 DVTInvokeWithStrongOwnership + 73
    3   DTDeviceKitBase                     0x00000001253f4ca8 -[DTDKMobileDeviceToken installApplicationBundleAtPath:withOptions:andError:withCallback:] + 1654
    4   IDEiOSSupportCore                   0x000000012526be91 __118-[DVTiOSDevice(DVTiPhoneApplicationInstallation) processAppInstallSet:appUninstallSet:installOptions:completionBlock:]_block_invoke.352 + 4165
    5   DVTFoundation                       0x000000010c24a7f4 __DVT_CALLING_CLIENT_BLOCK__ + 7
    6   DVTFoundation                       0x000000010c24c436 __DVTDispatchAsync_block_invoke + 1194
    7   libdispatch.dylib                   0x00007fff6eea06c4 _dispatch_call_block_and_release + 12
    8   libdispatch.dylib                   0x00007fff6eea1658 _dispatch_client_callout + 8
    9   libdispatch.dylib                   0x00007fff6eea6c44 _dispatch_lane_serial_drain + 597
    10  libdispatch.dylib                   0x00007fff6eea75d6 _dispatch_lane_invoke + 363
    11  libdispatch.dylib                   0x00007fff6eeb0c09 _dispatch_workloop_worker_thread + 596
    12  libsystem_pthread.dylib             0x00007fff6f0fba3d _pthread_wqthread + 290
    13  libsystem_pthread.dylib             0x00007fff6f0fab77 start_wqthread + 15
);
}
--

System Information

macOS Version 10.15.5 (Build 19F96)
Xcode 11.5 (16139)
</code>```

答:
I'm still fairly new to Xcode (less than a month and Swift is my first language), but I ran into the same problem as you and I understand how frustrating it is. After doing some digging and tinkering around, I found that the new  iOS 13.5 and Xcode 11.5 Update kind of counted other apps as free developer apps.

I ran the app multiple times in an attempt to install and searched for the error on the console. You can click Window>Devices and Simulators>Open Console. Click on your phone and search [MIFreeProfileValidatedAppTracker]

Once you find it, it should list down apps that are installed. I deleted those apps one by one until it freed up some space to install the current app that I am building.

The console should open up something similar to this. I found that you can leave up to 4 installed applications. Good luck!

```<code>0x16d05f000 -[MIFreeProfileValidatedAppTracker _onQueue_addReferenceForApplicationIdentifier:bundle:error:]: 182: This device has reached the maximum number of installed apps using a free developer profile: {(
    "com.apple.Fitness",
    "Random",
    "com.apple.DocumentsApp",
    "Random"
)}
</code>```

Body:
I can't get any apps to run on my iPhone. I have uninstalled the apps on the device and from the window -> Devices section. Does anyone know how else to fix this?

Details

enter code hereUnable to install "App Name"
Domain: com.apple.dt.MobileDeviceErrorDomain
Code: -402620383
--
The maximum number of apps for free development profiles has been reached.
Domain: com.apple.dt.MobileDeviceErrorDomain
Code: -402620383
User Info: {
    DVTRadarComponentKey = 487925;
    MobileDeviceErrorCode = "(0xE8008021)";
    "com.apple.dtdevicekit.stacktrace" = (
    0   DTDeviceKitBase                     0x00000001253b381a DTDKCreateNSErrorFromAMDErrorCode + 233
    1   DTDeviceKitBase                     0x00000001253f4f70 __90-[DTDKMobileDeviceToken installApplicationBundleAtPath:withOptions:andError:withCallback:]_block_invoke + 155
    2   DVTFoundation                       0x000000010c117155 DVTInvokeWithStrongOwnership + 73
    3   DTDeviceKitBase                     0x00000001253f4ca8 -[DTDKMobileDeviceToken installApplicationBundleAtPath:withOptions:andError:withCallback:] + 1654
    4   IDEiOSSupportCore                   0x000000012526be91 __118-[DVTiOSDevice(DVTiPhoneApplicationInstallation) processAppInstallSet:appUninstallSet:installOptions:completionBlock:]_block_invoke.352 + 4165
    5   DVTFoundation                       0x000000010c24a7f4 __DVT_CALLING_CLIENT_BLOCK__ + 7
    6   DVTFoundation                       0x000000010c24c436 __DVTDispatchAsync_block_invoke + 1194
    7   libdispatch.dylib                   0x00007fff6eea06c4 _dispatch_call_block_and_release + 12
    8   libdispatch.dylib                   0x00007fff6eea1658 _dispatch_client_callout + 8
    9   libdispatch.dylib                   0x00007fff6eea6c44 _dispatch_lane_serial_drain + 597
    10  libdispatch.dylib                   0x00007fff6eea75d6 _dispatch_lane_invoke + 363
    11  libdispatch.dylib                   0x00007fff6eeb0c09 _dispatch_workloop_worker_thread + 596
    12  libsystem_pthread.dylib             0x00007fff6f0fba3d _pthread_wqthread + 290
    13  libsystem_pthread.dylib             0x00007fff6f0fab77 start_wqthread + 15
);
}
--

System Information

macOS Version 10.15.5 (Build 19F96)
Xcode 11.5 (16139)

Body:
I'm still fairly new to Xcode (less than a month and Swift is my first language), but I ran into the same problem as you and I understand how frustrating it is. After doing some digging and tinkering around, I found that the new  iOS 13.5 and Xcode 11.5 Update kind of counted other apps as free developer apps.

I ran the app multiple times in an attempt to install and searched for the error on the console. You can click Window>Devices and Simulators>Open Console. Click on your phone and search [MIFreeProfileValidatedAppTracker]

Once you find it, it should list down apps that are installed. I deleted those apps one by one until it freed up some space to install the current app that I am building.

The console should open up something similar to this. I found that you can leave up to 4 installed applications. Good luck!

0x16d05f000 -[MIFreeProfileValidatedAppTracker _onQueue_addReferenceForApplicationIdentifier:bundle:error:]: 182: This device has reached the maximum number of installed apps using a free developer profile: {(
    "com.apple.Fitness",
    "Random",
    "com.apple.DocumentsApp",
    "Random"
)}


问:
Can placeholder text color in a TextBox in Winforms be changed?
I want to change the color of the placeholder text in a textbox but cant seem to find a way to do it. Is it possible to change it ?</p>

答:
I don't think there is a Placeholder text property in WinForms (Someone correct me if I had missed this)

My way of doing this will be to add 2 event handlers, one for Enter event and another for Leave event

```<code>private void textbox1_Enter(object sender, EventArgs e)
{
  if(textbox1.Text == "my_placeholder_text")
  {
      textbox1.Text = "";
      textbox1.ForeColor = Color.Black;
  }
}

private void textbox1_Leave(object sender, EventArgs e)
{
  if(textbox1.Text == "")
  {
      textbox1.Text = "my_placeholder_text";
      textbox1.ForeColor = Color.LightBlue;  //or whatever color your want to set
  }
}
</code>```

Additionally, if you wish to use this for multiple textboxes, create your own textbox control inheriting from System.Windows.Forms.UI.TextBox class and add two properties to it PlaceholderText and PlaceholderColor

```<code>class myTextBox: System.Windows.Forms.UI.TextBox
{
  public string PlaceholderText {get; set;} = "";
  public Color PlaceholderColor {get; set;} = Color.Gray;

  protected void override OnEnter(EventArgs e)
  {
    if(this.Text == PlaceholderText)
    {
      this.Text = "";
      this.Color = this.ForeColor;
    }
  }

  protected void override OnLeave(EventArgs e)
  {
    if(this.Text == "")
    {
      this.Text = PlaceholderText;
      this.Color = this.PlaceholderColor;
    }
  }
}
</code>```

PS: All code typed here, so typos and some errors might occur.

Body:
I don't think there is a Placeholder text property in WinForms (Someone correct me if I had missed this)

My way of doing this will be to add 2 event handlers, one for Enter event and another for Leave event

private void textbox1_Enter(object sender, EventArgs e)
{
  if(textbox1.Text == "my_placeholder_text")
  {
      textbox1.Text = "";
      textbox1.ForeColor = Color.Black;
  }
}

private void textbox1_Leave(object sender, EventArgs e)
{
  if(textbox1.Text == "")
  {
      textbox1.Text = "my_placeholder_text";
      textbox1.ForeColor = Color.LightBlue;  //or whatever color your want to set
  }
}

Additionally, if you wish to use this for multiple textboxes, create your own textbox control inheriting from System.Windows.Forms.UI.TextBox class and add two properties to it PlaceholderText and PlaceholderColor

class myTextBox: System.Windows.Forms.UI.TextBox
{
  public string PlaceholderText {get; set;} = "";
  public Color PlaceholderColor {get; set;} = Color.Gray;

  protected void override OnEnter(EventArgs e)
  {
    if(this.Text == PlaceholderText)
    {
      this.Text = "";
      this.Color = this.ForeColor;
    }
  }

  protected void override OnLeave(EventArgs e)
  {
    if(this.Text == "")
    {
      this.Text = PlaceholderText;
      this.Color = this.PlaceholderColor;
    }
  }
}

PS: All code typed here, so typos and some errors might occur.


问:
Battleship game board in Java
I write the code of the warships game. There are two players, human and computer players. Both of them have separate boards. In the beginning, I automatically place the ships on both boards randomly, then I take the coordinates and put the ships on each other's boards.If the place in the coordinate hits the other player's ship, I will send a message saying this to the screen. The character "s" is shown on the screen if it sinks the ship, only with "*" if it hits and "x" if it cannot hit. How can I make changes to the computer player's board after receiving coordinates when it's time for the human player?</p>

```<code>public static int numRows = 10;
public static int numCols = 10;
public static int playerShips;
public static int computerShips;
public static String[][] grid = new String[numRows][numCols];
public static int[][] missedGuesses = new int[numRows][numCols];

public static void main(String[] args) {
    System.out.println("Welcome to Amiral Batti game");
    System.out.println("\nComputer: ");
    deployComputerShips();
    System.out.println("\n");
    System.out.println("\nHuman: ");
    deployPlayerShips();

    do {
        Battle();
    }
    while(players.playerShips != 0 && players.computerShips != 0);

    gameOver();
}
public static int FIELD_SIZE = 10;

public static void deployPlayerShips() {
    Random random = new Random();
    int[][] field = new int[FIELD_SIZE][FIELD_SIZE];
    for (int i = 5; i > 0; i--) {
        int x = random.nextInt(field.length);
        int y = random.nextInt(field.length);
        boolean vertical = random.nextBoolean();

        if (vertical) {
            if (y + i > FIELD_SIZE) {
                y -= i;
            }
        } else if (x + i > FIELD_SIZE) {
            x -= i;
        }
        boolean isFree = true;

        if (vertical) {
            for (int m = y; m < y + i; m++) {
                if (field[m][x] != 0) {
                    isFree = false;
                    break;
                }
            }
        } else {
            for (int n = x; n < x + i; n++) {
                if (field[y][n] != 0) {
                    isFree = false;
                    break;
                }
            }
        }
        if (!isFree) {
            i++;
            continue;
        }

        if (vertical) {
            for (int m = Math.max(0, x - 1); m < Math.min(FIELD_SIZE, x + 2); m++) {
                for (int n = Math.max(0, y - 1); n < Math.min(FIELD_SIZE, y + i + 1); n++) {
                    field[n][m] = 9;
                }
            }
        } else {
            for (int m = Math.max(0, y - 1); m < Math.min(FIELD_SIZE, y + 2); m++) {
                for (int n = Math.max(0, x - 1); n < Math.min(FIELD_SIZE, x + i + 1); n++) {
                    field[m][n] = 9;
                }
            }
        }

        for (int j = 0; j < i; j++) {
            field[y][x] = i;
            if (vertical) {
                y++;
            } else {
                x++;
            }
        }
    }

    System.out.print(" ");
    System.out.println("0 1 2 3 4 5 6 7 8 9");
    char[][] map = new char[FIELD_SIZE][FIELD_SIZE];
    for (int i = 0; i < FIELD_SIZE; i++) {
        for (int j = 0; j < FIELD_SIZE; j++) {
            map[i][j] = field[i][j] == 0 || field[i][j] == 9 ? '.' : 'o';
        }
    }

    Arrays.stream(map)
            .forEach(m -> System.out.println(Arrays.toString(m).replace(",", "")));
}
public static void deployComputerShips() {
    Random random = new Random();
    int[][] field = new int[FIELD_SIZE][FIELD_SIZE];
    for (int i = 5; i > 0; i--) {

        int x = random.nextInt(field.length);
        int y = random.nextInt(field.length);
        boolean vertical = random.nextBoolean();

        if (vertical) {
            if (y + i > FIELD_SIZE) {
                y -= i;
            }
        } else if (x + i > FIELD_SIZE) {
            x -= i;
        }

        boolean isFree = true;

        if (vertical) {
            for (int m = y; m < y + i; m++) {
                if (field[m][x] != 0) {
                    isFree = false;
                    break;
                }
            }
        } else {
            for (int n = x; n < x + i; n++) {
                if (field[y][n] != 0) {
                    isFree = false;
                    break;
                }
            }
        }
        if (!isFree) {
            i++;
            continue;
        }

        if (vertical) {
            for (int m = Math.max(0, x - 1); m < Math.min(FIELD_SIZE, x + 2); m++) {
                for (int n = Math.max(0, y - 1); n < Math.min(FIELD_SIZE, y + i + 1); n++) {
                    field[n][m] = 9;
                }
            }
        } else {
            for (int m = Math.max(0, y - 1); m < Math.min(FIELD_SIZE, y + 2); m++) {
                for (int n = Math.max(0, x - 1); n < Math.min(FIELD_SIZE, x + i + 1); n++) {
                    field[m][n] = 9;
                }
            }
        }

        for (int j = 0; j < i; j++) {
            field[y][x] = i;
            if (vertical) {
                y++;
            } else {
                x++;
            }
        }
    }

    System.out.print(" ");
    System.out.println("0 1 2 3 4 5 6 7 8 9");
    char[][] map = new char[FIELD_SIZE][FIELD_SIZE];
    for (int i = 0; i < FIELD_SIZE; i++) {
        for (int j = 0; j < FIELD_SIZE; j++) {
            map[i][j] = field[i][j] == 0 || field[i][j] == 9 ? '.' : 'o';
        }
    }

    Arrays.stream(map)
            .forEach(m -> System.out.println(Arrays.toString(m).replace(",", "")));
}

public static void Battle(){
    playerTurn();
    computerTurn();

    printBoard();

    System.out.println();
    System.out.println("Your ships: " + players.playerShips + " | Computer ships: " + players.computerShips);
    System.out.println();
}

public static void playerTurn(){
    Scanner scn = new Scanner(System.in);
    System.out.println("\nHuman's turn: ");
    int x = -1, y = -1;
    do {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter row number: ");
        x = scn.nextInt();
        System.out.print("Enter column number: ");
        y = scn.nextInt();

        if ((x >= 0 && x < numRows) && (y >= 0 && y < numCols)){
            if (grid[x][y].equals("o")){
                System.out.println("You sunk the ship!");
                grid[x][y] = "s";
                --players.computerShips;
            }
            else if (grid[x][y].equals(".")) {
                System.out.println("You missed");
                grid[x][y] = "x";
            }
        }
        else if ((x < 0 || x >= numRows) || (y < 0 || y >= numCols))
            System.out.println("You can't place ships outside the " + numRows + " by " + numCols + " grid");
    }
    while((x < 0 || x >= numRows) || (y < 0 || y >= numCols));
}
public static void computerTurn(){
    System.out.println("\nComputer's turn: ");

    int x = -1, y = -1;
    do {
        x = (int)(Math.random()*10);
        y = (int)(Math.random()*10);
        System.out.println("Enter row number: "+x);
        System.out.println("Enter column number: "+y);

        if ((x >= 0 && x < numRows) && (y >= 0 && y < numCols)){
            if (grid[x][y].equals("o")){
                System.out.println("The Computer sunk one of your ships!");
                grid[x][y] = "s";
                --players.playerShips;
                ++players.computerShips;
            }
            else if (grid[x][y].equals(".")) {
                System.out.println("Computer missed");
                grid[x][y] = "x";
                if(missedGuesses[x][y] != 1)
                    missedGuesses[x][y] = 1;
            }
        }
    }
    while((x < 0 || x >= numRows) || (y < 0 || y >= numCols));
}

public static void gameOver(){
    System.out.println("Your ships: " + players.playerShips + " | Computer ships: " + players.computerShips);
    if(players.playerShips > 0 && players.computerShips <= 0)
        System.out.println("You won the battle! ");
    else
        System.out.println("You lost the battle! ");
    System.out.println();
}

public static void printBoard(){

    System.out.print(" ");
    System.out.println("0123456789");

    for(int x = 0; x < grid.length; x++) {
        System.out.print(x);

        for (int y = 0; y < grid[x].length; y++){
            System.out.print(grid[x][y]);
        }
        System.out.println();
    }
    System.out.println();
}
</code>```

答:
Okay here is a more correct version. I could do more but ... then half of the code would be rewritten and I don't see the point of doing that (doesn't help you). So I insist that its far from perfect but at least it resolves your issue. I made the following corrections:

The battle() method has a corrected game logic

I removed the 'grid' variable. I don't understand why it exists. And instead externalized the 'field' variable -> one for each player.

I merged your two deployPlayerShips() deployComputerShips() methods into one: deployPlayersShips(...). But I still don't understand most of its logic. And with the given code below there are issues at display and field init. But these errors certainly are already present in your original code.

I have rewritten printBoard() to make use of 'field' variables. But it will still need fixes.

I fixed partially the playerTurn() and computerTurn() methods as they had badly constructed loops. Turns could never really "turn". The biggest (blocking) problem was in these methods I think (even though other errors remain).

I've added a global Random() and made Scanner instantiated only once.

package sandbox;

```<code>import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

// ATTENTION: low-quality code based on original source posted in question. Not fully functional and has many issues. But it answers the original question.
public class Warships {

    private static final int numRows = 10;
    private static final int numCols = 10;
    private static final int NB_SHIPS = 5;

    private static int playerShips = NB_SHIPS;
    private static int computerShips = NB_SHIPS;
    private static final int[][] missedGuesses = new int[numRows][numCols];

    private static final Random random = new Random(System.currentTimeMillis());

    public static final int FIELD_SIZE = 10;
    private static final int[][] playerField = new int[FIELD_SIZE][FIELD_SIZE];
    private static final int[][] computerField = new int[FIELD_SIZE][FIELD_SIZE];

    public static void main(String[] args) {
        System.out.println("Welcome to Amiral Batti game");

        System.out.println("\nComputer: ");
        deployPlayersShips(computerField);
        System.out.println("\n");
        System.out.println("\nHuman: ");
        deployPlayersShips(playerField);

        Scanner scn = new Scanner(System.in);

        do {
            battle(scn);
        } while (playerShips != 0 && computerShips != 0);

        gameOver();
    }

    public static void deployPlayersShips(int[][] field) {
        for (int i = NB_SHIPS; i > 0; i--) {
            int x = random.nextInt(field.length);
            int y = random.nextInt(field.length);
            boolean vertical = random.nextBoolean();

            (...)
        }
        printBoard2(field);
    }

    public static void battle(Scanner scn) {
            playerTurn(scn);
            computerTurn();

            System.out.println("\nComputer: ");
            printBoard2(computerField);
            System.out.println("\nHuman: ");
            printBoard2(playerField);

            System.out.println();
            System.out.println("Your ships: " + playerShips + " | Computer ships: " + computerShips);
            System.out.println();
    }

    public static void playerTurn(Scanner scn) {
        System.out.println("\nHuman's turn: ");
        int x = -1, y = -1;

        // MAIN ISSUE WAS HERE -- Add correct loop on invalid input
        do {
            System.out.print("Enter row number: ");
            x = scn.nextInt();
            System.out.print("Enter column number: ");
            y = scn.nextInt();
        } while ((x < 0 || x >= numRows) || (y < 0 || y >= numCols));

        // MAIN ISSUE WAS HERE -- Removed invalid loop on update field
        if (computerField[x][y] != 0 && computerField[x][y] != 9) {
            System.out.println("You sunk the ship!");
            computerField[x][y] = 1;//"s";
            computerShips--;
        } else if (".".equals(computerField[x][y])) {
            System.out.println("You missed");
            computerField[x][y] = 2; //"x";
        }
    }

    public static void computerTurn() {
        System.out.println("\nComputer's turn: ");

        int x = random.nextInt(FIELD_SIZE);
        int y = random.nextInt(FIELD_SIZE);
        System.out.println("Enter row number: " + x);
        System.out.println("Enter column number: " + y);

        // MAIN ISSUE WAS HERE -- Removed invalid loop on input/rand
        if ((x >= 0 && x < numRows) && (y >= 0 && y < numCols)) {
            if (playerField[x][y] != 0 && playerField[x][y] != 9) {
                System.out.println("The Computer sunk one of your ships!");
                playerField[x][y] = 1;//"s";
                playerShips--;
            } else if (".".equals(playerField[x][y])) {
                System.out.println("Computer missed");
                playerField[x][y] = 2; //"x";
                if (missedGuesses[x][y] != 1) {
                    missedGuesses[x][y] = 1;
                }
            }
        }
    }

    public static void gameOver() {
        System.out.println("Your ships: " + playerShips + " | Computer ships: " + computerShips);
        if (playerShips > 0 && computerShips <= 0) {
            System.out.println("You won the battle! ");
        } else {
            System.out.println("You lost the battle! ");
        }
        System.out.println();
    }

    public static void printBoard2(int[][] field) {
        System.out.print(" ");
        System.out.println("0 1 2 3 4 5 6 7 8 9");
        char[][] map = new char[FIELD_SIZE][FIELD_SIZE];
        for (int i = 0; i < FIELD_SIZE; i++) {
            for (int j = 0; j < FIELD_SIZE; j++) {
                switch(field[i][j]) {
                    case 0:
                    case 9: map[i][j] = '.';
                        break;
                    case 1: map[i][j] = 's';
                        break;
                    case 2: map[i][j] = 'x';
                        break;
                    default: map[i][j] = 'o';
                        break;
                }
            }
        }

        Arrays.stream(map)
                .forEach(m -> System.out.println(Arrays.toString(m).replace(",", "")));
    }
}
</code>```

At this point  I let you do the rest. Many errors remain. Take the time to truly finish and double-check your code before requesting help again. And keep training there is room for improvements out there in terms of OOP, coding rules and best practices. Good luck.

Title: Battleship game board in Java

Body:
I write the code of the warships game. There are two players, human and computer players. Both of them have separate boards. In the beginning, I automatically place the ships on both boards randomly, then I take the coordinates and put the ships on each other's boards.If the place in the coordinate hits the other player's ship, I will send a message saying this to the screen. The character "s" is shown on the screen if it sinks the ship, only with "*" if it hits and "x" if it cannot hit. How can I make changes to the computer player's board after receiving coordinates when it's time for the human player?

public static int numRows = 10;
public static int numCols = 10;
public static int playerShips;
public static int computerShips;
public static String[][] grid = new String[numRows][numCols];
public static int[][] missedGuesses = new int[numRows][numCols];

public static void main(String[] args) {
    System.out.println("Welcome to Amiral Batti game");
    System.out.println("\nComputer: ");
    deployComputerShips();
    System.out.println("\n");
    System.out.println("\nHuman: ");
    deployPlayerShips();

    do {
        Battle();
    }
    while(players.playerShips != 0 && players.computerShips != 0);

    gameOver();
}
public static int FIELD_SIZE = 10;

public static void deployPlayerShips() {
    Random random = new Random();
    int[][] field = new int[FIELD_SIZE][FIELD_SIZE];
    for (int i = 5; i > 0; i--) {
        int x = random.nextInt(field.length);
        int y = random.nextInt(field.length);
        boolean vertical = random.nextBoolean();

        if (vertical) {
            if (y + i > FIELD_SIZE) {
                y -= i;
            }
        } else if (x + i > FIELD_SIZE) {
            x -= i;
        }
        boolean isFree = true;

        if (vertical) {
            for (int m = y; m < y + i; m++) {
                if (field[m][x] != 0) {
                    isFree = false;
                    break;
                }
            }
        } else {
            for (int n = x; n < x + i; n++) {
                if (field[y][n] != 0) {
                    isFree = false;
                    break;
                }
            }
        }
        if (!isFree) {
            i++;
            continue;
        }

        if (vertical) {
            for (int m = Math.max(0, x - 1); m < Math.min(FIELD_SIZE, x + 2); m++) {
                for (int n = Math.max(0, y - 1); n < Math.min(FIELD_SIZE, y + i + 1); n++) {
                    field[n][m] = 9;
                }
            }
        } else {
            for (int m = Math.max(0, y - 1); m < Math.min(FIELD_SIZE, y + 2); m++) {
                for (int n = Math.max(0, x - 1); n < Math.min(FIELD_SIZE, x + i + 1); n++) {
                    field[m][n] = 9;
                }
            }
        }

        for (int j = 0; j < i; j++) {
            field[y][x] = i;
            if (vertical) {
                y++;
            } else {
                x++;
            }
        }
    }

    System.out.print(" ");
    System.out.println("0 1 2 3 4 5 6 7 8 9");
    char[][] map = new char[FIELD_SIZE][FIELD_SIZE];
    for (int i = 0; i < FIELD_SIZE; i++) {
        for (int j = 0; j < FIELD_SIZE; j++) {
            map[i][j] = field[i][j] == 0 || field[i][j] == 9 ? '.' : 'o';
        }
    }

    Arrays.stream(map)
            .forEach(m -> System.out.println(Arrays.toString(m).replace(",", "")));
}
public static void deployComputerShips() {
    Random random = new Random();
    int[][] field = new int[FIELD_SIZE][FIELD_SIZE];
    for (int i = 5; i > 0; i--) {

        int x = random.nextInt(field.length);
        int y = random.nextInt(field.length);
        boolean vertical = random.nextBoolean();

        if (vertical) {
            if (y + i > FIELD_SIZE) {
                y -= i;
            }
        } else if (x + i > FIELD_SIZE) {
            x -= i;
        }

        boolean isFree = true;

        if (vertical) {
            for (int m = y; m < y + i; m++) {
                if (field[m][x] != 0) {
                    isFree = false;
                    break;
                }
            }
        } else {
            for (int n = x; n < x + i; n++) {
                if (field[y][n] != 0) {
                    isFree = false;
                    break;
                }
            }
        }
        if (!isFree) {
            i++;
            continue;
        }

        if (vertical) {
            for (int m = Math.max(0, x - 1); m < Math.min(FIELD_SIZE, x + 2); m++) {
                for (int n = Math.max(0, y - 1); n < Math.min(FIELD_SIZE, y + i + 1); n++) {
                    field[n][m] = 9;
                }
            }
        } else {
            for (int m = Math.max(0, y - 1); m < Math.min(FIELD_SIZE, y + 2); m++) {
                for (int n = Math.max(0, x - 1); n < Math.min(FIELD_SIZE, x + i + 1); n++) {
                    field[m][n] = 9;
                }
            }
        }

        for (int j = 0; j < i; j++) {
            field[y][x] = i;
            if (vertical) {
                y++;
            } else {
                x++;
            }
        }
    }

    System.out.print(" ");
    System.out.println("0 1 2 3 4 5 6 7 8 9");
    char[][] map = new char[FIELD_SIZE][FIELD_SIZE];
    for (int i = 0; i < FIELD_SIZE; i++) {
        for (int j = 0; j < FIELD_SIZE; j++) {
            map[i][j] = field[i][j] == 0 || field[i][j] == 9 ? '.' : 'o';
        }
    }

    Arrays.stream(map)
            .forEach(m -> System.out.println(Arrays.toString(m).replace(",", "")));
}

public static void Battle(){
    playerTurn();
    computerTurn();

    printBoard();

    System.out.println();
    System.out.println("Your ships: " + players.playerShips + " | Computer ships: " + players.computerShips);
    System.out.println();
}

public static void playerTurn(){
    Scanner scn = new Scanner(System.in);
    System.out.println("\nHuman's turn: ");
    int x = -1, y = -1;
    do {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter row number: ");
        x = scn.nextInt();
        System.out.print("Enter column number: ");
        y = scn.nextInt();

        if ((x >= 0 && x < numRows) && (y >= 0 && y < numCols)){
            if (grid[x][y].equals("o")){
                System.out.println("You sunk the ship!");
                grid[x][y] = "s";
                --players.computerShips;
            }
            else if (grid[x][y].equals(".")) {
                System.out.println("You missed");
                grid[x][y] = "x";
            }
        }
        else if ((x < 0 || x >= numRows) || (y < 0 || y >= numCols))
            System.out.println("You can't place ships outside the " + numRows + " by " + numCols + " grid");
    }
    while((x < 0 || x >= numRows) || (y < 0 || y >= numCols));
}
public static void computerTurn(){
    System.out.println("\nComputer's turn: ");

    int x = -1, y = -1;
    do {
        x = (int)(Math.random()*10);
        y = (int)(Math.random()*10);
        System.out.println("Enter row number: "+x);
        System.out.println("Enter column number: "+y);

        if ((x >= 0 && x < numRows) && (y >= 0 && y < numCols)){
            if (grid[x][y].equals("o")){
                System.out.println("The Computer sunk one of your ships!");
                grid[x][y] = "s";
                --players.playerShips;
                ++players.computerShips;
            }
            else if (grid[x][y].equals(".")) {
                System.out.println("Computer missed");
                grid[x][y] = "x";
                if(missedGuesses[x][y] != 1)
                    missedGuesses[x][y] = 1;
            }
        }
    }
    while((x < 0 || x >= numRows) || (y < 0 || y >= numCols));
}

public static void gameOver(){
    System.out.println("Your ships: " + players.playerShips + " | Computer ships: " + players.computerShips);
    if(players.playerShips > 0 && players.computerShips <= 0)
        System.out.println("You won the battle! ");
    else
        System.out.println("You lost the battle! ");
    System.out.println();
}

public static void printBoard(){

    System.out.print(" ");
    System.out.println("0123456789");

    for(int x = 0; x < grid.length; x++) {
        System.out.print(x);

        for (int y = 0; y < grid[x].length; y++){
            System.out.print(grid[x][y]);
        }
        System.out.println();
    }
    System.out.println();
}

Body:
Okay here is a more correct version. I could do more but ... then half of the code would be rewritten and I don't see the point of doing that (doesn't help you). So I insist that its far from perfect but at least it resolves your issue. I made the following corrections:

The battle() method has a corrected game logic

I removed the 'grid' variable. I don't understand why it exists. And instead externalized the 'field' variable -> one for each player.

I merged your two deployPlayerShips() deployComputerShips() methods into one: deployPlayersShips(...). But I still don't understand most of its logic. And with the given code below there are issues at display and field init. But these errors certainly are already present in your original code.

I have rewritten printBoard() to make use of 'field' variables. But it will still need fixes.

I fixed partially the playerTurn() and computerTurn() methods as they had badly constructed loops. Turns could never really "turn". The biggest (blocking) problem was in these methods I think (even though other errors remain).

I've added a global Random() and made Scanner instantiated only once.

package sandbox;

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

// ATTENTION: low-quality code based on original source posted in question. Not fully functional and has many issues. But it answers the original question.
public class Warships {

    private static final int numRows = 10;
    private static final int numCols = 10;
    private static final int NB_SHIPS = 5;

    private static int playerShips = NB_SHIPS;
    private static int computerShips = NB_SHIPS;
    private static final int[][] missedGuesses = new int[numRows][numCols];

    private static final Random random = new Random(System.currentTimeMillis());

    public static final int FIELD_SIZE = 10;
    private static final int[][] playerField = new int[FIELD_SIZE][FIELD_SIZE];
    private static final int[][] computerField = new int[FIELD_SIZE][FIELD_SIZE];

    public static void main(String[] args) {
        System.out.println("Welcome to Amiral Batti game");

        System.out.println("\nComputer: ");
        deployPlayersShips(computerField);
        System.out.println("\n");
        System.out.println("\nHuman: ");
        deployPlayersShips(playerField);

        Scanner scn = new Scanner(System.in);

        do {
            battle(scn);
        } while (playerShips != 0 && computerShips != 0);

        gameOver();
    }

    public static void deployPlayersShips(int[][] field) {
        for (int i = NB_SHIPS; i > 0; i--) {
            int x = random.nextInt(field.length);
            int y = random.nextInt(field.length);
            boolean vertical = random.nextBoolean();

            (...)
        }
        printBoard2(field);
    }

    public static void battle(Scanner scn) {
            playerTurn(scn);
            computerTurn();

            System.out.println("\nComputer: ");
            printBoard2(computerField);
            System.out.println("\nHuman: ");
            printBoard2(playerField);

            System.out.println();
            System.out.println("Your ships: " + playerShips + " | Computer ships: " + computerShips);
            System.out.println();
    }

    public static void playerTurn(Scanner scn) {
        System.out.println("\nHuman's turn: ");
        int x = -1, y = -1;

        // MAIN ISSUE WAS HERE -- Add correct loop on invalid input
        do {
            System.out.print("Enter row number: ");
            x = scn.nextInt();
            System.out.print("Enter column number: ");
            y = scn.nextInt();
        } while ((x < 0 || x >= numRows) || (y < 0 || y >= numCols));

        // MAIN ISSUE WAS HERE -- Removed invalid loop on update field
        if (computerField[x][y] != 0 && computerField[x][y] != 9) {
            System.out.println("You sunk the ship!");
            computerField[x][y] = 1;//"s";
            computerShips--;
        } else if (".".equals(computerField[x][y])) {
            System.out.println("You missed");
            computerField[x][y] = 2; //"x";
        }
    }

    public static void computerTurn() {
        System.out.println("\nComputer's turn: ");

        int x = random.nextInt(FIELD_SIZE);
        int y = random.nextInt(FIELD_SIZE);
        System.out.println("Enter row number: " + x);
        System.out.println("Enter column number: " + y);

        // MAIN ISSUE WAS HERE -- Removed invalid loop on input/rand
        if ((x >= 0 && x < numRows) && (y >= 0 && y < numCols)) {
            if (playerField[x][y] != 0 && playerField[x][y] != 9) {
                System.out.println("The Computer sunk one of your ships!");
                playerField[x][y] = 1;//"s";
                playerShips--;
            } else if (".".equals(playerField[x][y])) {
                System.out.println("Computer missed");
                playerField[x][y] = 2; //"x";
                if (missedGuesses[x][y] != 1) {
                    missedGuesses[x][y] = 1;
                }
            }
        }
    }

    public static void gameOver() {
        System.out.println("Your ships: " + playerShips + " | Computer ships: " + computerShips);
        if (playerShips > 0 && computerShips <= 0) {
            System.out.println("You won the battle! ");
        } else {
            System.out.println("You lost the battle! ");
        }
        System.out.println();
    }

    public static void printBoard2(int[][] field) {
        System.out.print(" ");
        System.out.println("0 1 2 3 4 5 6 7 8 9");
        char[][] map = new char[FIELD_SIZE][FIELD_SIZE];
        for (int i = 0; i < FIELD_SIZE; i++) {
            for (int j = 0; j < FIELD_SIZE; j++) {
                switch(field[i][j]) {
                    case 0:
                    case 9: map[i][j] = '.';
                        break;
                    case 1: map[i][j] = 's';
                        break;
                    case 2: map[i][j] = 'x';
                        break;
                    default: map[i][j] = 'o';
                        break;
                }
            }
        }

        Arrays.stream(map)
                .forEach(m -> System.out.println(Arrays.toString(m).replace(",", "")));
    }
}

At this point  I let you do the rest. Many errors remain. Take the time to truly finish and double-check your code before requesting help again. And keep training there is room for improvements out there in terms of OOP, coding rules and best practices. Good luck.


问:
how to update the base of a sub-branch
In our repository, we want to develop a feature and keep it in its branch(branchX) until finished. Multiple people are working on this one branch and have sub-branches of it. PRs from the sub-branches will get merged into branchX. Now, a feature from sub-branchA is finished and got merged, how can now all other sub-branches pull-in that change?

On branchB (that started before the feature from branchA got merged into branchX) I have tried git rebase branchX but it doesn't seem like it changes anything or pulls in any data. How can I get branchB updated with the commits from branchA that now got merged into branch X?

tree:

```<code>                      - branchA -
          - branchX -/           \- branchA (branchA got merged into branchX)
master - /           \
                      - branchB (how do I pull the changes that branchA introduced into branchB)?
</code>```

答: Probably the most true way is to execute git pull --rebase origin branchX, because for common case you should not know, what other subBranch was merged into branchX, you will just get all actual changes.

Title: how to update the base of a sub-branch

Body:
In our repository, we want to develop a feature and keep it in its branch(branchX) until finished. Multiple people are working on this one branch and have sub-branches of it. PRs from the sub-branches will get merged into branchX. Now, a feature from sub-branchA is finished and got merged, how can now all other sub-branches pull-in that change?

On branchB (that started before the feature from branchA got merged into branchX) I have tried git rebase branchX but it doesn't seem like it changes anything or pulls in any data. How can I get branchB updated with the commits from branchA that now got merged into branch X?

tree:

                      - branchA -
          - branchX -/           \- branchA (branchA got merged into branchX)
master - /           \
                      - branchB (how do I pull the changes that branchA introduced into branchB)?