问:
Username hidden html + php
I have problem with html and php,so I created login page and all functions for login,but I want to put username in header (Like a facebook) and have problem.Username is hidden when I add php code.
Everything work perfect,here is my HTML code.
pocetna.html

```<code><?php
session_start();
?>
<html>
<head>
    <title>
        weekta RolePlay | Pocetna
    </title>
    <link rel="stylesheet" href="style/styless.css">
    <link href="https://fonts.googleapis.com/css2?family=Jost&display=swap" rel="stylesheet">
</head>
<body>
<header>
            <a class="logo" href="/" style="text-decoration: none;color: #1260a8;font-size: 30px;font-family: 'Jost', sans-serif;"><p>weekta</p></a>
            <nav>
                <ul class="nav__links">
                    <li><a href="#">Services</a></li>
                    <li><a href="#">Projects</a></li>
                    <li><a href="#">About</a></li>
                    <li><a href="#"><span><?php echo( $_SESSION['korisnickoime'] );?></span></a></li>
                </ul>
            </nav>
            <a class="cta" href="index.html">Login</a>

            <p class="menu cta">Menu</p>
        </header>
        <div id="mobile__menu" class="overlay">
            <a class="close">×</a>
            <div class="overlay__content">
                <a href="#">Services</a>
                <a href="#">Projects</a>
                <a href="#">About</a>
            </div>
        </div>
        <script type="text/javascript" src="mobile.js"></script>
</body>
</html>
</code>```

And here is login_process.php

```<code><?php

$mysql_host="localhost";
$mysql_user="root";
$mysql_password="";
$mysql_db="weekta";

$conn = mysqli_connect($mysql_host,$mysql_user,$mysql_password);
mysqli_select_db($conn, 'weekta');
session_start();
if(isset($_POST['korisnickoime'])){

    $username=$_POST['korisnickoime'];
    $password=$_POST['sifrajedan'];

    $sql="SELECT * FROM loginform where korisnickoime='".$username."'AND sifrajedan='".$password."' limit 1";

    $result = mysqli_query($conn,$sql);

    if(mysqli_num_rows($result)==1){
        header("Location:pocetna.html");
        echo " Dobodosao $username";
        exit();
    }
    else{
        echo " Pogresna lozinka.";
        exit();
    }
}
?>
</code>```

Can someone help me?Thanks.

答:
In your script there is one mistake

```<code>$sql="SELECT * FROM loginform where korisnickoime='".$username."'AND sifrajedan='".$password."' limit 1";
</code>```

in this query near username where korisnickoime='".$username."'AND sifrajedan='".$password."' there is not space between  $username and AND.

The end result of this query after appending username and password will be like

```<code>SELECT * FROM loginform where korisnickoime='user1'AND sifrajedan='xyz' limit 1";
</code>```

This Query will break so please add a little space between, replace your Query string with this.

```<code> $sql="SELECT * FROM loginform where korisnickoime='".$username."' AND sifrajedan='".$password."' limit 1";
</code>```

Your PHP script could be like this

index.php

```<code><form method="post" name="login">
        <label for="username">Username:</label><br>
        <input type="text" name="username"><br>
        <label for="password">Password:</label><br>
        <input type="password" name="password"><br>
        <button type="submit" name="login">Log in</button>
</form>
<?php
    session_start();
    if(isset($_POST['username']) and isset($_POST['password']))
    {
        $username = $_POST['username'];
        $pass = $_POST['password'];
        $query = "SELECT * FROM `person` WHERE name='$username' and pass='$pass'";
        $result = mysql_query($query) or die(mysql_error());
        $count = mysql_num_rows($result);
        if ($count == 1){
            $_SESSION['username'] = $username;
            header('Location: homepage.php');
        }
        else
        {
            $msg = "Wrong credentials";
        }
    }

    if(isset($msg) & !empty($msg)){
        echo $msg;
    }
 ?>
</code>```

Then in homepage.php

```<code><nav>
<ul class="nav__links">
    <li><a href="#">Services</a></li>
    <li><a href="#">Projects</a></li>
    <li><a href="#">About</a></li>
    <li><a href="#">
    <span>
    <?php
            session_start();
            if(!isset($_SESSION['username']))
            {
                die("You are not logged in!");
            }
            $username = $_SESSION['username'];
            echo "Hai " . $username;
        ?>
    </span></a></li>
</ul>
</nav>
</code>```

PS: TO make your Query Secure use parameterized query like this

```<code><?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$stmt = $conn->prepare(SELECT * FROM loginform where korisnickoime='?' AND sifrajedan='?' limit 1");
$stmt->bind_param("ss", $username, $password);

// set parameters and execute
$username = "John";
$password = "Doe";
$result = $stmt->execute();

?>
</code>```

Title: Username hidden html + php

Body:
I have problem with html and php,so I created login page and all functions for login,but I want to put username in header (Like a facebook) and have problem.Username is hidden when I add php code.
Everything work perfect,here is my HTML code.
pocetna.html

<?php
session_start();
?>

    <title>
        weekta RolePlay | Pocetna
    </title>
    <link rel="stylesheet" href="style/styless.css">
    <link href="https://fonts.googleapis.com/css2?family=Jost&display=swap" rel="stylesheet">

weekta

Services

Projects

About

<?php echo( $_SESSION['korisnickoime'] );?>

            Login

Menu

            ×

                Services
                Projects
                About

And here is login_process.php

<?php

$mysql_host="localhost";
$mysql_user="root";
$mysql_password="";
$mysql_db="weekta";

$conn = mysqli_connect($mysql_host,$mysql_user,$mysql_password);
mysqli_select_db($conn, 'weekta');
session_start();
if(isset($_POST['korisnickoime'])){

    $username=$_POST['korisnickoime'];
    $password=$_POST['sifrajedan'];

    $sql="SELECT * FROM loginform where korisnickoime='".$username."'AND sifrajedan='".$password."' limit 1";

    $result = mysqli_query($conn,$sql);

    if(mysqli_num_rows($result)==1){
        header("Location:pocetna.html");
        echo " Dobodosao $username";
        exit();
    }
    else{
        echo " Pogresna lozinka.";
        exit();
    }
}
?>

Can someone help me?Thanks.

Body:
In your script there is one mistake

$sql="SELECT * FROM loginform where korisnickoime='".$username."'AND sifrajedan='".$password."' limit 1";

in this query near username where korisnickoime='".$username."'AND sifrajedan='".$password."' there is not space between  $username and AND.

The end result of this query after appending username and password will be like

SELECT * FROM loginform where korisnickoime='user1'AND sifrajedan='xyz' limit 1";

This Query will break so please add a little space between, replace your Query string with this.

 $sql="SELECT * FROM loginform where korisnickoime='".$username."' AND sifrajedan='".$password."' limit 1";

Your PHP script could be like this

index.php

<form method="post" name="login">
        <label for="username">Username:</label><br>
        <input type="text" name="username"><br>
        <label for="password">Password:</label><br>
        <input type="password" name="password"><br>
        <button type="submit" name="login">Log in</button>
</form>
<?php
    session_start();
    if(isset($_POST['username']) and isset($_POST['password']))
    {
        $username = $_POST['username'];
        $pass = $_POST['password'];
        $query = "SELECT * FROM `person` WHERE name='$username' and pass='$pass'";
        $result = mysql_query($query) or die(mysql_error());
        $count = mysql_num_rows($result);
        if ($count == 1){
            $_SESSION['username'] = $username;
            header('Location: homepage.php');
        }
        else
        {
            $msg = "Wrong credentials";
        }
    }

    if(isset($msg) & !empty($msg)){
        echo $msg;
    }
 ?>

Then in homepage.php

<nav>
<ul class="nav__links">
    <li><a href="#">Services</a></li>
    <li><a href="#">Projects</a></li>
    <li><a href="#">About</a></li>
    <li><a href="#">
    <span>
    <?php
            session_start();
            if(!isset($_SESSION['username']))
            {
                die("You are not logged in!");
            }
            $username = $_SESSION['username'];
            echo "Hai " . $username;
        ?>
    </span></a></li>
</ul>
</nav>

PS: TO make your Query Secure use parameterized query like this

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$stmt = $conn->prepare(SELECT * FROM loginform where korisnickoime='?' AND sifrajedan='?' limit 1");
$stmt->bind_param("ss", $username, $password);

// set parameters and execute
$username = "John";
$password = "Doe";
$result = $stmt->execute();

?>


来源: stackexchange

问:
kubectl get -o yaml: is it possible to hide metadata.managedFields?
Using kubectl version 1.18, on microk8s 1.18.3

When getting a resource definition in yaml format. Example  kubectl get pod/mypod-6f855c5fff-j8mrw -o yaml. The output contains a section related to metadata.managedFields

Is there a way to hide that metadata.managedFields to shorten the console output?

Below is an example of output to better illustrate the question.

```<code>apiVersion: v1
kind: Service
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"v1","kind":"Service","metadata":{"annotations":{},"labels":{"app":"productpage","service":"productpage"},"name":"productpage","namespace":"bookinfo"},"spec":{"ports":[{"name":"http","port":9080}],"selector":{"app":"productpage"}}}
  creationTimestamp: "2020-05-28T05:22:41Z"
  labels:
    app: productpage
    service: productpage
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:metadata:
        f:annotations:
          .: {}
          f:kubectl.kubernetes.io/last-applied-configuration: {}
        f:labels:
          .: {}
          f:app: {}
          f:service: {}
      f:spec:
        f:ports:
          .: {}
          k:{"port":9080,"protocol":"TCP"}:
            .: {}
            f:name: {}
            f:port: {}
            f:protocol: {}
            f:targetPort: {}
        f:selector:
          .: {}
          f:app: {}
        f:sessionAffinity: {}
        f:type: {}
    manager: kubectl
    operation: Update
    time: "2020-05-28T05:22:41Z"
  name: productpage
  namespace: bookinfo
  resourceVersion: "121804"
  selfLink: /api/v1/namespaces/bookinfo/services/productpage
  uid: feb5a62b-8784-41d2-b104-bf6ebc4a2763
spec:
  clusterIP: 10.152.183.9
  ports:
  - name: http
    port: 9080
    protocol: TCP
    targetPort: 9080
  selector:
    app: productpage
  sessionAffinity: None
  type: ClusterIP
status:
  loadBalancer: {}
</code>```

答:
check out this kubectl plugin: https://github.com/itaysk/kubectl-neat.
it not only removes managedField but many other fields users are not interested in.

for example: kubectl get pod mymod -oyaml | kubectl neat or kubectl neat pod mypod -oyaml

ContentLicense: CC BY-SA 4.0

Body:
Using kubectl version 1.18, on microk8s 1.18.3

When getting a resource definition in yaml format. Example  kubectl get pod/mypod-6f855c5fff-j8mrw -o yaml. The output contains a section related to metadata.managedFields

Is there a way to hide that metadata.managedFields to shorten the console output?

Below is an example of output to better illustrate the question.

apiVersion: v1
kind: Service
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"v1","kind":"Service","metadata":{"annotations":{},"labels":{"app":"productpage","service":"productpage"},"name":"productpage","namespace":"bookinfo"},"spec":{"ports":[{"name":"http","port":9080}],"selector":{"app":"productpage"}}}
  creationTimestamp: "2020-05-28T05:22:41Z"
  labels:
    app: productpage
    service: productpage
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:metadata:
        f:annotations:
          .: {}
          f:kubectl.kubernetes.io/last-applied-configuration: {}
        f:labels:
          .: {}
          f:app: {}
          f:service: {}
      f:spec:
        f:ports:
          .: {}
          k:{"port":9080,"protocol":"TCP"}:
            .: {}
            f:name: {}
            f:port: {}
            f:protocol: {}
            f:targetPort: {}
        f:selector:
          .: {}
          f:app: {}
        f:sessionAffinity: {}
        f:type: {}
    manager: kubectl
    operation: Update
    time: "2020-05-28T05:22:41Z"
  name: productpage
  namespace: bookinfo
  resourceVersion: "121804"
  selfLink: /api/v1/namespaces/bookinfo/services/productpage
  uid: feb5a62b-8784-41d2-b104-bf6ebc4a2763
spec:
  clusterIP: 10.152.183.9
  ports:
  - name: http
    port: 9080
    protocol: TCP
    targetPort: 9080
  selector:
    app: productpage
  sessionAffinity: None
  type: ClusterIP
status:
  loadBalancer: {}


问:
Uncaught Reference Error when trying to pass a function through a button in JavaScript?
I'm trying to write a navigation bar at the top of my web app to change a parameter in backend, but when I call the function it always return an unexpected end of input or an uncaught reference error that says my function was not defined on click. Can someone please help me figure out what I'm doing wrong?

JS File:

```<code>let typearray=["supermarkets_and_groceries", "churches", "cafes"];
let type = "supermarkets_and_groceries";
function changeType(randomstring){
    console.log('ok');
    type = randomstring;
    console.log(type);
}

let str = '<div class="topnav">';
for(let count = 0; count < typearray.length; count++){
    str = str +
    '<button onclick ="changeType("'+typearray[count]+'")" title = " '+ typearray[count] + '">' +typearray[count] +'</button>';
}
str = str + '</div>' +
'</div>';
console.log(str);

document.getElementById('navbar').innerHTML = str;
</code>```

HTML File(includes the rest of the program)

```<code><html>
  <head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1">
    <meta charset="utf-8">
    <style>
      #map {
        height: 75%;
        width: 75%;
      }
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <script src = getlocation.js></script>
    <!-- this implements the navbar-->
    <div id="navbar"></div>
    <script type = "module" src = navbar.js></script>
    <!-- this implements the map-->
    <div id="map"></div>
    <script src = index.js> </script>
    <!-- this implements the list-->
    <div id="list"></div>
    <script type = "module" src = rankedstores.js></script>
    <script src="https://maps.googleapis.com/maps/api/js?key=000000000000000000
    &callback=initMap"></script>
  </body>
</html>
</code>```

答:
Modified Code Snippet </p>

```<code>let typearray = ["supermarkets_and_groceries", "churches", "cafes"];
  let type = "supermarkets_and_groceries";
  function changeType(event) {
    type = event.target.getAttribute("type");
    console.log(type);
  }

  let navHtml = document.createElement("div");

  for (let count = 0; count < typearray.length; count++) {
    let btn = document.createElement("button");
    btn.setAttribute("type", typearray[count]);
    btn.setAttribute("title", typearray[count]);
    btn.innerText = typearray[count];
    btn.addEventListener("click", changeType);
    navHtml.appendChild(btn);
  }
  document.getElementById("navbar").appendChild(navHtml);
</code>```

Body:
I'm trying to write a navigation bar at the top of my web app to change a parameter in backend, but when I call the function it always return an unexpected end of input or an uncaught reference error that says my function was not defined on click. Can someone please help me figure out what I'm doing wrong?

JS File:

let typearray=["supermarkets_and_groceries", "churches", "cafes"];
let type = "supermarkets_and_groceries";
function changeType(randomstring){
    console.log('ok');
    type = randomstring;
    console.log(type);
}

let str = '
';
for(let count = 0; count < typearray.length; count++){
    str = str +
    '<button onclick ="changeType("'+typearray[count]+'")" title = " '+ typearray[count] + '">' +typearray[count] +'</button>';
}
str = str + '
' +
'
';
console.log(str);

document.getElementById('navbar').innerHTML = str;

HTML File(includes the rest of the program)

    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1">
    <meta charset="utf-8">

Body:
Modified Code Snippet

let typearray = ["supermarkets_and_groceries", "churches", "cafes"];
  let type = "supermarkets_and_groceries";
  function changeType(event) {
    type = event.target.getAttribute("type");
    console.log(type);
  }

  let navHtml = document.createElement("div");

  for (let count = 0; count < typearray.length; count++) {
    let btn = document.createElement("button");
    btn.setAttribute("type", typearray[count]);
    btn.setAttribute("title", typearray[count]);
    btn.innerText = typearray[count];
    btn.addEventListener("click", changeType);
    navHtml.appendChild(btn);
  }
  document.getElementById("navbar").appendChild(navHtml);


问:
Check if object is visible
How would I check if an object drawn in openGL-ES is visible?</p>

答:
You could use a variant of picking. The idea of OpenGL picking is that you render a small area of the view, pushing names on a stack as you go (so you can refer what's being rendered). OpenGL will return a hit record so you know what's been rendered. It is often used to find out what's under the mouse.

So you'd do the following:

setup a small renderable surface (just to do visibility checks)

render your scene onto this renderable surface (replace your models by something simple, e.g. bounding boxes; note you don't need to render actual triangles, you could just render lines or dots instead)

check the hit record to see what's been rendered.

I haven't tried yet, but I think it would work; maybe not very fast, but reliable. Custom visibility/culling algorithms are typically used instead, although writing an efficient visibility/culling algorithm is difficult.

ContentLicense: CC BY-SA 2.5

Title: Check if object is visible

ContentLicense: CC BY-SA 3.0


问:
Need to accomodate gridView in my flutter
Im building an app that shows diets and also have a search bar to look for the diets.
I cant manage accomodate the search bar correctly like outside the gridviewer. heres the code of my view and how it actually looks. I dont want to be like another card

```<code>body: Container(
          child: GridView.builder(
              padding: EdgeInsets.all(15),
              gridDelegate:
                  SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
              itemCount: dietsForDisplay.length + 1,
              itemBuilder: (BuildContext context, int index) {
                if (diets.length == 0) {
                  return Container(
                    child: Padding(
                      padding: const EdgeInsets.all(60.0),
                      child: Text(
                        "No existen Dietas registradas por la nutrióloga.",
                        style: TextStyle(
                            color: Color(0xFF002D53),
                            fontFamily: 'Montserrat',
                            fontSize: 25,
                            fontWeight: FontWeight.bold),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  );
                } else {
                  return index == 0
                      ? _searchBar()
                      : _listItem(
                          context,
                          index - 1,
                        );
                }
              }),
        ));
  }

</code>```

and the code for the searchBar and listItem are Cards

答:
I would suggest you to wrap your Scaffold widget with SafeArea so that your appbar won't get obstructed due to the notch. If you would want to add a search bar in your Scaffold's body, I would suggest using a Column to place your search bar on the top and your GridView.builder() on the bottom.  Here is how it looks like after my suggestions:

```<code>SafeArea(
 child:Scaffold(
  body: Column(
     children: <Widget>[
        //Search Bar here
        Expanded(
          child: //GridView.builder() here
        );
    ],
   ),
  ),
);
</code>```

*If you want that page to be scrollable then replace Column with ListView

Body:
Im building an app that shows diets and also have a search bar to look for the diets.
I cant manage accomodate the search bar correctly like outside the gridviewer. heres the code of my view and how it actually looks. I dont want to be like another card

body: Container(
          child: GridView.builder(
              padding: EdgeInsets.all(15),
              gridDelegate:
                  SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
              itemCount: dietsForDisplay.length + 1,
              itemBuilder: (BuildContext context, int index) {
                if (diets.length == 0) {
                  return Container(
                    child: Padding(
                      padding: const EdgeInsets.all(60.0),
                      child: Text(
                        "No existen Dietas registradas por la nutrióloga.",
                        style: TextStyle(
                            color: Color(0xFF002D53),
                            fontFamily: 'Montserrat',
                            fontSize: 25,
                            fontWeight: FontWeight.bold),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  );
                } else {
                  return index == 0
                      ? _searchBar()
                      : _listItem(
                          context,
                          index - 1,
                        );
                }
              }),
        ));
  }

and the code for the searchBar and listItem are Cards

Body:
I would suggest you to wrap your Scaffold widget with SafeArea so that your appbar won't get obstructed due to the notch. If you would want to add a search bar in your Scaffold's body, I would suggest using a Column to place your search bar on the top and your GridView.builder() on the bottom.  Here is how it looks like after my suggestions:

SafeArea(
 child:Scaffold(
  body: Column(
     children: <Widget>[
        //Search Bar here
        Expanded(
          child: //GridView.builder() here
        );
    ],
   ),
  ),
);

*If you want that page to be scrollable then replace Column with ListView


问:
How I add an object to an existing array? React
recently I started to work in a proyect and I notice that I need some way to modify a value without losing my previous state. Basically work with an array. However I don't know how to do that.
Can anyone help me by telling me how can I modify an state (I'm using react hooks by the way...) to add more values to the previous state in an array?

Sorry not posting code or something like that, I don't even know how to write that.

Thank you in advance.

答:
Use ES6 spread operator to push new object to the existing array.

Adding a new object to an Array:

```<code>const [todo, setTodo] = useState([{ task: "Todo 1" }]);

const addTodo = () => {
    let newTodoTask = { task: `Task ${todo.length + 1}` };

    setTodo(tasks => [...tasks, { ...newTodoTask }]);
};
</code>```

Modifying an object in an Array:

```<code>const editTask = (e, taskId = 0) => {
    setTodo(tasks =>
      tasks.map((task, idx) =>
        idx === taskId ? { task: "Edited Todo 1" } : { ...task }
      )
    );
};
</code>```

Deleting an object from an array

```<code>const deleteTask = (e, taskId = 0) => {
    setTodo(tasks => tasks.filter((task, idx) => idx !== taskId));
};
</code>```

Find the simple working example here.

https://codesandbox.io/s/unruffled-elgamal-h7fhg?file=/src/App.js:482-593

First, Learn basic ES6 before start working on the project.

Body:
Use ES6 spread operator to push new object to the existing array.

Adding a new object to an Array:

const [todo, setTodo] = useState([{ task: "Todo 1" }]);

const addTodo = () => {
    let newTodoTask = { task: `Task ${todo.length + 1}` };

    setTodo(tasks => [...tasks, { ...newTodoTask }]);
};

Modifying an object in an Array:

const editTask = (e, taskId = 0) => {
    setTodo(tasks =>
      tasks.map((task, idx) =>
        idx === taskId ? { task: "Edited Todo 1" } : { ...task }
      )
    );
};

Deleting an object from an array

const deleteTask = (e, taskId = 0) => {
    setTodo(tasks => tasks.filter((task, idx) => idx !== taskId));
};

Find the simple working example here.

https://codesandbox.io/s/unruffled-elgamal-h7fhg?file=/src/App.js:482-593

First, Learn basic ES6 before start working on the project.


问:
Highlight a specific part of the text in SwiftUI
Hello I'm new to Swift and am using SwiftUI for my project where I download some weather data and I display it in the ContentView().

I would like to highlight some part of the Text if it contains some specific word, but I don't have any idea how to start.

In ContentView(), I have tried to set a function receiving the string downloaded from web and return a string. I believe this is wrong, because SwiftUI does not apply the modifiers at the all for the Text.

For example, in my ContentView() I would like the word thunderstorm to have the .bold() modifier:

```<code>struct ContentView: View {
  let testo : String = "There is a thunderstorm in the area"

  var body: some View {
    Text(highlight(str: testo))
  }

  func highlight(str: String) -> String {
    let textToSearch = "thunderstorm"
    var result = ""

    if str.contains(textToSearch) {
      let index = str.startIndex
      result = String( str[index])
    }

    return result
  }

}
</code>```

答:
If that requires just simple word styling then here is possible solution.

Tested with Xcode 11.4 / iOS 13.4

```<code>struct ContentView: View {
    let testo : String = "There is a thunderstorm in the area. Added some testing long text to demo that wrapping works correctly!"

    var body: some View {
        hilightedText(str: testo, searched: "thunderstorm")
            .multilineTextAlignment(.leading)
    }

    func hilightedText(str: String, searched: String) -> Text {
        guard !str.isEmpty && !searched.isEmpty else { return Text(str) }

        var result: Text!
        let parts = str.components(separatedBy: searched)
        for i in parts.indices {
            result = (result == nil ? Text(parts[i]) : result + Text(parts[i]))
            if i != parts.count - 1 {
                result = result + Text(searched).bold()
            }
        }
        return result ?? Text(str)
    }
}
</code>```

Note: below is previously used function, but as commented by @Lkabo it has limitations on very long strings

```<code>func hilightedText(str: String) -> Text {
    let textToSearch = "thunderstorm"
    var result: Text!

    for word in str.split(separator: " ") {
        var text = Text(word)
        if word == textToSearch {
            text = text.bold()
        }
        result = (result == nil ? text : result + Text(" ") + text)
    }
    return result ?? Text(str)
}
</code>```

Body:
Hello I'm new to Swift and am using SwiftUI for my project where I download some weather data and I display it in the ContentView().

I would like to highlight some part of the Text if it contains some specific word, but I don't have any idea how to start.

In ContentView(), I have tried to set a function receiving the string downloaded from web and return a string. I believe this is wrong, because SwiftUI does not apply the modifiers at the all for the Text.

For example, in my ContentView() I would like the word thunderstorm to have the .bold() modifier:

struct ContentView: View {
  let testo : String = "There is a thunderstorm in the area"

  var body: some View {
    Text(highlight(str: testo))
  }

  func highlight(str: String) -> String {
    let textToSearch = "thunderstorm"
    var result = ""

    if str.contains(textToSearch) {
      let index = str.startIndex
      result = String( str[index])
    }

    return result
  }

}

Body:
If that requires just simple word styling then here is possible solution.

Tested with Xcode 11.4 / iOS 13.4

struct ContentView: View {
    let testo : String = "There is a thunderstorm in the area. Added some testing long text to demo that wrapping works correctly!"

    var body: some View {
        hilightedText(str: testo, searched: "thunderstorm")
            .multilineTextAlignment(.leading)
    }

    func hilightedText(str: String, searched: String) -> Text {
        guard !str.isEmpty && !searched.isEmpty else { return Text(str) }

        var result: Text!
        let parts = str.components(separatedBy: searched)
        for i in parts.indices {
            result = (result == nil ? Text(parts[i]) : result + Text(parts[i]))
            if i != parts.count - 1 {
                result = result + Text(searched).bold()
            }
        }
        return result ?? Text(str)
    }
}

Note: below is previously used function, but as commented by @Lkabo it has limitations on very long strings

func hilightedText(str: String) -> Text {
    let textToSearch = "thunderstorm"
    var result: Text!

    for word in str.split(separator: " ") {
        var text = Text(word)
        if word == textToSearch {
            text = text.bold()
        }
        result = (result == nil ? text : result + Text(" ") + text)
    }
    return result ?? Text(str)
}


问:
How to force Laravel Project to use HTTPS for all routes?
I am working on a project that requires a secure connection.

I can set the route, uri, asset to use 'https' via:

```<code>Route::get('order/details/{id}', ['uses' => 'OrderController@details', 'as' => 'order.details', 'https']);

url($language.'/index', [], true)

asset('css/bootstrap.min.css', true)
</code>```

But setting the parameters all the time seems tiring.

Is there a way to force all routes to generate HTTPS links?

答:
Force Https in Laravel 7.x (2020)

"2020 Update? Url::forceScheme was acting funky for me, but this worked liked a dime."

https code snippet.

resolve(\Illuminate\Routing\UrlGenerator::class)->forceScheme('https');

Add that snippet within any Service Provider Boot Method

1: Open app/providers/RouteServiceProvider.php.

2: Then add the https code snippet to the boot method.

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        resolve(\Illuminate\Routing\UrlGenerator::class)->forceScheme('https');

        parent::boot();
    }
```

3: Lastly run php artisan route:clear && composer dumpautoload to clear Laravel's cached routes and cached Service Providers.

Body:
I am working on a project that requires a secure connection.

I can set the route, uri, asset to use 'https' via:

Route::get('order/details/{id}', ['uses' => 'OrderController@details', 'as' => 'order.details', 'https']);

url($language.'/index', [], true)

asset('css/bootstrap.min.css', true)

But setting the parameters all the time seems tiring.

Is there a way to force all routes to generate HTTPS links?

Body:
Force Https in Laravel 7.x (2020)

"2020 Update? Url::forceScheme was acting funky for me, but this worked liked a dime."

https code snippet.

resolve(\Illuminate\Routing\UrlGenerator::class)->forceScheme('https');

Add that snippet within any Service Provider Boot Method

1: Open app/providers/RouteServiceProvider.php.

2: Then add the https code snippet to the boot method.

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        resolve(\Illuminate\Routing\UrlGenerator::class)->forceScheme('https');

        parent::boot();
    }

3: Lastly run php artisan route:clear && composer dumpautoload to clear Laravel's cached routes and cached Service Providers.


问:
How to optimize the query? t-sql
This query works about 3 minutes and returns 7279 rows:

```<code>SELECT identity(int,1,1) as id, c.client_code, a.account_num,
        c.client_short_name, u.uso, us.fio, null as new, null as txt
INTO #ttable
FROM accounts a INNER JOIN Clients c ON
    c.id = a.client_id INNER JOIN Uso u ON c.uso_id = u.uso_id INNER JOIN
    Magazin m ON a.account_id = m.account_id LEFT JOIN Users us ON
    m.user_id = us.user_id
WHERE m.status_id IN ('1','5','9') AND m.account_new_num is null
    AND u.branch_id = @branch_id
ORDER BY c.client_code;
</code>```

The type of 'client_code' field is VARCHAR(6).

Is it possible to somehow optimize this query?

答: Do you have indexes set up for your tables? An index on foreign key columns as well as Magazin.status might help.</p>

Title: How to optimize the query? t-sql

Body:
This query works about 3 minutes and returns 7279 rows:

SELECT identity(int,1,1) as id, c.client_code, a.account_num,
        c.client_short_name, u.uso, us.fio, null as new, null as txt
INTO #ttable
FROM accounts a INNER JOIN Clients c ON
    c.id = a.client_id INNER JOIN Uso u ON c.uso_id = u.uso_id INNER JOIN
    Magazin m ON a.account_id = m.account_id LEFT JOIN Users us ON
    m.user_id = us.user_id
WHERE m.status_id IN ('1','5','9') AND m.account_new_num is null
    AND u.branch_id = @branch_id
ORDER BY c.client_code;

The type of 'client_code' field is VARCHAR(6).

Is it possible to somehow optimize this query?


问:
how to update all my local git branches with a single script?
I wish to use only the git tool and not any other tools to do this. I am looking for a shell script or even it is a inbuilt git sub command which can update all of my local branches by pulling changes from the origin master. So that I can simply run the script or the sub command to get this done.
Please help.</p>

答: you can use git pull --all to update all your local branches.


问:
How can I convert a normal array of doubles to a guava immutable array
I was just wondering how would i go about converting this:

Into a Google Guava ImmutableDoubleArray.

```<code>public class Data  {

    private final ImmutableDoubleArray arrays;

    public Data(double[] array)
    {

    }
</code>```

Thank you.

答:
```<code>this.arrays = ImmutableDoubleArray.copyOf(array);
</code>```

Using ImmutableDoubleArray is generally preferable to using ImmutableList, because it does not come with the overhead of boxing.

Body:
I was just wondering how would i go about converting this:

Into a Google Guava ImmutableDoubleArray.

public class Data  {

    private final ImmutableDoubleArray arrays;

    public Data(double[] array)
    {

    }

Thank you.

Body:
this.arrays = ImmutableDoubleArray.copyOf(array);

Using ImmutableDoubleArray is generally preferable to using ImmutableList, because it does not come with the overhead of boxing.


问:
pick a random image from unsplash API reactjs
I am developing a reactjs application which uses unsplash API to update background images of the application. The result from the API is as below:

```<code>{total: 2330, total_pages: 78, results: Array(30)}
</code>```

As the API gives back 30 images only per page, I have implemented the following logic to retrieve any random image from the list of 30 images:

```<code>        if (typeof response.data !== "undefined") {
          const num = Math.floor(Math.random() * 30) + 1;
          const url = response.data.results[num].urls.regular;
          updateBackground(url);
        }
</code>```

But the above logic is limited to picking up a random image from the first page only. How do I pick a random image from the total of 2330 images ? Is there a way to exclude total_pages from the result ?

Thanks

答:
Wouldn't the Random Photo API be the solution you need? https://unsplash.com/documentation#get-a-random-photo

Otherwise if that's not what you need, you could randomize the page you pick from in addition to the photo within that page, perhaps.

Body:
I am developing a reactjs application which uses unsplash API to update background images of the application. The result from the API is as below:

{total: 2330, total_pages: 78, results: Array(30)}

As the API gives back 30 images only per page, I have implemented the following logic to retrieve any random image from the list of 30 images:

        if (typeof response.data !== "undefined") {
          const num = Math.floor(Math.random() * 30) + 1;
          const url = response.data.results[num].urls.regular;
          updateBackground(url);
        }

But the above logic is limited to picking up a random image from the first page only. How do I pick a random image from the total of 2330 images ? Is there a way to exclude total_pages from the result ?

Thanks


问:
Converting a json object to an associative array
I have this array which is retrieved by a json_encode().When I execute

```<code>$.getJSON('beta.php' , function(data){
    console.log(data);
});
</code>```

I get the result as follows

```<code>[
Object { StuId="1", fName="Saman", more...},
Object { StuId="2", fName="Marry", more...},
Object { StuId="3", fName="Navjoth", more...},
Object { StuId="4", fName="Jassu", more...}
]
</code>```

I'm trying to iterate through this result using

```<code>$.each(data, function(key, value){

            for(var key in value){

                if(value.hasOwnProperty(key)){

                        $("#article tbody").html(
                        "<tr><td>" + value.StuId +
                        "</td><td>" + value.fName +
                        "</td><td>" + value.lName +
                        "</td><td>" + value.age +
                        "</td><td>" + value.grade +
                        "</td></tr>");

                        $("article tbody").appendTo("document.body");

                }

                }

        });
</code>```

.I guess It is impossible because of the above format of the array.

If someone could explain why this is happening and how to correct it I would be really grateful.I want to know how to convert the above into the following format.

```<code>[
{"StuId":"1","fName":"Saman","lName":"Kumara","age":"14","grade":"A"},
{"StuId":"2","fName":"Marry","lName":"Vass","age":"12","grade":"B"},
{"StuId":"3","fName":"Navjoth","lName":"Bogal","age":"32","grade":"A"},
{"StuId":"4","fName":"Jassu","lName":"Singh","age":"22","grade":"E"}
]
</code>```

答:
The base object is a javascript array, so can you not:

```<code>$.each(data, function(item) {
    var html = "<tr><td>" + item.StuId + "</td><td>" + item.fname + "</td></tr>";
    // etc.
});
</code>```

?

Body:
I have this array which is retrieved by a json_encode().When I execute

$.getJSON('beta.php' , function(data){
    console.log(data);
});

I get the result as follows

[
Object { StuId="1", fName="Saman", more...},
Object { StuId="2", fName="Marry", more...},
Object { StuId="3", fName="Navjoth", more...},
Object { StuId="4", fName="Jassu", more...}
]

I'm trying to iterate through this result using

$.each(data, function(key, value){

            for(var key in value){

                if(value.hasOwnProperty(key)){

                        $("#article tbody").html(
                        "
" + value.StuId +
                        "	" + value.fName +
                        "	" + value.lName +
                        "	" + value.age +
                        "	" + value.grade +
                        "
");

                        $("article tbody").appendTo("document.body");

                }

                }

        });

.I guess It is impossible because of the above format of the array.

If someone could explain why this is happening and how to correct it I would be really grateful.I want to know how to convert the above into the following format.

[
{"StuId":"1","fName":"Saman","lName":"Kumara","age":"14","grade":"A"},
{"StuId":"2","fName":"Marry","lName":"Vass","age":"12","grade":"B"},
{"StuId":"3","fName":"Navjoth","lName":"Bogal","age":"32","grade":"A"},
{"StuId":"4","fName":"Jassu","lName":"Singh","age":"22","grade":"E"}
]

Body:
The base object is a javascript array, so can you not:

$.each(data, function(item) {
    var html = "<tr><td>" + item.StuId + "</td><td>" + item.fname + "</td></tr>";
    // etc.
});

?


问:
TypeError: argument of type 'int' is not iterable in indexing
Why does my code print: TypeError: argument of type 'int' is not iterable, whenever I run it? I have the following lists given below. What I am trying to do is to get the element/s in O then find its match in J. After finding the match, the index is obtained. Using this index, I will find its corresponding value in R.

```<code>    J = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    R = [[0, 0], [4, 3], [2, 0], [2, 1], [0, 3], [1, 1], [1, 2], [2, 1], [0, 3], [2, 2], [0, 0]]
    O = J[0]

    R_demand = [d for a, d in zip(J, R) if a in O]
    print(R_demand)
</code>```

For the code above, since O = 1 in J, I should get R_demand = [0, 0] as my answer. All values in lists are integers.

答:
You are correct, O == 1. Which is why the conditional part of your list comprehension if a in O throws a TypeError. The in operation needs an iterable to follow it, 1 is a constant (non-iterable), so a in 1 is invalid. If O will always be an integer, just change in to ==, as in:

```<code>R_demand = [d for a, d in zip(J, R) if a == O]
</code>```

But even better would be to ensure that O is an interable, like a set or a list. If you use O = {1} or O = {3, 6, 9} as in your comment below, then you should be able to use in as you previously had. Have you tried that?

Hope that helps, happy coding!

Body:
Why does my code print: TypeError: argument of type 'int' is not iterable, whenever I run it? I have the following lists given below. What I am trying to do is to get the element/s in O then find its match in J. After finding the match, the index is obtained. Using this index, I will find its corresponding value in R.

    J = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    R = [[0, 0], [4, 3], [2, 0], [2, 1], [0, 3], [1, 1], [1, 2], [2, 1], [0, 3], [2, 2], [0, 0]]
    O = J[0]

    R_demand = [d for a, d in zip(J, R) if a in O]
    print(R_demand)

For the code above, since O = 1 in J, I should get R_demand = [0, 0] as my answer. All values in lists are integers.

Body:
You are correct, O == 1. Which is why the conditional part of your list comprehension if a in O throws a TypeError. The in operation needs an iterable to follow it, 1 is a constant (non-iterable), so a in 1 is invalid. If O will always be an integer, just change in to ==, as in:

R_demand = [d for a, d in zip(J, R) if a == O]

But even better would be to ensure that O is an interable, like a set or a list. If you use O = {1} or O = {3, 6, 9} as in your comment below, then you should be able to use in as you previously had. Have you tried that?

Hope that helps, happy coding!


问:
Why does this beginner python program stop midway?
This is my first day learning python from a book called "Automate the Boring Stuff with Python".

On the "your first program" section the program is this

```<code># This program says hello and asks for my name.
print('Hello world!')
print('What is your name?')  # ask for their name
myName = input("Mizu")
print('It is good to meet you, ' + myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?')  # ask for their age
myAge = input('20')
print('You will be ' + str(int(myAge) + 1) + ' in a year.')
</code>```

but the program only runs

```<code>Hello world!
What is your name?
Mizu
</code>```

but if i replace the input() functions with just values like myName = 'Mizu' , it prints the rest of the lines just fine.

What am i doing wrong here?

i used the default python editor and pycharm and both show no errors or anything.

答:
Note, the book says

```<code>myName = input()
</code>```

so that's what you put in your programme, not

```<code>myName = input("Mizu")
</code>```

and then, likes others have written, when the programme gets there you type in your name.

CAUTION this is correct for python 3. Check your version. If you are using python 2, replace "input" with "raw_input()"

```<code>myName = raw_input()
</code>```

Body:
This is my first day learning python from a book called "Automate the Boring Stuff with Python".

On the "your first program" section the program is this

# This program says hello and asks for my name.
print('Hello world!')
print('What is your name?')  # ask for their name
myName = input("Mizu")
print('It is good to meet you, ' + myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?')  # ask for their age
myAge = input('20')
print('You will be ' + str(int(myAge) + 1) + ' in a year.')

but the program only runs

Hello world!
What is your name?
Mizu

but if i replace the input() functions with just values like myName = 'Mizu' , it prints the rest of the lines just fine.

What am i doing wrong here?

i used the default python editor and pycharm and both show no errors or anything.

Body:
Note, the book says

myName = input()

so that's what you put in your programme, not

myName = input("Mizu")

and then, likes others have written, when the programme gets there you type in your name.

CAUTION this is correct for python 3. Check your version. If you are using python 2, replace "input" with "raw_input()"

myName = raw_input()


问:
python to c# convert?
Py To C# how can i convert?
Py Code

```<code>
def mygames_login():
 payload = {
   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
   'Accept-Encoding': 'gzip, deflate, br',
   'Accept-Language': 'en-US,en;q=0.9,it-IT;q=0.8,it;q=0.7',
   'Connection': 'keep-alive',
   'Content-Type': 'application/x-www-form-urlencoded',
   'Cookie':'amc_lang=en_US; ',
   'DNT': '1',
   'Host': 'auth-ac.my.games',
   'Origin': 'https://account.my.games',
   'Referer': 'https://account.my.games/oauth2/login/?continue=https%3A%2F%2Faccount.my.games%2Foauth2%2F%3Fredirect_uri%3Dhttps%253A%252F%252Fpc.warface.com%252Fdynamic%252Fauth%252F%253Fo2%253D1%26client_id%3Dwf.my.com%26response_type%3Dcode%26signup_method%3Demail%2Cphone%26signup_social%3Dmailru%252Cfb%252Cvk%252Cg%252Cok%252Ctwitch%252Ctw%252Cps%252Cxbox%252Csteam%26lang%3Den_US&client_id=wf.my.com&lang=en_US&signup_method=email%2Cphone&signup_social=mailru%2Cfb%2Cvk%2Cg%2Cok%2Ctwitch%2Ctw%2Cps%2Cxbox%2Csteam',
   'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
   }
 login_data = {
   'email':email.get(),
   'password':password.get(),
   'continue':'https://account.my.games/oauth2/?redirect_uri=https%3A%2F%2Fpc.warface.com%2Fdynamic%2Fauth%2F%3Fo2%3D1&client_id=wf.my.com&response_type=code&signup_method=email,phone&signup_social=mailru%2Cfb%2Cvk%2Cg%2Cok%2Ctwitch%2Ctw%2Cps%2Cxbox%2Csteam&lang=en_US',
   'failure':'https://account.my.games/oauth2/login/?continue=https%3A%2F%2Faccount.my.games%2Foauth2%2Flogin%2F%3Fcontinue%3Dhttps%253A%252F%252Faccount.my.games%252Foauth2%252F%253Fredirect_uri%253Dhttps%25253A%25252F%25252Fpc.warface.com%25252Fdynamic%25252Fauth%25252F%25253Fo2%25253D1%2526client_id%253Dwf.my.com%2526response_type%253Dcode%2526signup_method%253Demail%252Cphone%2526signup_social%253Dmailru%25252Cfb%25252Cvk%25252Cg%25252Cok%25252Ctwitch%25252Ctw%25252Cps%25252Cxbox%25252Csteam%2526lang%253Den_US%26client_id%3Dwf.my.com%26lang%3Den_US%26signup_method%3Demail%252Cphone%26signup_social%3Dmailru%252Cfb%252Cvk%252Cg%252Cok%252Ctwitch%252Ctw%252Cps%252Cxbox%252Csteam&client_id=wf.my.com&lang=en_US&signup_method=email%2Cphone&signup_social=mailru%2Cfb%2Cvk%2Cg%2Cok%2Ctwitch%2Ctw%2Cps%2Cxbox%2Csteam',
   'nosavelogin':'0'
   }
 while True:
   try:
     r = s.post('https://auth-ac.my.games/auth',headers=payload,data=login_data, allow_redirects=False)
     for i in range(0,5):
       """
       1- Auth redirect to oauth2
       2- Oauth2 redirect to sdc
       3- Generates link to get to sdc token
       4- SDC token redirects to oauth2
       5- Auth link for pc.warface.com is generated
       6- GET auth link for session
       """
       r = s.get(r.headers['location'], allow_redirects=False)
     get_token = s.get('https://pc.warface.com/minigames/user/info').json()
     s.cookies['mg_token'] = get_token['data']['token']
     s.cookies['cur_language'] = op_lang()
   except:
     continue
   break
 notificationSender("Crate Manager","Logged in with My.Games profile")
 main_app()

</code>```

site: https://pc.warface.com/en/
login to this site. I want to get the incoming value. how can I do that

I want to convert this code to c#
how?

c# Convert Help me pls
Bad English Sorry
I use Google translation

答:
Your code is lazy and I have no idea what's going on ...
for example why you did like this:

```<code>   for i in range(0,5):
       r = s.get(r.headers['location'], allow_redirects=False)
</code>```

You reassign to r variable five times in a useless for loop.

By the way, you can easily write your code in c# syntax

```<code>while True:
  # stuff
</code>```

turns to

```<code>while(true)
{
}
</code>```

for Get/Post request do like this:

```<code>using (HttpClient client = new HttpClient())
        {
            var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
            var response = await client.GetAsync(url, content); // or PostAsync
            if (response != null)
            {
                var jsonString = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<object>(jsonString);
            }
        }
</code>```

Goodjob

Title: python to c# convert?

Body:
Py To C# how can i convert?
Py Code

def mygames_login():
 payload = {
   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
   'Accept-Encoding': 'gzip, deflate, br',
   'Accept-Language': 'en-US,en;q=0.9,it-IT;q=0.8,it;q=0.7',
   'Connection': 'keep-alive',
   'Content-Type': 'application/x-www-form-urlencoded',
   'Cookie':'amc_lang=en_US; ',
   'DNT': '1',
   'Host': 'auth-ac.my.games',
   'Origin': 'https://account.my.games',
   'Referer': 'https://account.my.games/oauth2/login/?continue=https%3A%2F%2Faccount.my.games%2Foauth2%2F%3Fredirect_uri%3Dhttps%253A%252F%252Fpc.warface.com%252Fdynamic%252Fauth%252F%253Fo2%253D1%26client_id%3Dwf.my.com%26response_type%3Dcode%26signup_method%3Demail%2Cphone%26signup_social%3Dmailru%252Cfb%252Cvk%252Cg%252Cok%252Ctwitch%252Ctw%252Cps%252Cxbox%252Csteam%26lang%3Den_US&client_id=wf.my.com&lang=en_US&signup_method=email%2Cphone&signup_social=mailru%2Cfb%2Cvk%2Cg%2Cok%2Ctwitch%2Ctw%2Cps%2Cxbox%2Csteam',
   'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
   }
 login_data = {
   'email':email.get(),
   'password':password.get(),
   'continue':'https://account.my.games/oauth2/?redirect_uri=https%3A%2F%2Fpc.warface.com%2Fdynamic%2Fauth%2F%3Fo2%3D1&client_id=wf.my.com&response_type=code&signup_method=email,phone&signup_social=mailru%2Cfb%2Cvk%2Cg%2Cok%2Ctwitch%2Ctw%2Cps%2Cxbox%2Csteam&lang=en_US',
   'failure':'https://account.my.games/oauth2/login/?continue=https%3A%2F%2Faccount.my.games%2Foauth2%2Flogin%2F%3Fcontinue%3Dhttps%253A%252F%252Faccount.my.games%252Foauth2%252F%253Fredirect_uri%253Dhttps%25253A%25252F%25252Fpc.warface.com%25252Fdynamic%25252Fauth%25252F%25253Fo2%25253D1%2526client_id%253Dwf.my.com%2526response_type%253Dcode%2526signup_method%253Demail%252Cphone%2526signup_social%253Dmailru%25252Cfb%25252Cvk%25252Cg%25252Cok%25252Ctwitch%25252Ctw%25252Cps%25252Cxbox%25252Csteam%2526lang%253Den_US%26client_id%3Dwf.my.com%26lang%3Den_US%26signup_method%3Demail%252Cphone%26signup_social%3Dmailru%252Cfb%252Cvk%252Cg%252Cok%252Ctwitch%252Ctw%252Cps%252Cxbox%252Csteam&client_id=wf.my.com&lang=en_US&signup_method=email%2Cphone&signup_social=mailru%2Cfb%2Cvk%2Cg%2Cok%2Ctwitch%2Ctw%2Cps%2Cxbox%2Csteam',
   'nosavelogin':'0'
   }
 while True:
   try:
     r = s.post('https://auth-ac.my.games/auth',headers=payload,data=login_data, allow_redirects=False)
     for i in range(0,5):
       """
       1- Auth redirect to oauth2
       2- Oauth2 redirect to sdc
       3- Generates link to get to sdc token
       4- SDC token redirects to oauth2
       5- Auth link for pc.warface.com is generated
       6- GET auth link for session
       """
       r = s.get(r.headers['location'], allow_redirects=False)
     get_token = s.get('https://pc.warface.com/minigames/user/info').json()
     s.cookies['mg_token'] = get_token['data']['token']
     s.cookies['cur_language'] = op_lang()
   except:
     continue
   break
 notificationSender("Crate Manager","Logged in with My.Games profile")
 main_app()

site: https://pc.warface.com/en/
login to this site. I want to get the incoming value. how can I do that

I want to convert this code to c#
how?

c# Convert Help me pls
Bad English Sorry
I use Google translation

Body:
Your code is lazy and I have no idea what's going on ...
for example why you did like this:

   for i in range(0,5):
       r = s.get(r.headers['location'], allow_redirects=False)

You reassign to r variable five times in a useless for loop.

By the way, you can easily write your code in c# syntax

while True:
  # stuff

turns to

while(true)
{
}

for Get/Post request do like this:

using (HttpClient client = new HttpClient())
        {
            var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
            var response = await client.GetAsync(url, content); // or PostAsync
            if (response != null)
            {
                var jsonString = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<object>(jsonString);
            }
        }

Goodjob


问:
Append / copy table row with a dropdown value from database in javascript / jQuery
I have a dropdown value from database in table row,

```<code><button type="button" class="btn btn-outline-primary" id="addbutton">Add Item</button>
<table class="table" id="table">
      <thead>
        <tr>
          <th scope="col">Name</th>
        </tr>
      </thead>
      <tbody>
        <tr>
            <td>
            <select >
              <option selected="" disabled="">--Select Product Name--</option>
                <?php
                $con = new mysqli($host, $dbid, $dbpass, $dbname);
                $stmt = $con->prepare( "SELECT name FROM product ORDER BY name DESC" );
                $stmt->execute();
                $result = $stmt->get_result();
                $con->close();
                while($row = mysqli_fetch_assoc($result)) {
                  echo '<option value="'.$row["name"].'">'.$row["name"].'</option>';
                }
              ?>
            </select>
            </td>
        </tr>
        </tbody>
    </table>
</code>```

if I click add button, I want to append the row that have same dropdown without make a database query again (for a dropdown value).
I have make jQuery to add row

```<code>  $("#addbutton").click(function(){
    $('#table tr:last').after(' _??_ ');
  });
</code>```

what is the best way to do this?

答:
You can have implemented by selecting the
 that contains the select then .clone() it and using .appendTo() you can have added to the table, here is a working snippet:

$('#addbutton').click(function() {
  $('table tr:last-child').clone().appendTo($('table'))
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-outline-primary" id="addbutton">Add Item</button>
<table class="table" id="table">
    <thead>
        <tr>
            <th scope="col">Name</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
                <select>
                    <option selected="" disabled="">--Select Product Name--</option>
                    <option selected="" disabled="">option1</option>
                    <option selected="" disabled="">option2</option>
                    <option selected="" disabled="">option3</option>
                    <option selected="" disabled="">option4</option>
                </select>
            </td>
        </tr>
    </tbody>
</table></code>```

Body:
I have a dropdown value from database in table row,

<button type="button" class="btn btn-outline-primary" id="addbutton">Add Item</button>

          Name

            <select >
              <option selected="" disabled="">--Select Product Name--</option>
                <?php
                $con = new mysqli($host, $dbid, $dbpass, $dbname);
                $stmt = $con->prepare( "SELECT name FROM product ORDER BY name DESC" );
                $stmt->execute();
                $result = $stmt->get_result();
                $con->close();
                while($row = mysqli_fetch_assoc($result)) {
                  echo '<option value="'.$row["name"].'">'.$row["name"].'</option>';
                }
              ?>
            </select>

if I click add button, I want to append the row that have same dropdown without make a database query again (for a dropdown value).
I have make jQuery to add row

  $("#addbutton").click(function(){
    $('#table tr:last').after(' _??_ ');
  });

what is the best way to do this?

Body:
You can have implemented by selecting the <tr> that contains the select then .clone() it and using .appendTo() you can have added to the table, here is a working snippet:

$('#addbutton').click(function() {
  $('table tr:last-child').clone().appendTo($('table'))
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-outline-primary" id="addbutton">Add Item</button>
<table class="table" id="table">
    <thead>
        <tr>
            <th scope="col">Name</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
                <select>
                    <option selected="" disabled="">--Select Product Name--</option>
                    <option selected="" disabled="">option1</option>
                    <option selected="" disabled="">option2</option>
                    <option selected="" disabled="">option3</option>
                    <option selected="" disabled="">option4</option>
                </select>
            </td>
        </tr>
    </tbody>
</table>


问:
VSCode extension works in development but fails when installed
I created an extension for adding test files in Ruby on Rails - https://github.com/SimonBo/rails-go-to-test. It works when I test it locally (press F5 from VSCode with the extension code open) but when I package the extension and install it i get =>  "command 'extension.goToTest' not found". The problem is probably with runtime dependencies but not sure how to fix this.</p>

答:
Turns out I was using mkdirp but it wasnt specified in dependencies in package.json, adding the following line fixed everything:</p>

```<code>"dependencies": {
    "mkdirp": "^0.5.1"
  }
</code>```

Body:
Turns out I was using mkdirp but it wasnt specified in dependencies in package.json, adding the following line fixed everything:

"dependencies": {
    "mkdirp": "^0.5.1"
  }


问:
Problem while retrieving Button tags
my app requirements are as follows:-

1.) Make a Buttton  according to Number of images store in a library.(i have done it).
2.) Disable all buttons when user click on Disable Button.
to full fill the second requirement i set the tag of each button at the time of creation:

```<code>button.setTag=tag;
</code>```

where tag increase on e by one.

problem is that when i disable button it disable only last button.how can i acess button tag value one by one.?

```<code>for (int index = 0; index < [objectButtonArray count];index++) {
    UIButton *button = [objectButtonArray objectAtIndex:index];
    button.hidden = NO;
    imageButton.userInteractionEnabled = NO;
}
</code>```

答: Either use button.tag = tag; or [button setTag:tag];. Your line button.setTag=tag; does not do what you think it does (unless you think it's nonsense).

Title: Problem while retrieving Button tags

Body:
my app requirements are as follows:-

1.) Make a Buttton  according to Number of images store in a library.(i have done it).
2.) Disable all buttons when user click on Disable Button.
to full fill the second requirement i set the tag of each button at the time of creation:

button.setTag=tag;

where tag increase on e by one.

problem is that when i disable button it disable only last button.how can i acess button tag value one by one.?

for (int index = 0; index < [objectButtonArray count];index++) {
    UIButton *button = [objectButtonArray objectAtIndex:index];
    button.hidden = NO;
    imageButton.userInteractionEnabled = NO;
}


问:
How to hide a TabLayout with BottomNavigationView
I have a TabLayout with 3 tabs and a BottonNavigation and I need that at the moment of pressing patients and configuration the tablayout disappears, I do not know what line of code I need?
I also use a ViewPager, everything works well the only thing I need is that the TabLayout disappears when it is in patients. In the Patient Fragment I will use a recycleView and CardView, I want to show the photo of the patient and his data

project image:

MainActivity.java:

```<code>public class MainActivity extends AppCompatActivity {
BottomNavigationView mbottomNavigation;
private ViewPager mviewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //bottomNavigation
    mbottomNavigation = (BottomNavigationView) findViewById(R.id.bottom_navigation);
    mbottomNavigation.setOnNavigationItemSelectedListener(navigationItemSelectedListener);
    //aqui se especifica donde es que se quiere que inicie el bottom
    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new AgendaFragment()).commit();
    //ViewPager
    mviewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(mviewPager);
    final BottomNavigationView navigation=(BottomNavigationView)findViewById(R.id.bottom_navigation);
    navigation.setOnNavigationItemSelectedListener(navigationItemSelectedListener);
    mviewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            switch (position){
                case 0:
                    navigation.setSelectedItemId(R.id.nav_agenda);
                    break;
                case 1:
                    navigation.setSelectedItemId(R.id.nav_pacientes);
                    break;
                case 2:
                    navigation.setSelectedItemId(R.id.nav_configuracion);
                    break;
            }

        }
        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });
}

private OnNavigationItemSelectedListener navigationItemSelectedListener = new OnNavigationItemSelectedListener() {
  @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.nav_agenda:
                mviewPager.setCurrentItem(0);
                return true;
            case R.id.nav_pacientes:
                mviewPager.setCurrentItem(1);
                return true;
            case R.id.nav_configuracion:
                mviewPager.setCurrentItem(2);
                return true;
        }
        return false;
    }
};
private void setupViewPager(ViewPager mviewPager) {
   BottomNavPagerAdapter adapter=new BottomNavPagerAdapter(getSupportFragmentManager());
   adapter.addFragment(new AgendaFragment());
   adapter.addFragment(new PacientesFragment());
   adapter.addFragment(new ConfiguracionFragment());
   mviewPager.setAdapter(adapter);
}

}
</code>```

PatientsFragment.java:

```<code>public class AgendaFragment<toolbar> extends Fragment {

private TabLayout tabLayout;
private ViewPager firstViewPager;

public AgendaFragment() {
    // Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView=inflater.inflate(R.layout.fragment_agenda,container,false);
    firstViewPager=(ViewPager)rootView.findViewById(R.id.viewpager_content);
    tabLayout=(TabLayout)rootView.findViewById(R.id.tablayout);
    tabLayout.setupWithViewPager(firstViewPager);
    setupViewPager(firstViewPager);
    return rootView;
}

private void setupViewPager(ViewPager viewPager) {
    TabViewPagerAdapter adapter = new TabViewPagerAdapter(getChildFragmentManager());
    adapter.addFragment(new Tab1Fragment(), "Today");
    adapter.addFragment(new Tab1Fragment(), "Tomorrow");
    adapter.addFragment(new Tab1Fragment(), "Other Date");
    viewPager.setAdapter(adapter);
}
}
</code>```

答: You could just keep your activity layout with the BottomNavigation and the FrameLayout to show the content of each navigation item. Add the AppBar with the Toolbar and TabBar in your Agenda Fragment layout.</p>

Body:
I have a TabLayout with 3 tabs and a BottonNavigation and I need that at the moment of pressing patients and configuration the tablayout disappears, I do not know what line of code I need?
I also use a ViewPager, everything works well the only thing I need is that the TabLayout disappears when it is in patients. In the Patient Fragment I will use a recycleView and CardView, I want to show the photo of the patient and his data

project image:

MainActivity.java:

public class MainActivity extends AppCompatActivity {
BottomNavigationView mbottomNavigation;
private ViewPager mviewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //bottomNavigation
    mbottomNavigation = (BottomNavigationView) findViewById(R.id.bottom_navigation);
    mbottomNavigation.setOnNavigationItemSelectedListener(navigationItemSelectedListener);
    //aqui se especifica donde es que se quiere que inicie el bottom
    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new AgendaFragment()).commit();
    //ViewPager
    mviewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(mviewPager);
    final BottomNavigationView navigation=(BottomNavigationView)findViewById(R.id.bottom_navigation);
    navigation.setOnNavigationItemSelectedListener(navigationItemSelectedListener);
    mviewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            switch (position){
                case 0:
                    navigation.setSelectedItemId(R.id.nav_agenda);
                    break;
                case 1:
                    navigation.setSelectedItemId(R.id.nav_pacientes);
                    break;
                case 2:
                    navigation.setSelectedItemId(R.id.nav_configuracion);
                    break;
            }

        }
        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });
}

private OnNavigationItemSelectedListener navigationItemSelectedListener = new OnNavigationItemSelectedListener() {
  @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.nav_agenda:
                mviewPager.setCurrentItem(0);
                return true;
            case R.id.nav_pacientes:
                mviewPager.setCurrentItem(1);
                return true;
            case R.id.nav_configuracion:
                mviewPager.setCurrentItem(2);
                return true;
        }
        return false;
    }
};
private void setupViewPager(ViewPager mviewPager) {
   BottomNavPagerAdapter adapter=new BottomNavPagerAdapter(getSupportFragmentManager());
   adapter.addFragment(new AgendaFragment());
   adapter.addFragment(new PacientesFragment());
   adapter.addFragment(new ConfiguracionFragment());
   mviewPager.setAdapter(adapter);
}

}

PatientsFragment.java:

public class AgendaFragment<toolbar> extends Fragment {

private TabLayout tabLayout;
private ViewPager firstViewPager;

public AgendaFragment() {
    // Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView=inflater.inflate(R.layout.fragment_agenda,container,false);
    firstViewPager=(ViewPager)rootView.findViewById(R.id.viewpager_content);
    tabLayout=(TabLayout)rootView.findViewById(R.id.tablayout);
    tabLayout.setupWithViewPager(firstViewPager);
    setupViewPager(firstViewPager);
    return rootView;
}

private void setupViewPager(ViewPager viewPager) {
    TabViewPagerAdapter adapter = new TabViewPagerAdapter(getChildFragmentManager());
    adapter.addFragment(new Tab1Fragment(), "Today");
    adapter.addFragment(new Tab1Fragment(), "Tomorrow");
    adapter.addFragment(new Tab1Fragment(), "Other Date");
    viewPager.setAdapter(adapter);
}
}


问:
How to set labels align left in Horizontal Bar using chart.js?
My code using chart.js

```<code>var ctx_1 = document.getElementById('non_200_pages').getContext('2d');
var myChart_1 = new Chart(ctx_1, {
type: 'horizontalBar',
data: {
    labels: ["Total","301 Redirect","Broken Pages (4xx Errors)","Uncategorised HTTP Response Codes","5xx Errors","Unauthorised Pages","Non-301 Redirects"],
    datasets: [{

        data: [ {{ $array_non_200_pages[0] }}, {{ $array_non_200_pages[1] }}, {{ $array_non_200_pages[2] }}, {{ $array_non_200_pages[3] }}, {{ $array_non_200_pages[4] }}, {{ $array_non_200_pages[5] }}, {{ $array_non_200_pages[6]}} ],
        backgroundColor: [
            'rgba(237, 56, 98, 1.0)',
            'rgba(237, 56, 98, 1.0)',
            'rgba(237, 56, 98, 1.0)',
            'rgba(237, 56, 98, 1.0)',
            'rgba(237, 56, 98, 1.0)',
            'rgba(237, 56, 98, 1.0)',
            'rgba(237, 56, 98, 1.0)'
        ]

    }]
},
options: {
    showAllTooltips: true,
    tooltips: {
          enabled: true,
          displayColors: false,
          yPadding: 20,
          xPadding: 30,
          caretSize: 10,
          backgroundColor: 'rgba(240, 240, 240, 1)',
          bodyFontSize: 16,
          bodyFontColor: 'rgb(50, 50, 50)',
          borderColor: 'rgba(0,0,0,1)',
          borderWidth: 1,
          cornerRadius: 0,
          yAlign: 'bottom',
          xAlign: 'center',
          position: 'custom',
          custom: function(tooltip) {
            if (!tooltip) return;
            // disable displaying the color box;
            tooltip.displayColors = false;
          },
          callbacks: {
            // use label callback to return the desired label
            label: function(tooltipItem, data) {
              return tooltipItem.yLabel + " : " + tooltipItem.xLabel ;
            },
            // remove title
            title: function(tooltipItem, data) {
              return;
            }
        }
    },
    responsive: false,
    legend: { display: false },
    scales: {
        yAxes: [{
            ticks: {
                beginAtZero: true,
            },
            gridLines: {
                display: false
            },
        }],
        xAxes: [{
            ticks: {
                stepSize:5,
                display: false
            },
            gridLines: {
                drawBorder: false,
            }
        }],
    },
    plugins: {
        datalabels: {
    align: 'end',
    anchor: 'end',
    backgroundColor: function(context) {
      return context.dataset.backgroundColor;
    },
    borderRadius: 4,
    color: 'white',
    formatter: Math.round
  }
}
}
});
</code>```

My work

Expected Output

I'm having a problem on how to set the labels text align to left. What I want to do is I want my label same with the next picture but I don't know where in Options:{ settings for text align. Is there anyone can help me how to fix it? I can't find any on the  https://www.chartjs.org/docs/latest/configuration/legend.html. Thank you in advance.

答:
The yAxis.ticks labels can be left aligned by defining mirror: true combined with adding some padding.

```<code>yAxes: [{
  ticks: {
    mirror: true,
    padding: 220
  },
</code>```

To make the labels visible on the chart area, the same padding needs to be defined left of the chart layout.

```<code>layout: {
  padding: {
    left: 220
  }
},
</code>```

Please have a look at your changed code below.

new Chart('myChart', {
  type: 'horizontalBar',
  data: {
    labels: ["Total", "301 Redirect", "Broken Pages (4xx Errors)", "Uncategorised HTTP Response Codes", "5xx Errors", "Unauthorised Pages", "Non-301 Redirects"],
    datasets: [{
      data: [16, 14, 1, 1, 0, 0, 0],
      backgroundColor: ['rgba(237, 56, 98, 1.0)', 'rgba(237, 56, 98, 1.0)', 'rgba(237, 56, 98, 1.0)', 'rgba(237, 56, 98, 1.0)', 'rgba(237, 56, 98, 1.0)', 'rgba(237, 56, 98, 1.0)','rgba(237, 56, 98, 1.0)']
    }]
  },
  options: {
    responsive: false,
    layout: {
      padding: {
        left: 220
      }
    },
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          mirror: true,
          padding: 220
        },
        gridLines: {
          display: false
        },
      }],
      xAxes: [{
        ticks: {
          display: false
        },
        gridLines: {
          drawBorder: false,
        }
      }],
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" width="500" height="200"></canvas></code>```

Body:
My code using chart.js

var ctx_1 = document.getElementById('non_200_pages').getContext('2d');
var myChart_1 = new Chart(ctx_1, {
type: 'horizontalBar',
data: {
    labels: ["Total","301 Redirect","Broken Pages (4xx Errors)","Uncategorised HTTP Response Codes","5xx Errors","Unauthorised Pages","Non-301 Redirects"],
    datasets: [{

        data: [ {{ $array_non_200_pages[0] }}, {{ $array_non_200_pages[1] }}, {{ $array_non_200_pages[2] }}, {{ $array_non_200_pages[3] }}, {{ $array_non_200_pages[4] }}, {{ $array_non_200_pages[5] }}, {{ $array_non_200_pages[6]}} ],
        backgroundColor: [
            'rgba(237, 56, 98, 1.0)',
            'rgba(237, 56, 98, 1.0)',
            'rgba(237, 56, 98, 1.0)',
            'rgba(237, 56, 98, 1.0)',
            'rgba(237, 56, 98, 1.0)',
            'rgba(237, 56, 98, 1.0)',
            'rgba(237, 56, 98, 1.0)'
        ]

    }]
},
options: {
    showAllTooltips: true,
    tooltips: {
          enabled: true,
          displayColors: false,
          yPadding: 20,
          xPadding: 30,
          caretSize: 10,
          backgroundColor: 'rgba(240, 240, 240, 1)',
          bodyFontSize: 16,
          bodyFontColor: 'rgb(50, 50, 50)',
          borderColor: 'rgba(0,0,0,1)',
          borderWidth: 1,
          cornerRadius: 0,
          yAlign: 'bottom',
          xAlign: 'center',
          position: 'custom',
          custom: function(tooltip) {
            if (!tooltip) return;
            // disable displaying the color box;
            tooltip.displayColors = false;
          },
          callbacks: {
            // use label callback to return the desired label
            label: function(tooltipItem, data) {
              return tooltipItem.yLabel + " : " + tooltipItem.xLabel ;
            },
            // remove title
            title: function(tooltipItem, data) {
              return;
            }
        }
    },
    responsive: false,
    legend: { display: false },
    scales: {
        yAxes: [{
            ticks: {
                beginAtZero: true,
            },
            gridLines: {
                display: false
            },
        }],
        xAxes: [{
            ticks: {
                stepSize:5,
                display: false
            },
            gridLines: {
                drawBorder: false,
            }
        }],
    },
    plugins: {
        datalabels: {
    align: 'end',
    anchor: 'end',
    backgroundColor: function(context) {
      return context.dataset.backgroundColor;
    },
    borderRadius: 4,
    color: 'white',
    formatter: Math.round
  }
}
}
});

My work

Expected Output

I'm having a problem on how to set the labels text align to left. What I want to do is I want my label same with the next picture but I don't know where in Options:{ settings for text align. Is there anyone can help me how to fix it? I can't find any on the  https://www.chartjs.org/docs/latest/configuration/legend.html. Thank you in advance.

Body:
The yAxis.ticks labels can be left aligned by defining mirror: true combined with adding some padding.

yAxes: [{
  ticks: {
    mirror: true,
    padding: 220
  },

To make the labels visible on the chart area, the same padding needs to be defined left of the chart layout.

layout: {
  padding: {
    left: 220
  }
},

Please have a look at your changed code below.

new Chart('myChart', {
  type: 'horizontalBar',
  data: {
    labels: ["Total", "301 Redirect", "Broken Pages (4xx Errors)", "Uncategorised HTTP Response Codes", "5xx Errors", "Unauthorised Pages", "Non-301 Redirects"],
    datasets: [{
      data: [16, 14, 1, 1, 0, 0, 0],
      backgroundColor: ['rgba(237, 56, 98, 1.0)', 'rgba(237, 56, 98, 1.0)', 'rgba(237, 56, 98, 1.0)', 'rgba(237, 56, 98, 1.0)', 'rgba(237, 56, 98, 1.0)', 'rgba(237, 56, 98, 1.0)','rgba(237, 56, 98, 1.0)']
    }]
  },
  options: {
    responsive: false,
    layout: {
      padding: {
        left: 220
      }
    },
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          mirror: true,
          padding: 220
        },
        gridLines: {
          display: false
        },
      }],
      xAxes: [{
        ticks: {
          display: false
        },
        gridLines: {
          drawBorder: false,
        }
      }],
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" width="500" height="200"></canvas>


问:
Asp.Net client certificate authentication problem after chrome update 83.0.4103.61
In my website, I use client certificate authentication. But when update chrome I have problem with authenticate. In my code when a user enters I check Request.ClientCertificate.Count > 0 condition. Before the update, this get count of the certificate, but after update Request.ClientCertificate.Count code return zero. What is the reason for this?

答: Finally, we found the problem. We update our Windows server then the problem solved.</p>


问:
Bridging Knime, Keras and DL4J – Exceptions when loading h5 model
I’m working on a project which needs to train a DNN and then run the trained model in a Java environment. As the training data requires a lot of manipulation I’ve used Knime and its Keras libraries to do most of the work, and I’m exported the trained model to a Keras h5 file which can be loaded into DL4J (I’m using Knime Keras Integration 4.1.0v201911171432 and DL4J 1.0.0-beta6).

The modelling is ongoing, but for a POC I’ve created a network by chaining the following nodes:

Keras Input Layer (shape 144)

Keras Dense Layer (units 500)

Keras Dense Layer (units 500)

Keras Dense Layer (units 1)

Keras Set Output Layers (single output shape [1] pointing to the last layer)

This then gets trained and outputted with a “Keras Network Writer” node which writes a .h5 file.

In Java I have includes the following dependencies:

```<code> <dependency>
      <groupId>org.deeplearning4j</groupId>
      <artifactId>deeplearning4j-core</artifactId>
      <version>1.0.0-beta6</version>
    </dependency>
    <dependency>
      <groupId>org.nd4j</groupId>
      <artifactId>nd4j-native-platform</artifactId>
      <version>1.0.0-beta6</version>
    </dependency>
</code>```

And run the following code:

```<code>import org.deeplearning4j.nn.modelimport.keras.KerasModelImport;
…
ComputationGraph model = KerasModelImport.importKerasModelAndWeights("2x2x2keras.h5");
</code>```

Which returns the following exception

```<code>java.lang.IllegalStateException: Invalid configuration: network has no outputs. Use .setOutput(String...) to specify (and give an ordering to) the output vertices, or use allowNoOutputs(true) to disable this check
    at org.deeplearning4j.nn.conf.ComputationGraphConfiguration.validate(ComputationGraphConfiguration.java:375) ~[deeplearning4j-nn-1.0.0-beta6.jar:na]
    at org.deeplearning4j.nn.conf.ComputationGraphConfiguration$GraphBuilder.build(ComputationGraphConfiguration.java:1197) ~[deeplearning4j-nn-1.0.0-beta6.jar:na]
    at org.deeplearning4j.nn.modelimport.keras.KerasModel.getComputationGraphConfiguration(KerasModel.java:394) ~[deeplearning4j-modelimport-1.0.0-beta6.jar:na]
    at org.deeplearning4j.nn.modelimport.keras.KerasModel.getComputationGraph(KerasModel.java:415) ~[deeplearning4j-modelimport-1.0.0-beta6.jar:na]
    at org.deeplearning4j.nn.modelimport.keras.KerasModel.getComputationGraph(KerasModel.java:404) ~[deeplearning4j-modelimport-1.0.0-beta6.jar:na]
    at org.deeplearning4j.nn.modelimport.keras.KerasModelImport.importKerasModelAndWeights(KerasModelImport.java:173) ~[deeplearning4j-modelimport-1.0.0-beta6.jar:na]
    at dev.aisandbox.tftest.TFRunner.run(TFRunner.java:18) ~[classes/:na]
</code>```

As this is the first time I’ve tried using Knime to manage my dataflow, I can’t be certain if the issues is with the file (being created in Knime) or the code loading it (into DL4J+Java). I’m assuming the comment about setOutput is intended for when you are creating the network with a python script, but can’t see anyway to set allowNoOutputs when KerasModelImport only has static methods.

答:
You can try use Deep Java Library. Here is document about how to load Keras model into DJL.

And you can find example project here.

Body:
I’m working on a project which needs to train a DNN and then run the trained model in a Java environment. As the training data requires a lot of manipulation I’ve used Knime and its Keras libraries to do most of the work, and I’m exported the trained model to a Keras h5 file which can be loaded into DL4J (I’m using Knime Keras Integration 4.1.0v201911171432 and DL4J 1.0.0-beta6).

The modelling is ongoing, but for a POC I’ve created a network by chaining the following nodes:

Keras Input Layer (shape 144)

Keras Dense Layer (units 500)

Keras Dense Layer (units 500)

Keras Dense Layer (units 1)

Keras Set Output Layers (single output shape [1] pointing to the last layer)

This then gets trained and outputted with a “Keras Network Writer” node which writes a .h5 file.

In Java I have includes the following dependencies:

 <dependency>
      <groupId>org.deeplearning4j</groupId>
      <artifactId>deeplearning4j-core</artifactId>
      <version>1.0.0-beta6</version>
    </dependency>
    <dependency>
      <groupId>org.nd4j</groupId>
      <artifactId>nd4j-native-platform</artifactId>
      <version>1.0.0-beta6</version>
    </dependency>

And run the following code:

import org.deeplearning4j.nn.modelimport.keras.KerasModelImport;
…
ComputationGraph model = KerasModelImport.importKerasModelAndWeights("2x2x2keras.h5");

Which returns the following exception

java.lang.IllegalStateException: Invalid configuration: network has no outputs. Use .setOutput(String...) to specify (and give an ordering to) the output vertices, or use allowNoOutputs(true) to disable this check
    at org.deeplearning4j.nn.conf.ComputationGraphConfiguration.validate(ComputationGraphConfiguration.java:375) ~[deeplearning4j-nn-1.0.0-beta6.jar:na]
    at org.deeplearning4j.nn.conf.ComputationGraphConfiguration$GraphBuilder.build(ComputationGraphConfiguration.java:1197) ~[deeplearning4j-nn-1.0.0-beta6.jar:na]
    at org.deeplearning4j.nn.modelimport.keras.KerasModel.getComputationGraphConfiguration(KerasModel.java:394) ~[deeplearning4j-modelimport-1.0.0-beta6.jar:na]
    at org.deeplearning4j.nn.modelimport.keras.KerasModel.getComputationGraph(KerasModel.java:415) ~[deeplearning4j-modelimport-1.0.0-beta6.jar:na]
    at org.deeplearning4j.nn.modelimport.keras.KerasModel.getComputationGraph(KerasModel.java:404) ~[deeplearning4j-modelimport-1.0.0-beta6.jar:na]
    at org.deeplearning4j.nn.modelimport.keras.KerasModelImport.importKerasModelAndWeights(KerasModelImport.java:173) ~[deeplearning4j-modelimport-1.0.0-beta6.jar:na]
    at dev.aisandbox.tftest.TFRunner.run(TFRunner.java:18) ~[classes/:na]

As this is the first time I’ve tried using Knime to manage my dataflow, I can’t be certain if the issues is with the file (being created in Knime) or the code loading it (into DL4J+Java). I’m assuming the comment about setOutput is intended for when you are creating the network with a python script, but can’t see anyway to set allowNoOutputs when KerasModelImport only has static methods.


问:
Using the passwd command from within a shell script
I'm writing a shell script to automatically add a new user and update their password. I don't know how to get passwd to read from the shell script instead of interactively prompting me for the new password. My code is below.</p>

```adduser $1
passwd $1
$2
$2```

答:
Here-document works if your passwd doesn't support --stdin and you don't want to (or can't) use chpasswd for some reason.

Example:

#!/usr/bin/env bash

username="user"
password="pass"

passwd ${username} << EOD
${password}
${password}
EOD
```

Tested under Arch Linux. This passwd is an element of shadow-utils and installed from the core/filesystem package, which you usually have by default since the package is required by core/base.

OwnerDisplayName: Jared

Body:
I'm writing a shell script to automatically add a new user and update their password. I don't know how to get passwd to read from the shell script instead of interactively prompting me for the new password. My code is below.

adduser $1
passwd $1
$2
$2

LastEditorDisplayName: Adam Lassek

Body:
Here-document works if your passwd doesn't support --stdin and you don't want to (or can't) use chpasswd for some reason.

Example:

#!/usr/bin/env bash

username="user"
password="pass"

passwd ${username} << EOD
${password}
${password}
EOD

Tested under Arch Linux. This passwd is an element of shadow-utils and installed from the core/filesystem package, which you usually have by default since the package is required by core/base.


问:
Highlight a specific part of the text in SwiftUI
Hello I'm new to Swift and am using SwiftUI for my project where I download some weather data and I display it in the ContentView().

I would like to highlight some part of the Text if it contains some specific word, but I don't have any idea how to start.

In ContentView(), I have tried to set a function receiving the string downloaded from web and return a string. I believe this is wrong, because SwiftUI does not apply the modifiers at the all for the Text.

For example, in my ContentView() I would like the word thunderstorm to have the .bold() modifier:

```<code>struct ContentView: View {
  let testo : String = "There is a thunderstorm in the area"

  var body: some View {
    Text(highlight(str: testo))
  }

  func highlight(str: String) -> String {
    let textToSearch = "thunderstorm"
    var result = ""

    if str.contains(textToSearch) {
      let index = str.startIndex
      result = String( str[index])
    }

    return result
  }

}
</code>```

答:
You can concatenate with multiple Text Views.</p>

```<code>import SwiftUI
import PlaygroundSupport

struct ContentView: View {
  var body: some View{
    let testo : String = "There is a thunderstorm in the area"
    let stringArray = testo.components(separatedBy: " ")
    let stringToTextView = stringArray.reduce(Text(""), {
      if $1 == "thunderstorm" {
        return $0 + Text($1).bold() + Text(" ")
      } else {
        return $0 + Text($1) + Text(" ")
      }

    })
    return stringToTextView
  }
}

PlaygroundPage.current.setLiveView(ContentView())

</code>```

Body:
Hello I'm new to Swift and am using SwiftUI for my project where I download some weather data and I display it in the ContentView().

I would like to highlight some part of the Text if it contains some specific word, but I don't have any idea how to start.

In ContentView(), I have tried to set a function receiving the string downloaded from web and return a string. I believe this is wrong, because SwiftUI does not apply the modifiers at the all for the Text.

For example, in my ContentView() I would like the word thunderstorm to have the .bold() modifier:

struct ContentView: View {
  let testo : String = "There is a thunderstorm in the area"

  var body: some View {
    Text(highlight(str: testo))
  }

  func highlight(str: String) -> String {
    let textToSearch = "thunderstorm"
    var result = ""

    if str.contains(textToSearch) {
      let index = str.startIndex
      result = String( str[index])
    }

    return result
  }

}

Body:
You can concatenate with multiple Text Views.

import SwiftUI
import PlaygroundSupport

struct ContentView: View {
  var body: some View{
    let testo : String = "There is a thunderstorm in the area"
    let stringArray = testo.components(separatedBy: " ")
    let stringToTextView = stringArray.reduce(Text(""), {
      if $1 == "thunderstorm" {
        return $0 + Text($1).bold() + Text(" ")
      } else {
        return $0 + Text($1) + Text(" ")
      }

    })
    return stringToTextView
  }
}

PlaygroundPage.current.setLiveView(ContentView())


问:
Why the if condition is always false?
I was doing some java coding exercises and this add 2 binary number exercise.
I am not sure why the if condition is always false, even if I put actual int into the variable.

whats the problem???

```<code>public class Main {
    public static void main(String[]args){
        long bin1 = 10, bin2 = 101;
        int carry = 0, i = 0;

        int bin1Length = String.valueOf(bin1).length();
        int bin2Length = String.valueOf(bin2).length();
        int length;

        System.out.println("bin1: " + bin1Length);
        System.out.println("bin2: " + bin2Length);

        if(bin1Length > bin2Length){     // not sure why its always false in all 3 conditions
            length = bin1Length;
        } else if (bin2Length < bin1Length){
            length = bin2Length;
        } else if (bin1Length == bin2Length){
            length = bin1Length;
        }

        int [] finalOutput = new int [length];

        while(bin1 != 0 || bin2 != 0){
            finalOutput[i++] = (int)(carry + (bin1 % 10 + bin2 % 10) % 2);
            carry = (int)((carry + bin1 % 10 + bin2 % 10)/2);
            bin1 = bin1/10;
            bin2 = bin2/10;
        }

        if(carry != 0){
            finalOutput[i] = carry;
        }

        System.out.print("Output: ");

        while(i >= 0){
            System.out.print(finalOutput[i--]);
        }
    }
}
</code>```

edit: and this is the error.

Thanks.

答:
your first if condition and the following else if are the same.

have a better look on this:

```<code>    if(bin1Length > bin2Length){
        length = bin1Length;
    } else if (bin2Length < bin1Length){
        length = bin2Length;
    }
</code>```

if bin1Length won't be greater than bin2Length, of course bin2Length is not smaller than bin1Length.

change it to this:

```<code>    if(bin1Length > bin2Length){
        length = bin1Length;
    } else if (bin1Length < bin2Length){
        length = bin2Length;
    } else if (bin1Length == bin2Length){
        length = bin1Length;
    }
</code>```

Title: Why the if condition is always false?

Body:
I was doing some java coding exercises and this add 2 binary number exercise.
I am not sure why the if condition is always false, even if I put actual int into the variable.

whats the problem???

public class Main {
    public static void main(String[]args){
        long bin1 = 10, bin2 = 101;
        int carry = 0, i = 0;

        int bin1Length = String.valueOf(bin1).length();
        int bin2Length = String.valueOf(bin2).length();
        int length;

        System.out.println("bin1: " + bin1Length);
        System.out.println("bin2: " + bin2Length);

        if(bin1Length > bin2Length){     // not sure why its always false in all 3 conditions
            length = bin1Length;
        } else if (bin2Length < bin1Length){
            length = bin2Length;
        } else if (bin1Length == bin2Length){
            length = bin1Length;
        }

        int [] finalOutput = new int [length];

        while(bin1 != 0 || bin2 != 0){
            finalOutput[i++] = (int)(carry + (bin1 % 10 + bin2 % 10) % 2);
            carry = (int)((carry + bin1 % 10 + bin2 % 10)/2);
            bin1 = bin1/10;
            bin2 = bin2/10;
        }

        if(carry != 0){
            finalOutput[i] = carry;
        }

        System.out.print("Output: ");

        while(i >= 0){
            System.out.print(finalOutput[i--]);
        }
    }
}

edit: and this is the error.

Thanks.

Body:
your first if condition and the following else if are the same.

have a better look on this:

    if(bin1Length > bin2Length){
        length = bin1Length;
    } else if (bin2Length < bin1Length){
        length = bin2Length;
    }

if bin1Length won't be greater than bin2Length, of course bin2Length is not smaller than bin1Length.

change it to this:

    if(bin1Length > bin2Length){
        length = bin1Length;
    } else if (bin1Length < bin2Length){
        length = bin2Length;
    } else if (bin1Length == bin2Length){
        length = bin1Length;
    }