问:
How to store jwt in cookie and pass it to authentication function when redirecting a page?
I have a node.js express backend built with Postman and tested with Jest. I wrote a front end with hbs and the next step is to stitch them. However I still keep getting "please authenticate" error message that's from my auth function, which I guess is because I'm not successfully passing my jwt token.

So on login page (users/login) I want to login with email and password then I want to redirect to me page(users/me) where I can perform other stuff that belongs to this user.

Front-end
login page code:

```<code><section class="login-bg">
        <div class="login-form">
            <p>Welcome to Task Manager, please log in!</p>
            <form class="input-group" action="/users/login" method="POST">
                <label>Email:</label>
                <input type="email" name="email" placeholder="type your email" value="{{user.email}}" required >
                <label>Password:</label>
                <input type="password" name="password" placeholder="type your password" value="{{user.password}}" required>

                <button class="button" type="submit">Log In</button>
            </form>
        </div>
    </section>
</code>```

Back-end

in middleware/auth.js

```<code>const jwt = require('jsonwebtoken')
const User = require('../models/user')

const auth = async (req, res, next) => {
    try {
        const token = req.header('Authorization').replace('Bearer ', '')
        const decoded = jwt.verify(token, process.env.JWT_SECRET)
        const user = await User.findOne({_id: decoded._id, 'tokens.token': token})

        if (!user) {
            throw new Error()
        }

        req.token = token
        req.user = user
        next()

    } catch (error) {
        res.status(401).send({error: 'Please authenticate.'})
    }
}

module.exports = auth
</code>```

in src/routers/users.js

```<code>router.post('/login', async (req, res) => {
    try {
        const user = await User.findByCredentials(req.body.email, req.body.password)
        const token = await user.generateAuthToken()
        res.cookie('jwt',token, { httpOnly: true, secure: true, maxAge: 3600000 })
        res.redirect('/users/me')
    } catch (error) {
        res.status(400).send()
    }
})
</code>```

However, when I do console.log(document.cookie) in users/me it says undefined.

Then I have the cookie-parser installed and import to app.js, and try to write this part in src/routers/users.js:

```<code>router.get('/me', auth, async (req, res) => {
    console.log('Cookies: ', req.cookies)
    try {
        res.render('me', {name: user.name})
    } catch (error) {
        res.status(500).send()
    }
})
</code>```

but this console doesn't print anything, probably cos I am getting error from auth.

I also have a a js file attached to me page but I have no clue if I could write this way, probably wrong:

```<code>const userToken = document.cookie.jwt.token

fetch('/users/me', {
    method: 'POST',
    headers: {
     'Authorization': 'Bearer ' + userToken
    }
})
.then(res => res.json())
.then(data => { console.log(data) })
.catch(err => { console.log(err) })
</code>```

then in the Network / Headers, I have

Request URL:

http://localhost:3000/users/login

Request Method:

POST

Status Code:

302 Found

Remote Address:

Referrer Policy:

no-referrer-when-downgrade

Response Headers

Connection:

keep-alive

Content-Length:

62

Content-Type:

text/html; charset=utf-8

Date:

Fri, 07 Jun 2019 18:41:47 GMT

Location:

/users/me

Set-Cookie:

jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1Y2Y2NjNlMTQwMTQyYjE0MzhmZTJjNDMiLCJpYXQiOjE1NTk5MzI5MDd9.T_P8O-j98cs9gtahTzspJjx1qNMSe3M5OAySyeH25fs; Max-Age=3600; Path=/; Expires=Fri, 07 Jun 2019 19:41:47 GMT; HttpOnly; Secure

Vary:

Accept

X-Powered-By:

Express

There is no request cookies, only response cookies. I am not sure what those means...@_@

I want to pass the jwt to successfully login and render the me page properly, how could I do that?

答:
Make sure you have installed cookie-parser in your server.

Run:

```<code>npm i cookie-parser
</code>```

Body:
I have a node.js express backend built with Postman and tested with Jest. I wrote a front end with hbs and the next step is to stitch them. However I still keep getting "please authenticate" error message that's from my auth function, which I guess is because I'm not successfully passing my jwt token.

So on login page (users/login) I want to login with email and password then I want to redirect to me page(users/me) where I can perform other stuff that belongs to this user.

Front-end
login page code:

Welcome to Task Manager, please log in!

            <form class="input-group" action="/users/login" method="POST">
                Email:
                <input type="email" name="email" placeholder="type your email" value="{{user.email}}" required >
                Password:
                <input type="password" name="password" placeholder="type your password" value="{{user.password}}" required>

                <button class="button" type="submit">Log In</button>
            </form>

Back-end

in middleware/auth.js

const jwt = require('jsonwebtoken')
const User = require('../models/user')

const auth = async (req, res, next) => {
    try {
        const token = req.header('Authorization').replace('Bearer ', '')
        const decoded = jwt.verify(token, process.env.JWT_SECRET)
        const user = await User.findOne({_id: decoded._id, 'tokens.token': token})

        if (!user) {
            throw new Error()
        }

        req.token = token
        req.user = user
        next()

    } catch (error) {
        res.status(401).send({error: 'Please authenticate.'})
    }
}

module.exports = auth

in src/routers/users.js

router.post('/login', async (req, res) => {
    try {
        const user = await User.findByCredentials(req.body.email, req.body.password)
        const token = await user.generateAuthToken()
        res.cookie('jwt',token, { httpOnly: true, secure: true, maxAge: 3600000 })
        res.redirect('/users/me')
    } catch (error) {
        res.status(400).send()
    }
})

However, when I do console.log(document.cookie) in users/me it says undefined.

Then I have the cookie-parser installed and import to app.js, and try to write this part in src/routers/users.js:

router.get('/me', auth, async (req, res) => {
    console.log('Cookies: ', req.cookies)
    try {
        res.render('me', {name: user.name})
    } catch (error) {
        res.status(500).send()
    }
})

but this console doesn't print anything, probably cos I am getting error from auth.

I also have a a js file attached to me page but I have no clue if I could write this way, probably wrong:

const userToken = document.cookie.jwt.token

fetch('/users/me', {
    method: 'POST',
    headers: {
     'Authorization': 'Bearer ' + userToken
    }
})
.then(res => res.json())
.then(data => { console.log(data) })
.catch(err => { console.log(err) })

then in the Network / Headers, I have

Request URL:

http://localhost:3000/users/login

Request Method:

POST

Status Code:

302 Found

Remote Address:

Referrer Policy:

no-referrer-when-downgrade

Response Headers

Connection:

keep-alive

Content-Length:

62

Content-Type:

text/html; charset=utf-8

Date:

Fri, 07 Jun 2019 18:41:47 GMT

Location:

/users/me

Set-Cookie:

jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1Y2Y2NjNlMTQwMTQyYjE0MzhmZTJjNDMiLCJpYXQiOjE1NTk5MzI5MDd9.T_P8O-j98cs9gtahTzspJjx1qNMSe3M5OAySyeH25fs; Max-Age=3600; Path=/; Expires=Fri, 07 Jun 2019 19:41:47 GMT; HttpOnly; Secure

Vary:

Accept

X-Powered-By:

Express

There is no request cookies, only response cookies. I am not sure what those means...@_@

I want to pass the jwt to successfully login and render the me page properly, how could I do that?

Body:
Make sure you have installed cookie-parser in your server.

Run:

npm i cookie-parser


来源: stackexchange

问:
Get main content in a page while web scraping node js, Puppeteer, Cheerio
I have a Project with Node JS on web scraping where I will have to scrape Heading and Text from Main Content. But the Problem is I'm not able to Determine which is Main Content When there is No aside or main tag or class/id/role named aside or main. I'm Using Puppeteer and Cheerio Library. I have Tried using Mercury Web Parser But it has its Own problems. Like It doesn't return any content from Pages that Built with Elementor Theme builder on Wordpress. If anyone have any idea on how can I differentiate main content from rest of the web page it will be really helpful.

答: You can checkout Readability JS library from Mozilla. They use for reader view.</p>

ContentLicense: CC BY-SA 4.0


问:
Xamarin listview change color
How do change the color of the specific item in the listview?
Ex( a listview of user that has status of active and inactive)

The active item background or border color will be set to green and inactive as red.

答:
You should take a look at the 'VisualStateManager':
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/visual-state-manager</p>

Title: Xamarin listview change color


问:
OpenFileDialog with WPF in M-V-VM pattern
I need to use the OpenFileDialog to select a file, but I can't use any of the MVVM-centric toolkits like Galgasoft that allow me to do this without violating the MVVM pattern.

How else can I achieve this?

答:
Sure, here's an example of some code I use to read Excel files. It goes in a ViewModel and gets called from a SelectFileCommand

```<code>private void SelectFile()
{
    var dlg = new OpenFileDialog();
    dlg.DefaultExt = ".xls|.xlsx";
    dlg.Filter = "Excel documents (*.xls, *.xlsx)|*.xls;*.xlsx";

    if (dlg.ShowDialog() == true)
    {
        var file = new FileInfo(dlg.FileName);
        ReadExcelFile(file.FullName);
    }
}

private void ReadExcelFile(fileName)
{
    try
    {
        using (var conn = new OleDbConnection(string.Format(@"Provider=Microsoft.Ace.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", fileName)))
        {
            OleDbDataAdapter da = new OleDbDataAdapter("SELECT DISTINCT [File Number] FROM [Sheet1$]", conn);
            var dt = new DataTable();
            da.Fill(dt);

            int i;
            FileContents = (from row in dt.AsEnumerable()
                            where int.TryParse(row[0].ToString(), out i)
                            select row[0]).ToList()
                            .ConvertAll<int>(p => int.Parse(p.ToString()));
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Unable to read contents:\n\n" + ex.Message, "Error");
    }
}
</code>```

You need to reference Microsoft.Win32 for the OpenFileDialog

ContentLicense: CC BY-SA 3.0

Body:
Sure, here's an example of some code I use to read Excel files. It goes in a ViewModel and gets called from a SelectFileCommand

private void SelectFile()
{
    var dlg = new OpenFileDialog();
    dlg.DefaultExt = ".xls|.xlsx";
    dlg.Filter = "Excel documents (*.xls, *.xlsx)|*.xls;*.xlsx";

    if (dlg.ShowDialog() == true)
    {
        var file = new FileInfo(dlg.FileName);
        ReadExcelFile(file.FullName);
    }
}

private void ReadExcelFile(fileName)
{
    try
    {
        using (var conn = new OleDbConnection(string.Format(@"Provider=Microsoft.Ace.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", fileName)))
        {
            OleDbDataAdapter da = new OleDbDataAdapter("SELECT DISTINCT [File Number] FROM [Sheet1$]", conn);
            var dt = new DataTable();
            da.Fill(dt);

            int i;
            FileContents = (from row in dt.AsEnumerable()
                            where int.TryParse(row[0].ToString(), out i)
                            select row[0]).ToList()
                            .ConvertAll<int>(p => int.Parse(p.ToString()));
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Unable to read contents:\n\n" + ex.Message, "Error");
    }
}

You need to reference Microsoft.Win32 for the OpenFileDialog


问:
Double multiplication with brackets problem
```<code>double celsius_0 = (100.5 - 32) * (5 / 9);
double celsius_1 = (100.5- 32) * 5 / 9;

Console.WriteLine(celsius_0);
Console.WriteLine(celsius_1);

output:
0
38,0555555555556
</code>```

Why do they return differnt values?
I dont understand whats happening

答:
It's because here celsius_0 = (100.5 - 32) * (5 / 9)
you count value in the first bracket then in the second one and then you multiply them.

While in the second line (100.5- 32) * 5 / 9 you count value in bracket then multiply it by 5 and at the end divide it by 9

To sum up in mathematics first you do things in brackets and then multiply/divide and finally add/substract

Body:
double celsius_0 = (100.5 - 32) * (5 / 9);
double celsius_1 = (100.5- 32) * 5 / 9;

Console.WriteLine(celsius_0);
Console.WriteLine(celsius_1);

output:
0
38,0555555555556

Why do they return differnt values?
I dont understand whats happening


问:
Count the amount of array-childs / items in received nested array in angular, rxjs
I would like to count the amount of array items from a nested array.

I have done this successfully in a not so deeply nested array, and I am curious how I can create a similar outcome with a one level deeper example.

This is how the well-working one goes:

```<code>  const listId = this.route.snapshot.paramMap.get('listId');
  this.listService.getShortlist(listId)
    .subscribe(list =>
      {this.list = list;
      this.showEditlink = this.list.sublistCreators.find(element => element === this.username);
      this.itemcount = this.list.shortlistItem.length;
      });
}
</code>```

The itemcount is what I am looking for. This is usable in my template.

Now, another similar component has the length/count one level deeper, this was my attempt at gaining the array-item-count:

```<code>getList(): void {
const listId = this.route.snapshot.paramMap.get('listId');
console.log("het list-id = " + listId);
this.listService.getListNo404(listId)
  .subscribe((list =>
    {this.list = list;
    this.itemcount = this.list.sublist.item.length;
  })
  )
  }
</code>```

Also tried this (among a lot more):

```<code>   getList(): void {
const listId = this.route.snapshot.paramMap.get('listId');
console.log("het list-id = " + listId);
this.listService.getListNo404(listId)
  .subscribe((list =>
    {this.list = list;
    this.sublist = this.list.sublist
    this.itemcount = this.sublist.item.length;
  })
  )
  }
</code>```

Here I added the this.sublist = this.list.sublist in between. However not able to get this one working.

Can you help me to count the amount of array-items inside 'item'?

Maybe useful to add, below the json I receive from my backend:

In this particular example the outcomes should be 4 and 3.

```<code>{
  "_id": {
    "$oid": "dummy"
  },
  "listTitle": "dummy",
  "listCreator": "dummy",
  "sublist": [
    {
      "subListCreator": "dummy",
      "subListAdded": {
        "$date": dummy
      },
      "item": [
        {
          "positionId": 1,
          "itemScore": 3,
          "itemTitle": "dummy",
          "itemContext": "dummy"
        },
        {
          "positionId": 2,
          "itemScore": 2,
          "itemTitle": "dummy",
          "itemContext": "dummy"
        },
        {
          "positionId": 3,
          "itemScore": 1,
          "itemTitle": "dummy",
          "itemContext": "dummy"
        },
        {
          "positionId": 4,
          "itemScore": 1,
          "itemTitle": "dummy",
          "itemContext": "dummy"
        }
      ]
    },
    {
      "subListCreator": "dummy",
      "subListAdded": {
        "$date": dummy
      },
      "item": [
        {
          "positionId": 1,
          "itemScore": 3,
          "itemTitle": "dummy"
        },
        {
          "positionId": 2,
          "itemScore": 2,
          "itemTitle": "dummy",
          "itemContext": "dummy"
        },
        {
          "positionId": 3,
          "itemScore": 1,
          "itemTitle": "dummy"
        }
      ]
    }
  ]
}
</code>```

Thanks a lot for having a look!

答:
If I understand the problem right, this is something about json and arrays, not about rxjs.

Anyways, again if the understanding is right, the following could be an option.

Let's assume that the myJson constant holds the the json you are providing as example, i.e.

```<code>const myJson = {
  "_id": {
    "$oid": "dummy"
  },
.....
}
</code>```

then a solution could look like this

```<code>const subList = myJson.sublist;
const itemList = subList.map((listEl) => listEl.item);
const result = itemList.map((items) => items.length);
</code>```

What you end up in having in result is an array [4, 3] which is the expected result.

Here a stackblitz example.

Body:
I would like to count the amount of array items from a nested array.

I have done this successfully in a not so deeply nested array, and I am curious how I can create a similar outcome with a one level deeper example.

This is how the well-working one goes:

  const listId = this.route.snapshot.paramMap.get('listId');
  this.listService.getShortlist(listId)
    .subscribe(list =>
      {this.list = list;
      this.showEditlink = this.list.sublistCreators.find(element => element === this.username);
      this.itemcount = this.list.shortlistItem.length;
      });
}

The itemcount is what I am looking for. This is usable in my template.

Now, another similar component has the length/count one level deeper, this was my attempt at gaining the array-item-count:

getList(): void {
const listId = this.route.snapshot.paramMap.get('listId');
console.log("het list-id = " + listId);
this.listService.getListNo404(listId)
  .subscribe((list =>
    {this.list = list;
    this.itemcount = this.list.sublist.item.length;
  })
  )
  }

Also tried this (among a lot more):

   getList(): void {
const listId = this.route.snapshot.paramMap.get('listId');
console.log("het list-id = " + listId);
this.listService.getListNo404(listId)
  .subscribe((list =>
    {this.list = list;
    this.sublist = this.list.sublist
    this.itemcount = this.sublist.item.length;
  })
  )
  }

Here I added the this.sublist = this.list.sublist in between. However not able to get this one working.

Can you help me to count the amount of array-items inside 'item'?

Maybe useful to add, below the json I receive from my backend:

In this particular example the outcomes should be 4 and 3.

{
  "_id": {
    "$oid": "dummy"
  },
  "listTitle": "dummy",
  "listCreator": "dummy",
  "sublist": [
    {
      "subListCreator": "dummy",
      "subListAdded": {
        "$date": dummy
      },
      "item": [
        {
          "positionId": 1,
          "itemScore": 3,
          "itemTitle": "dummy",
          "itemContext": "dummy"
        },
        {
          "positionId": 2,
          "itemScore": 2,
          "itemTitle": "dummy",
          "itemContext": "dummy"
        },
        {
          "positionId": 3,
          "itemScore": 1,
          "itemTitle": "dummy",
          "itemContext": "dummy"
        },
        {
          "positionId": 4,
          "itemScore": 1,
          "itemTitle": "dummy",
          "itemContext": "dummy"
        }
      ]
    },
    {
      "subListCreator": "dummy",
      "subListAdded": {
        "$date": dummy
      },
      "item": [
        {
          "positionId": 1,
          "itemScore": 3,
          "itemTitle": "dummy"
        },
        {
          "positionId": 2,
          "itemScore": 2,
          "itemTitle": "dummy",
          "itemContext": "dummy"
        },
        {
          "positionId": 3,
          "itemScore": 1,
          "itemTitle": "dummy"
        }
      ]
    }
  ]
}

Thanks a lot for having a look!

Body:
If I understand the problem right, this is something about json and arrays, not about rxjs.

Anyways, again if the understanding is right, the following could be an option.

Let's assume that the myJson constant holds the the json you are providing as example, i.e.

const myJson = {
  "_id": {
    "$oid": "dummy"
  },
.....
}

then a solution could look like this

const subList = myJson.sublist;
const itemList = subList.map((listEl) => listEl.item);
const result = itemList.map((items) => items.length);

What you end up in having in result is an array [4, 3] which is the expected result.

Here a stackblitz example.


问:
Vue transition animation with router-view only works for the first transition
I want to make transitions between my navbar elements, so i'm using router-links. The transition works fine for the /about section, but for the others it completely stops working. If i'm on /something and return to /about, the transitions also works, but for other routes it doesn't.

Any advice of what i can do?

App.vue

<template>

    <Navbar/>

      <router-link to="/about"/>
      <router-link to="/experience"/>
      <router-link to="/education"/>
      <router-link to="/contact"/>

    <Transition name="slide-fade" mode="out-in">
      <router-view/>
    </Transition>

</template>

```
<blockquote>
<p>router.js</p>
</blockquote>
<pre class="lang-js prettyprint-override"><code>const routes = [
    {
        path:'/about',
        name: 'About',
        component: About
    },
    {
        path:'/experience',
        name: 'Experience',
        component: Experience
    },
    {
        path:'/education',
        name: 'Education',
        component: Education
    },
    {
        path:'/contact',
        name: 'Contact',
        component: Contact
    }
]

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes
})

export default router
</code>```

答:
Solved it! Had to change my router-view tag for this:

<router-view v-slot="{ Component, route }">
      <Transition name="fade" mode="out-in">

          <component :is="Component"></component>

      </Transition>
    </router-view>
```

Shoutout to the original solution https://stackoverflow.com/a/70042452/18184367

Body:
I want to make transitions between my navbar elements, so i'm using router-links. The transition works fine for the /about section, but for the others it completely stops working. If i'm on /something and return to /about, the transitions also works, but for other routes it doesn't.

Any advice of what i can do?

App.vue

<template>

    <Navbar/>

      <router-link to="/about"/>
      <router-link to="/experience"/>
      <router-link to="/education"/>
      <router-link to="/contact"/>

    <Transition name="slide-fade" mode="out-in">
      <router-view/>
    </Transition>

</template>

router.js

const routes = [
    {
        path:'/about',
        name: 'About',
        component: About
    },
    {
        path:'/experience',
        name: 'Experience',
        component: Experience
    },
    {
        path:'/education',
        name: 'Education',
        component: Education
    },
    {
        path:'/contact',
        name: 'Contact',
        component: Contact
    }
]

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes
})

export default router

Body:
Solved it! Had to change my router-view tag for this:

<router-view v-slot="{ Component, route }">
      <Transition name="fade" mode="out-in">
        <div :key="route.name">
          <component :is="Component"></component>
        </div>
      </Transition>
    </router-view>

Shoutout to the original solution https://stackoverflow.com/a/70042452/18184367


问:
text not in the the center vertically in TextFormField (Flutter)
I am writing an app in flutter and in the first page I have the app name and a text form field for the user phone number, but for some reason my text is not in the middle of the text form field vertically wise (added picture of the app at the bottom),

I want the text to be in the middle of the form field and not how it looks now.

Someone know how can I fix that?.

this is the text form field code code (without the app name widget):

```<code>import 'package:flutter/material.dart';

class EnterPhonePage extends StatefulWidget {
  const EnterPhonePage({Key? key}) : super(key: key);

  @override
  _EnterPhonePageState createState() => _EnterPhonePageState();
}

class _EnterPhonePageState extends State<EnterPhonePage> {
  final _phoneKey = GlobalKey<FormState>();
  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Scaffold(
      body: SafeArea(
        child: GestureDetector(
          onTap: () => FocusScope.of(context).requestFocus(
            FocusNode(),
          ),
          child: SingleChildScrollView(
            child: ConstrainedBox(
              constraints: BoxConstraints(
                minHeight: size.height - 90,
              ),
              child: Column(
                children: [
                  Padding(
                    padding: EdgeInsets.only(top: size.height * .015),
                    child: Center(
                      child: Container(
                        margin: EdgeInsets.symmetric(
                          horizontal: size.width * .045,
                        ),
                        height: size.height * .05,
                        child: Form(
                          key: _phoneKey,
                          child: TextFormField(
                            style: TextStyle(
                              fontSize: size.width * .035,
                            ),
                            decoration: InputDecoration(
                              hintText: 'Phone Number',
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(7.0),
                                borderSide: const BorderSide(
                                  color: Colors.black,
                                  width: 1.25,
                                ),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(7.0),
                                borderSide: const BorderSide(
                                  color: Colors.black,
                                  width: 1.5,
                                ),
                              ),
                            ),
                            autofocus: false,
                            keyboardType: TextInputType.number,
                            cursorColor: Colors.black,
                            textAlign: TextAlign.center,
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
</code>```

答:
You can add contentPadding in your input decoration

```<code>decoration: InputDecoration(
   contentPadding: EdgeInsets.fromLTRB(0, 10, 0, 0),
   hintText: 'Phone Number',
   enabledBorder: OutlineInputBorder(
     borderRadius: BorderRadius.circular(7.0),
     borderSide: const BorderSide(
       color: Colors.black,
       width: 1.25,
     ),
),
</code>```

Body:
I am writing an app in flutter and in the first page I have the app name and a text form field for the user phone number, but for some reason my text is not in the middle of the text form field vertically wise (added picture of the app at the bottom),

I want the text to be in the middle of the form field and not how it looks now.

Someone know how can I fix that?.

this is the text form field code code (without the app name widget):

import 'package:flutter/material.dart';

class EnterPhonePage extends StatefulWidget {
  const EnterPhonePage({Key? key}) : super(key: key);

  @override
  _EnterPhonePageState createState() => _EnterPhonePageState();
}

class _EnterPhonePageState extends State<EnterPhonePage> {
  final _phoneKey = GlobalKey<FormState>();
  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Scaffold(
      body: SafeArea(
        child: GestureDetector(
          onTap: () => FocusScope.of(context).requestFocus(
            FocusNode(),
          ),
          child: SingleChildScrollView(
            child: ConstrainedBox(
              constraints: BoxConstraints(
                minHeight: size.height - 90,
              ),
              child: Column(
                children: [
                  Padding(
                    padding: EdgeInsets.only(top: size.height * .015),
                    child: Center(
                      child: Container(
                        margin: EdgeInsets.symmetric(
                          horizontal: size.width * .045,
                        ),
                        height: size.height * .05,
                        child: Form(
                          key: _phoneKey,
                          child: TextFormField(
                            style: TextStyle(
                              fontSize: size.width * .035,
                            ),
                            decoration: InputDecoration(
                              hintText: 'Phone Number',
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(7.0),
                                borderSide: const BorderSide(
                                  color: Colors.black,
                                  width: 1.25,
                                ),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(7.0),
                                borderSide: const BorderSide(
                                  color: Colors.black,
                                  width: 1.5,
                                ),
                              ),
                            ),
                            autofocus: false,
                            keyboardType: TextInputType.number,
                            cursorColor: Colors.black,
                            textAlign: TextAlign.center,
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}

Body:
You can add contentPadding in your input decoration

decoration: InputDecoration(
   contentPadding: EdgeInsets.fromLTRB(0, 10, 0, 0),
   hintText: 'Phone Number',
   enabledBorder: OutlineInputBorder(
     borderRadius: BorderRadius.circular(7.0),
     borderSide: const BorderSide(
       color: Colors.black,
       width: 1.25,
     ),
),


问:
What is the proper way to determine usable screen dimensions in android
I know this question has been asked a few other times but I have yet to find a satisfactory answer. All previous answers work if you want the total screen resolution but fail to when you want to correct for the notification bar and/or the system bar in honeycomb.

Is there a way to determine the dimensions of the usable screen?

答: What I've done previously is almost definitely not the best way: make a control that is set to fill the screen and then check its size. This is useful if you have a view you paint to in a game or something like that.


问:
Getting indices of True values in a boolean list
I have a piece of my code where I'm supposed to create a switchboard. I want to return a list of all the switches that are on. Here "on" will equal True and "off" equal False. So now I just want to return a list of all the True values and their position. This is all I have but it only return the position of the first occurrence of True (this is just a portion of my code):

```<code>self.states = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]

def which_switch(self):
    x = [self.states.index(i) for i in self.states if i == True]
</code>```

This only returns "4"

答:
I got different benchmark result compared to @meysham answer. In this test, compress seems the fastest (python 3.7).

from itertools import compress
import numpy as np
```
<pre class="lang-py prettyprint-override"><code>t = [True, False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]

%timeit [i for i, x in enumerate(t) if x]
%timeit list(compress(range(len(t)), t))
%timeit list(filter(lambda x: t[x], range(len(t))))
%timeit np.where(t)[0]

# 2.54 µs ± 400 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
# 2.67 µs ± 600 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
# 6.22 µs ± 624 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
# 6.52 µs ± 768 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code>```

t = 1000*t
%timeit [i for i, x in enumerate(t) if x]
%timeit list(compress(range(len(t)), t))
%timeit list(filter(lambda x: t[x], range(len(t))))
%timeit np.where(t)[0]

# 1.68 ms ± 112 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
# 947 µs ± 105 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
# 3.96 ms ± 97 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
# 2.14 ms ± 45.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
```

Body:
I have a piece of my code where I'm supposed to create a switchboard. I want to return a list of all the switches that are on. Here "on" will equal True and "off" equal False. So now I just want to return a list of all the True values and their position. This is all I have but it only return the position of the first occurrence of True (this is just a portion of my code):

self.states = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]

def which_switch(self):
    x = [self.states.index(i) for i in self.states if i == True]

This only returns "4"

Body:
I got different benchmark result compared to @meysham answer. In this test, compress seems the fastest (python 3.7).

from itertools import compress
import numpy as np

t = [True, False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]

%timeit [i for i, x in enumerate(t) if x]
%timeit list(compress(range(len(t)), t))
%timeit list(filter(lambda x: t[x], range(len(t))))
%timeit np.where(t)[0]

# 2.54 µs ± 400 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
# 2.67 µs ± 600 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
# 6.22 µs ± 624 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
# 6.52 µs ± 768 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

t = 1000*t
%timeit [i for i, x in enumerate(t) if x]
%timeit list(compress(range(len(t)), t))
%timeit list(filter(lambda x: t[x], range(len(t))))
%timeit np.where(t)[0]

# 1.68 ms ± 112 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
# 947 µs ± 105 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
# 3.96 ms ± 97 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
# 2.14 ms ± 45.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)


问:
iPython console in Spyder does not enter in debug
I removed and started with a fresh new installation of Anaconda.
Just after installation I created a custom environment (cust_env)
Both the cust_env and the base environment have Python 3.9.
I then installed on both environments Spyder 5.1.

Now, the problem is the following:

If I run Spyder from the base environment, it seems to work and debug my code normally, while if I run it from the cust_env, when I enter in debug mode the console apparently does not answer anymore (the debug prompt does not appear and you must restart the kernel to have it back again).

I also tryed with different versions of Python (3.7.x and 3.8.x) and of Spyder (4.x, 3.x) and the behaviour looks identical.

I cannot understand what might be the difference which does not allow to use Spyder in an environment different to the base one.

答:
I was able to delimit the problem and find a workaround.

The base problem is that, when you create a new environment of Anaconda, since it contains very few packages (Python and few more), when you afterwards install a new package, it is fully updated with all its dependancies.
In particular

```<code>conda install spyder
</code>```

installs Spyder and all its dependancies at the very last available version.

On the opposite side, the base environment of Anaconda already contains plenty of packages and conda does it best to install the most updated version which is still compatible with the existing packages, but very often it is not the last one.
Now, it appears that Spyder uses QT to show the graphical interface and one of its dependancies qtconsole=5.2.2 has some bug which causes the problem.
When installing Spyder from the base environment, conda installs qtconsole=5.1.1 and the problem does not appear while, if installing from a fresh new environment, qtconsole=5.2.2 is installed and the problem shows up.
Therefore, is is sufficient to downgrade qtconsole

```<code>conda install qtconsole=5.1.1
</code>```

to fix the problem.

Body:
I was able to delimit the problem and find a workaround.

The base problem is that, when you create a new environment of Anaconda, since it contains very few packages (Python and few more), when you afterwards install a new package, it is fully updated with all its dependancies.
In particular

conda install spyder

installs Spyder and all its dependancies at the very last available version.

On the opposite side, the base environment of Anaconda already contains plenty of packages and conda does it best to install the most updated version which is still compatible with the existing packages, but very often it is not the last one.
Now, it appears that Spyder uses QT to show the graphical interface and one of its dependancies qtconsole=5.2.2 has some bug which causes the problem.
When installing Spyder from the base environment, conda installs qtconsole=5.1.1 and the problem does not appear while, if installing from a fresh new environment, qtconsole=5.2.2 is installed and the problem shows up.
Therefore, is is sufficient to downgrade qtconsole

conda install qtconsole=5.1.1

to fix the problem.


问:
How to use Inner Joins with where clause?
I am here posting some extension of How to concatenate more sql queries to get one table? question to get more specific query results.

Let assume we are having now this type of dataset.

```<code>query1 : select * from userdetails1.UserTable;

Result1:
UserID  Username    Status
1         John      Active
2         Micheal   Active
3         Ann       Active
4         Shasha    Resigned
5         mike      Resigned

query2 :
select *
from userdetails2.AmountTable
where TotalAmountResetDate ='2022-01-31' ;

result2:
UserId  TotalAmount TotalAmountResetDate
1          -12         1/31/2022
2          345         1/31/2022
3          213         1/31/2022
4          0           1/31/2022
5          0           1/31/2022

query3:
select Username,sum(TotalInvested) as TotalInvested
from userdetails2.TotalInvestmentsTable
where total_invested_date between '2022-01-31' and '2022-02-12'
group by Username;

result3:

Username    Totalnvested
John         45000
Micheal      45000
Ann          45000

query4:
select Username,sum(TotalExpenses)
from userdetails2.TotalExpensesTable
where date_of_expense_date between '2022-01-31' and '2022-02-12'
group by Username;

Username    TotalExpenses
John           2543
Micheal        2345
Ann            3290
</code>```

Then how I get the output as below,

```<code>UserId  Username    TotalAmountResetDate    TotalAmount Totalnvested    TotalExpenses   TotalBalance
1        John              1/31/2022               -12       45000            2543          42445
2        Micheal           1/31/2022               345       45000            2345          43000
3        Ann               1/31/2022               213       45000            3290          41923
4        Shasha            1/31/2022               0         0                 0            0
5        mike              1/31/2022               0         0                 0            0
</code>```

From the answers I have made this answer, but seems it is not getting what I need, it removes Zero values. Can someone help?

```<code>    SELECT t2.UserID,
       t1.Username,
       t2.TotalAmountResetDate,
       t2.TotalAmount,
       COALESCE(Totalnvested,0) Totalnvested,
       COALESCE(TotalExpenses,0) TotalExpenses,
       t2.TotalAmount + COALESCE(Totalnvested,0) - COALESCE(TotalExpenses,0) TotalBalance
FROM userdetails1.UserTable t1
INNER JOIN userdetails2.AmountTable t2
ON t1.UserID = t2.UserID
LEFT JOIN userdetails2.TotalInvestmentsTable investment
ON t1.Username = investment.Username
LEFT JOIN userdetails2.TotalExpensesTable expenses
ON t1.Username = expenses.Username
where t2.TotalAmountResetDate='2022-01-31' and investment.total_invested_date between '2022-01-31' and '2022-02-12';
</code>```

答:
Apologies, edited as I misread the question...

I would just move the date parameter from the where clause to the join on 'TotalInvestmentsTable' as below:

SELECT t2.UserID,
       t1.Username,
       t2.TotalAmountResetDate,
       t2.TotalAmount,
       COALESCE(Totalnvested,0) Totalnvested,
       COALESCE(TotalExpenses,0) TotalExpenses,
       t2.TotalAmount + COALESCE(Totalnvested,0) - COALESCE(TotalExpenses,0) TotalBalance
FROM userdetails1.UserTable t1
INNER JOIN userdetails2.AmountTable t2
ON t1.UserID = t2.UserID
INNER JOIN userdetails2.TotalInvestmentsTable investment
ON t1.Username = investment.Username
and investment.total_invested_date between '2022-01-31' and '2022-02-12'
INNER JOIN userdetails2.TotalExpensesTable expenses
ON t1.Username = expenses.Username
where t2.TotalAmountResetDate='2022-01-31';
```

Body:
I am here posting some extension of How to concatenate more sql queries to get one table? question to get more specific query results.

Let assume we are having now this type of dataset.

query1 : select * from userdetails1.UserTable;

Result1:
UserID  Username    Status
1         John      Active
2         Micheal   Active
3         Ann       Active
4         Shasha    Resigned
5         mike      Resigned

query2 :
select *
from userdetails2.AmountTable
where TotalAmountResetDate ='2022-01-31' ;

result2:
UserId  TotalAmount TotalAmountResetDate
1          -12         1/31/2022
2          345         1/31/2022
3          213         1/31/2022
4          0           1/31/2022
5          0           1/31/2022

query3:
select Username,sum(TotalInvested) as TotalInvested
from userdetails2.TotalInvestmentsTable
where total_invested_date between '2022-01-31' and '2022-02-12'
group by Username;

result3:

Username    Totalnvested
John         45000
Micheal      45000
Ann          45000

query4:
select Username,sum(TotalExpenses)
from userdetails2.TotalExpensesTable
where date_of_expense_date between '2022-01-31' and '2022-02-12'
group by Username;

Username    TotalExpenses
John           2543
Micheal        2345
Ann            3290

Then how I get the output as below,

UserId  Username    TotalAmountResetDate    TotalAmount Totalnvested    TotalExpenses   TotalBalance
1        John              1/31/2022               -12       45000            2543          42445
2        Micheal           1/31/2022               345       45000            2345          43000
3        Ann               1/31/2022               213       45000            3290          41923
4        Shasha            1/31/2022               0         0                 0            0
5        mike              1/31/2022               0         0                 0            0

From the answers I have made this answer, but seems it is not getting what I need, it removes Zero values. Can someone help?

    SELECT t2.UserID,
       t1.Username,
       t2.TotalAmountResetDate,
       t2.TotalAmount,
       COALESCE(Totalnvested,0) Totalnvested,
       COALESCE(TotalExpenses,0) TotalExpenses,
       t2.TotalAmount + COALESCE(Totalnvested,0) - COALESCE(TotalExpenses,0) TotalBalance
FROM userdetails1.UserTable t1
INNER JOIN userdetails2.AmountTable t2
ON t1.UserID = t2.UserID
LEFT JOIN userdetails2.TotalInvestmentsTable investment
ON t1.Username = investment.Username
LEFT JOIN userdetails2.TotalExpensesTable expenses
ON t1.Username = expenses.Username
where t2.TotalAmountResetDate='2022-01-31' and investment.total_invested_date between '2022-01-31' and '2022-02-12';


问:
iOS - Scan QR code with camera - Option A: Go to installed application - Option B: Go to appstore
At this moment we have a feature build in our app that uses the normal iOS camera app for scanning a QR code. When this happens you will be redirected to the concerning app that's installed and not a certain webpage.

Our question is:
Is it possible to be redirected to the appstore, if you don't have the concerning app installed where this QR code is for?

I'm not a developer myself and only curious if its possible.
This for future expansions of our app.

Thanks in advance.

答: You can use Firebase Dynamic Links Firebase Dynamic Links: Getting Started</p>


问:
Get Column Names as Symbols in Julia DataFrame
I have a DataFrame

```<code>df = DataFrame(a=1:4,b=5:8, c=["a", "b", "c", "d"])
4×3 DataFrame
 Row │ a      b      c
     │ Int64  Int64  String
─────┼──────────────────────
   1 │     1      5  a
   2 │     2      6  b
   3 │     3      7  c
   4 │     4      8  d
</code>```

I can get the column names as a Vector of Strings with

```<code>names(df)
3-element Vector{String}:
 "a"
 "b"
 "c"
</code>```

Is there a built-in way of getting it as Symbols? (I thought, I've seen this somewhere, but I can't remember where...)

答:
Use propertynames from Base Julia to get what you want:

```<code>julia> propertynames(df)
3-element Vector{Symbol}:
 :a
 :b
 :c
</code>```

Body:
I have a DataFrame

df = DataFrame(a=1:4,b=5:8, c=["a", "b", "c", "d"])
4×3 DataFrame
 Row │ a      b      c
     │ Int64  Int64  String
─────┼──────────────────────
   1 │     1      5  a
   2 │     2      6  b
   3 │     3      7  c
   4 │     4      8  d

I can get the column names as a Vector of Strings with

names(df)
3-element Vector{String}:
 "a"
 "b"
 "c"

Is there a built-in way of getting it as Symbols? (I thought, I've seen this somewhere, but I can't remember where...)

Body:
Use propertynames from Base Julia to get what you want:

julia> propertynames(df)
3-element Vector{Symbol}:
 :a
 :b
 :c


问:
cvCvtColor crashes when converting from RGB to grayscale
I'm trying to convert an image from RGB to grayscale.  However, I am getting this error when trying:

OpenCV Error: Null pointer  in unknown
  function, file
  ......\ocv\opencv\src\cxcore\cxarray.cpp,
  line 2376

Why might this be happening?

答:
Notice the following:

..The destination image of the same data type as the source.

Otherwise, you'll crash.

ContentLicense: CC BY-SA 2.5


问:
Exiting all long trades when entering short trade
I use pyramiding. Lets say I have now 3 long trades open and then short trade condiction appears. Short trade entries, but at the same moment all opposite trades (in this example long trades) close.

How to have both long and short trades being open simultaneously?

答:
You can call the strategy.close_all() function before you open your short trade.

It is a command to exit from current market position making it flat.
If there is no open market position by the moment the command is
triggered, the command will not come into effect.

```<code>strategy("closeAll Demo", overlay=false)
strategy.entry("buy", strategy.long, when = open > close)
strategy.close_all(when = open < close, comment = "close all entries")
plot(strategy.position_size)
</code>```

Body:
You can call the strategy.close_all() function before you open your short trade.

It is a command to exit from current market position making it flat.
If there is no open market position by the moment the command is
triggered, the command will not come into effect.

strategy("closeAll Demo", overlay=false)
strategy.entry("buy", strategy.long, when = open > close)
strategy.close_all(when = open < close, comment = "close all entries")
plot(strategy.position_size)


问:
Scanner doesn't read whole sentence - difference between next() and nextLine() of scanner class
I'm writing a program which allows the user to input his data then outputs it. Its 3/4 correct but when it arrives at outputting the address it only prints a word lets say only 'Archbishop' from 'Archbishop Street'. How do I fix this?</p>

```<code>import java.util.*;

class MyStudentDetails{
    public static void main (String args[]){
        Scanner s = new Scanner(System.in);
        System.out.println("Enter Your Name: ");
        String name = s.next();
        System.out.println("Enter Your Age: ");
        int age = s.nextInt();
        System.out.println("Enter Your E-mail: ");
        String email = s.next();
        System.out.println("Enter Your Address: ");
        String address = s.next();

        System.out.println("Name: "+name);
        System.out.println("Age: "+age);
        System.out.println("E-mail: "+email);
        System.out.println("Address: "+address);
    }
}
</code>```

答:
Try this !!!</p>
```<code>    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String s = scan.nextLine();
        s = scan.nextLine();
        scan.close();
        System.out.println("String: " + s);

    }
</code>```

Body:
I'm writing a program which allows the user to input his data then outputs it. Its 3/4 correct but when it arrives at outputting the address it only prints a word lets say only 'Archbishop' from 'Archbishop Street'. How do I fix this?

import java.util.*;

class MyStudentDetails{
    public static void main (String args[]){
        Scanner s = new Scanner(System.in);
        System.out.println("Enter Your Name: ");
        String name = s.next();
        System.out.println("Enter Your Age: ");
        int age = s.nextInt();
        System.out.println("Enter Your E-mail: ");
        String email = s.next();
        System.out.println("Enter Your Address: ");
        String address = s.next();

        System.out.println("Name: "+name);
        System.out.println("Age: "+age);
        System.out.println("E-mail: "+email);
        System.out.println("Address: "+address);
    }
}

Body:
Try this !!!

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String s = scan.nextLine();
        s = scan.nextLine();
        scan.close();
        System.out.println("String: " + s);

    }


问:
How to set up fixed width for ?
Simple scheme:

```<code>  <tr class="something">
    <td>A</td>
    <td>B</td>
    <td>C</td>
    <td>D</td>
  </tr>
</code>```

I need to set up a fixed width for . I've tried:

```<code>tr.something {
  td {
    width: 90px;
  }
}
</code>```

Also

```<code>td.something {
  width: 90px;
}
</code>```

for

```<code><td class="something">B</td>
</code>```

And even

```<code><td style="width: 90px;">B</td>
</code>```

But the width of  is still the same.

答:
For me, setting the table's layout to auto and targeting the specific columns'  did the trick. I found that targeting  in any of the rows works as well. Feel free to throw in !important if you need to.

```<code>.table {
  table-layout: auto;
}

th {
 width: 10%;
}
</code>```

Title: How to set up fixed width for <td>?

Body:
Simple scheme:

    A
    B
    C
    D

I need to set up a fixed width for . I've tried:

tr.something {
  td {
    width: 90px;
  }
}

Also

td.something {
  width: 90px;
}

for

B

And even

B

But the width of  is still the same.

Body:
For me, setting the table's layout to auto and targeting the specific columns' <th> did the trick. I found that targeting <td> in any of the rows works as well. Feel free to throw in !important if you need to.

.table {
  table-layout: auto;
}

th {
 width: 10%;
}


问:
Firebase push notification routing flutter
I have the push notifications set up using firebase_messaging on my app. When the app is opened from a terminated state via a push notification, I navigate to a specific route (ProductPage) and upon pressing the back button, I get a black screen as there are no routes on the navigation stack

When I press the back button from the app bar or trigger the hardware back button on an Android device, how can I make the app navigate to the initial route instead of seeing a black screen?

I tried utilizing the onWillPop callback of the WillPopScope widget, but the callback exits the app entirely instead of navigating to the new route.

```<code>class ProductPage extends StatefulWidget {
@override
_ProductPageState createState() => _ProductPageState();

}

class _ProductPageState extends State<ProductPage> {
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
    onWillPop: () async {
      Navigator.pushReplacementNamed(context,"homePage");
      return false;
    },
    child: Scaffold(appBar: AppBar(title: Text("Product Page"),),));
   }
  }
</code>```

onMessageOpenedApp callback:

```<code>FirebaseMessaging.onMessageOpenedApp.listen((message) {
    print("ON MESSAGE OPENED");
    Navigator.pushNamed(context,"productsPage");
  });
</code>```

The expected routing behaviour is close to this video below. Consider this navigation from quick action of the app, the settings app was not running in the background. I tap on a quick action, I get navigated to a specific screen, and upon a back button gesture or pressing the back button on the app bar, I get navigated to the home page of the app.

Expected routing

答:
you could try saving a backstack like here and adding it manually when the user enters via the push notification.

Try debugging your app in this state. My guess is, that you don't have a full backstack opening the app via push notification.

Maybe this helps:
https://medium.com/androiddevelopers/multiple-back-stacks-b714d974f134

Body:
I have the push notifications set up using firebase_messaging on my app. When the app is opened from a terminated state via a push notification, I navigate to a specific route (ProductPage) and upon pressing the back button, I get a black screen as there are no routes on the navigation stack

When I press the back button from the app bar or trigger the hardware back button on an Android device, how can I make the app navigate to the initial route instead of seeing a black screen?

I tried utilizing the onWillPop callback of the WillPopScope widget, but the callback exits the app entirely instead of navigating to the new route.

class ProductPage extends StatefulWidget {
@override
_ProductPageState createState() => _ProductPageState();

}

class _ProductPageState extends State<ProductPage> {
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
    onWillPop: () async {
      Navigator.pushReplacementNamed(context,"homePage");
      return false;
    },
    child: Scaffold(appBar: AppBar(title: Text("Product Page"),),));
   }
  }

onMessageOpenedApp callback:

FirebaseMessaging.onMessageOpenedApp.listen((message) {
    print("ON MESSAGE OPENED");
    Navigator.pushNamed(context,"productsPage");
  });

The expected routing behaviour is close to this video below. Consider this navigation from quick action of the app, the settings app was not running in the background. I tap on a quick action, I get navigated to a specific screen, and upon a back button gesture or pressing the back button on the app bar, I get navigated to the home page of the app.

Expected routing


问:
Errors while building APK: Algorithm HmacPBESHA256 not available
I am trying to update an existing Android app, but while generating a Signed APK the following error message appears: Algorithm HmacPBESHA256 not available

I have searched the internet for a solution, including here on StackOverflow, but I cannot find one anywhere. I know that the current keystore uses SHA1withRSA, but how to convert it to HmacPBESHA256 I would not know. Google Play support unfortunately can't help me either, as this question is too technical.

For the sake of clarity here is the full notification:

Execution failed for task ':app:packageRelease'.
A failure occurred while executing com.android.build.gradle.tasks.PackageAndroidArtifact$IncrementalSplitterRunnable
com.android.ide.common.signing.KeytoolException: Failed to read key 1 from store "/Users/KDApps/Documents/KDApps/original-signing-keystore.jks": Integrity check failed: java.security.NoSuchAlgorithmException: Algorithm HmacPBESHA256 not available

答:
I solved this problem by entering
"File" -> "Settings" -> "Build, Execution, Deployment" -> "Build Tools" -> "Gradle"
and selected appropriate "Gradle JDK" version.</p>


问:
Modifying String in Java
I have a String  , String a = newNumber + "*" + nn + "+" + difference;
the newNumber = 106 , nn = 3 and difference = 3.
so the output should be as follow ;

Output :
106*3+3

I would like to modify the String so that the output becomes (35*3+1)*3+3 and then with this new String I would like to modify it again so that it becomes ((11*3+2)*3+1)*3+3
Basically I just need to replace the newNumber which was 106 and kept changing to 11, as you can see I'm trying to modify only the newNumber and replacing it with another while keeping the entire String untouched , I'm just replacing and adding to it , how can this be achieved ?
The output should be like this,
Output :

```<code>106*3+3
(35*3+1)*3+3
((11*3+2)*3+1)*3+3
</code>```

I'm solving an equation with steps , the formulas don't matter I'm just trying to figure out how can I modify the String by replacing the newNumber with a another number and adding new brackets to the equation.
I hope I wrote my problem in a way you would understand , I'd really appreciate the help.

答:
You can’t actually modify Strings, but you can use replaceFirst() like this:

```<code>s = s.replaceFirst("106", "(35*3+1)");
s = s.replaceFirst("35", "(11*3+2)");
</code>```

etc

Title: Modifying String in Java

Body:
I have a String  , String a = newNumber + "*" + nn + "+" + difference;
the newNumber = 106 , nn = 3 and difference = 3.
so the output should be as follow ;

Output :
106*3+3

I would like to modify the String so that the output becomes (35*3+1)*3+3 and then with this new String I would like to modify it again so that it becomes ((11*3+2)*3+1)*3+3
Basically I just need to replace the newNumber which was 106 and kept changing to 11, as you can see I'm trying to modify only the newNumber and replacing it with another while keeping the entire String untouched , I'm just replacing and adding to it , how can this be achieved ?
The output should be like this,
Output :

106*3+3
(35*3+1)*3+3
((11*3+2)*3+1)*3+3

I'm solving an equation with steps , the formulas don't matter I'm just trying to figure out how can I modify the String by replacing the newNumber with a another number and adding new brackets to the equation.
I hope I wrote my problem in a way you would understand , I'd really appreciate the help.

Body:
You can’t actually modify Strings, but you can use replaceFirst() like this:

s = s.replaceFirst("106", "(35*3+1)");
s = s.replaceFirst("35", "(11*3+2)");

etc


问:
Telegram bot doesn't run on heroku

Problem

My problem is that when trying to deploy bot on heroku I get r10 error boot timeout, but it works when running locally and I cant seem to find the fix for it

heroku logs

```<code>Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 90 seconds of launch
Stopping process with SIGKILL
Process exited with status 137
State changed from starting to crashed
</code>```

My code

```<code>process.env.NTBA_FIX_319 = 1
const TelegramBot = require('node-telegram-bot-api')
require('dotenv').config()

const token = process.env.TOKEN
const myInfo = process.env.INFO
const error = process.env.ERROR
const git = process.env.GIT
const bot = new TelegramBot(token, { polling: true })

bot.on('message', (msg) => {
  const chatId = msg.chat.id
  const name = msg.chat.first_name
  const { text } = msg

  if (text === '/start' || text === '/help') {
    bot.sendMessage(chatId, `Hi ${name}! These are the commands below:`, {
      reply_markup: {
        keyboard: [
          [
            { text: '/start' },
            { text: '/about' },
            { text: '/links' },
            { text: '/help' },
          ],
        ],
        resize_keyboard: true,
        one_time_keyboard: true,
      },
    })
  } else if (text === '/about') {
    bot.sendMessage(chatId, `${myInfo}`)
  } else if (text === '/links') {
    bot.sendMessage(chatId, `${git}`)
  } else {
    bot.sendMessage(chatId, `${error}`)
  }
})
</code>```

Dockerfile

```<code>FROM node:16.13.2-alpine
WORKDIR /Bot1
ENV PORT 88
COPY package.json /Bot1/package.json
RUN npm install
COPY . .
CMD ["node", "app.js"]
</code>```

comands to deploy bot

heroku container:push web

heroku container:release web

答:
You have deployed your code as a web process. web processes listen for HTTP requests and must bind to a port provided at runtime shortly after starting up.

Since your bot does not respond to HTTP requests it should not be deployed as a web process. A common name for such processes is worker.

First, remove the web container you have already deployed:

heroku container:rm web
```
<p>Now, redeploy your code as a <code>worker</code> process:</p>
<pre class="lang-none prettyprint-override"><code>heroku container:push worker
heroku container:release worker
</code>```

You may need to scale your dynos after doing this. Something like

heroku ps:scale worker=1
```

should do the trick.

Title: Telegram bot doesn't run on heroku

Body:
Problem

My problem is that when trying to deploy bot on heroku I get r10 error boot timeout, but it works when running locally and I cant seem to find the fix for it

heroku logs

Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 90 seconds of launch
Stopping process with SIGKILL
Process exited with status 137
State changed from starting to crashed

My code

process.env.NTBA_FIX_319 = 1
const TelegramBot = require('node-telegram-bot-api')
require('dotenv').config()

const token = process.env.TOKEN
const myInfo = process.env.INFO
const error = process.env.ERROR
const git = process.env.GIT
const bot = new TelegramBot(token, { polling: true })

bot.on('message', (msg) => {
  const chatId = msg.chat.id
  const name = msg.chat.first_name
  const { text } = msg

  if (text === '/start' || text === '/help') {
    bot.sendMessage(chatId, `Hi ${name}! These are the commands below:`, {
      reply_markup: {
        keyboard: [
          [
            { text: '/start' },
            { text: '/about' },
            { text: '/links' },
            { text: '/help' },
          ],
        ],
        resize_keyboard: true,
        one_time_keyboard: true,
      },
    })
  } else if (text === '/about') {
    bot.sendMessage(chatId, `${myInfo}`)
  } else if (text === '/links') {
    bot.sendMessage(chatId, `${git}`)
  } else {
    bot.sendMessage(chatId, `${error}`)
  }
})

Dockerfile

FROM node:16.13.2-alpine
WORKDIR /Bot1
ENV PORT 88
COPY package.json /Bot1/package.json
RUN npm install
COPY . .
CMD ["node", "app.js"]

comands to deploy bot

heroku container:push web

heroku container:release web

Body:
You have deployed your code as a web process. web processes listen for HTTP requests and must bind to a port provided at runtime shortly after starting up.

Since your bot does not respond to HTTP requests it should not be deployed as a web process. A common name for such processes is worker.

First, remove the web container you have already deployed:

heroku container:rm web

Now, redeploy your code as a worker process:

heroku container:push worker
heroku container:release worker

You may need to scale your dynos after doing this. Something like

heroku ps:scale worker=1

should do the trick.


问:
Template function for max_element on maps needs to know both types
I'm trying to write a custom cmp function for a map, a simple one that does the comparison over the second element of the map. I'd like to have the function as a template, but I can't figure out how to pass the map's .first and .second types along to my cmp function. My non-working code is below, which will clearly fail since the type of T1 and T2 are not passed along:

```<code>#include <map>
#include <vector>
#include <algorithm>

template<class T1, class T2>
bool pairCompare(const std::pair<T1,T2> & x,
                 const std::pair<T1,T2> & y) {
  return x.second < y.second;
}

template<class T1>
typename T1::iterator map_max_element(const T1 & A) {

  // How do I pass the type to pairCompare?
  return std::max_element(A.begin(), A.end(), pairCompare<?????>);
}

int main() {
  std::map<std::vector<double>, int> A;
  map_max_element(A);

  return 0;
}
</code>```

答: You can use T1::key_type and T1::mapped_type, or more simply, just T1::value_type, which is equivalent to std::pair<T1::key_type,T1::mapped_type>.

Body:
I'm trying to write a custom cmp function for a map, a simple one that does the comparison over the second element of the map. I'd like to have the function as a template, but I can't figure out how to pass the map's .first and .second types along to my cmp function. My non-working code is below, which will clearly fail since the type of T1 and T2 are not passed along:

#include <map>
#include <vector>
#include <algorithm>

template<class T1, class T2>
bool pairCompare(const std::pair<T1,T2> & x,
                 const std::pair<T1,T2> & y) {
  return x.second < y.second;
}

template<class T1>
typename T1::iterator map_max_element(const T1 & A) {

  // How do I pass the type to pairCompare?
  return std::max_element(A.begin(), A.end(), pairCompare<?????>);
}

int main() {
  std::map<std::vector<double>, int> A;
  map_max_element(A);

  return 0;
}


问:
MacOS Catalina(v 10.15.3): Error: “chromedriver” cannot be opened because the developer cannot be verified. Unable to launch the chrome browser
I have recently upgraded my mac machine to OS Catalina(v 10.15.3). After this upgrade I am unable to launch the chrome driver using selenium.

I am facing the below error when I run the selenium code to launch the chrome browser.

"“chromedriver” cannot be opened because the developer cannot be verified".
"macOS cannot verify that this app is free from malware."

Please help me!

答:
The easiest way to solve this error, please follow the steps below.

Navigate to where your chrome driver application is saved / downloaded

Right click and select Open with

Select open with Terminal

Allow or select yes

you should get a success message on the terminal screen

Go back to open your chrome driver or on your IDE and run, you should not get the error anymore


问:
Conda stopped working with the debug feature in visual studio code for no apparent reason

To note:

Pressing F5 (start debugging) correctly activates the conda environment

The environment of the IDE is indeed the desired conda environment. Python 3.9.7 ('conda environment name': conda)

The conda environment works if done through the terminal instead of the F5 debugging feature

After the environment is activated and I press F5 nothing happens and nothing is logged to the visual studio code logs. It does not work with any conda environment I have including 'base'.

This is the only thing that happens when I press F5:

Starts debugging, as expected.

One / two seconds later:

If I change the code interpreter to just Python 3.9.7 the code does in fact run. And again, if I run the conda enviroment THROUGH the terminal instead of F5 (and giving up on debugging, which I need) the conda enviroment also works.

To reiterate, no debug logs in Visual Studio Code, including files.

Any idea on how to tackle this? Been stuck for a while.

Machine is an ubuntu 20.04

答:
Seems to be a bug with VS Code (issue link). Apparently, it was supposed to be fixed, but it still wasn't working for me. The issue was with new the new Python extension and older versions of Conda.

So first of all try updating Conda. For me it still wasn't working because VS Code didn't have the appropriate permissions, so I had to launch it with admin rights. Now it works.


问:
Select images and display using JavaScript
This will select the targeted files and cycles through selected files and stops on the last file. How can the images be displayed without being over written?</p>
```<code>//Function below is in the DOM area
function showDirectory(){
   var myFiles = document.getElementById("files");
   for(var i=0;i<=myFiles.files.length; i++){
   var x = myFiles.files[i].name;
   document.getElementById("demo1").src= x;
   }
}
//This is in a div in the body
<input type="file" id="files" name="files[]" multiple/>
<button onclick="showDirectory();">Show files in the Directory</button>
<img id="demo1" src=""  style="width: 40px; height: 40px;"><br>
</code>```

答:
The syntax document.createElement() is used to actually create new DOM elements, so that you don't have to override old ones. In your case, replace document.getElementById("demo1").src= x; with

```<code>let e = document.createElement("img");
e.src = x;
document.getElementById("demo1").appendChild(e);
</code>```

This code will create a new DOM element of type image, it will set its source to whatever your for loop outputs, and then it will append the img to the div that you have created.

Body:
This will select the targeted files and cycles through selected files and stops on the last file. How can the images be displayed without being over written?

//Function below is in the DOM area
function showDirectory(){
   var myFiles = document.getElementById("files");
   for(var i=0;i<=myFiles.files.length; i++){
   var x = myFiles.files[i].name;
   document.getElementById("demo1").src= x;
   }
}
//This is in a div in the body
<input type="file" id="files" name="files[]" multiple/>
<button onclick="showDirectory();">Show files in the Directory</button>

Body:
The syntax document.createElement() is used to actually create new DOM elements, so that you don't have to override old ones. In your case, replace document.getElementById("demo1").src= x; with

let e = document.createElement("img");
e.src = x;
document.getElementById("demo1").appendChild(e);

This code will create a new DOM element of type image, it will set its source to whatever your for loop outputs, and then it will append the img to the div that you have created.


问:
How to create an np.array from another np.array if the element of a third np.array of the same index is zero?
Suppose I have

a = np.array([0, 1, 3, 0])
b = np.array([[4,5],[7,8],[9,5],[8,2]])
```
<p>How can I create a third array</p>
```c = [[4,5],[8,2]]
```

with a list comprehension?

答:
Note that the best (and fastest) way of doing this is without list comprehensions, and using boolean indexing:

c = b[a==0]
```
<p>If you want to use list comprehensions, besides the option presented by @politinsa, you can use <code>zip</code>, that is useful when you have to go through more than one iterable at the same time (in this case, <code>a</code> and <code>b</code>):</p>
<pre class="lang-py prettyprint-override"><code>c = np.array([b_d for (b_d, a_d) in zip(b, a) if a_d == 0])
</code>```

When you want to iterate through elements and get the index of each element, enumerate can be cleaner than a range(len(iterable)) (although not necessarily faster):

c = np.array([b_d for i,b_d in enumerate(b) if a[i] == 0])
```

Body:
Suppose I have

a = np.array([0, 1, 3, 0])
b = np.array([[4,5],[7,8],[9,5],[8,2]])

How can I create a third array

c = [[4,5],[8,2]]

with a list comprehension?

Body:
Note that the best (and fastest) way of doing this is without list comprehensions, and using boolean indexing:

c = b[a==0]

If you want to use list comprehensions, besides the option presented by @politinsa, you can use zip, that is useful when you have to go through more than one iterable at the same time (in this case, a and b):

c = np.array([b_d for (b_d, a_d) in zip(b, a) if a_d == 0])

When you want to iterate through elements and get the index of each element, enumerate can be cleaner than a range(len(iterable)) (although not necessarily faster):

c = np.array([b_d for i,b_d in enumerate(b) if a[i] == 0])


问:
value of type string cannot be converted to list(of string) VB.Net
I am serializing the data structure to xml but i am getting the Error

Data Structure

```<code>Public Class Product
Public Id As Integer
Public name As String
Public quantity As Integer
Public price As Integer
Public Property state As List(Of States)

Public Sub New()
End Sub

Public Sub New(ByVal name As String,
               ByVal quantity As Integer,
               ByVal price As Integer,
               ByVal state As List(Of States)
               )
    Me.name = name
    Me.quantity = quantity
    Me.price = price
    Me.state = state
End Sub
End Class

Public Class States
    <XmlArrayItem("State")>
    Public Property state As List(Of String)
    Public Sub New()
    End Sub

    Public Sub New(state As List(Of String))
        state = New List(Of String)()
    End Sub
End Class
</code>```

This is how I am passing the data

```<code>        Dim countries As New List(Of Product) From
    {
        New Product With {.name = "Pakistan", .quantity = 1, .price = 50, .state = New List(Of States) From
        {
            New States With {.state = "KPK"},
            New States With {.state = "Punjab"},
            New States With {.state = "Sindh"}}},
        New Product With {.name = "Saudi Arabia", .quantity = 2, .price = 100, .state = New List(Of States) From
        {
            New States With {.state = "Makkah"},
            New States With {.state = "Madina"},
            New States With {.state = "Jaddah"}}
        }
    }
</code>```

I am getting the Error in States List i.e. (New States With {.state = "Makkah"}) it says value of type string cannot be converted to list(of string) I tried it in different way but this error is not going anywhere

My Serializer Code

```<code>Dim serialization As XmlSerializer = New XmlSerializer(GetType(List(Of Product)))
    serialization.Serialize(Console.Out, countries)
    Console.ReadLine()
</code>```

I'm not sure what exactly is wrong with this code.

答:
Just as you create a List(Of States) for Product, you'd need to create a List(Of String) for States

Dim countries As New List(Of Product) From
    {
        New Product With {.name = "Pakistan", .quantity = 1, .price = 50, .state = New List(Of States) From
        {
            New States With {.state = New List(Of String) From {"KPK"}}, 'A list with one item
            New States With {.state = New List(Of String) From {"Punjab", "Sindh"} 'A list with two items
        }
    }
```

Body:
I am serializing the data structure to xml but i am getting the Error

Data Structure

Public Class Product
Public Id As Integer
Public name As String
Public quantity As Integer
Public price As Integer
Public Property state As List(Of States)

Public Sub New()
End Sub

Public Sub New(ByVal name As String,
               ByVal quantity As Integer,
               ByVal price As Integer,
               ByVal state As List(Of States)
               )
    Me.name = name
    Me.quantity = quantity
    Me.price = price
    Me.state = state
End Sub
End Class

Public Class States
    <XmlArrayItem("State")>
    Public Property state As List(Of String)
    Public Sub New()
    End Sub

    Public Sub New(state As List(Of String))
        state = New List(Of String)()
    End Sub
End Class

This is how I am passing the data

        Dim countries As New List(Of Product) From
    {
        New Product With {.name = "Pakistan", .quantity = 1, .price = 50, .state = New List(Of States) From
        {
            New States With {.state = "KPK"},
            New States With {.state = "Punjab"},
            New States With {.state = "Sindh"}}},
        New Product With {.name = "Saudi Arabia", .quantity = 2, .price = 100, .state = New List(Of States) From
        {
            New States With {.state = "Makkah"},
            New States With {.state = "Madina"},
            New States With {.state = "Jaddah"}}
        }
    }

I am getting the Error in States List i.e. (New States With {.state = "Makkah"}) it says value of type string cannot be converted to list(of string) I tried it in different way but this error is not going anywhere

My Serializer Code

Dim serialization As XmlSerializer = New XmlSerializer(GetType(List(Of Product)))
    serialization.Serialize(Console.Out, countries)
    Console.ReadLine()

I'm not sure what exactly is wrong with this code.


问:
ERROR:'keytool' is not recognized as an internal or external command, operable program or batch file
When I use the command:

```<code>C:\>keytool -list -alias androiddebugkey
            -keystore .android\debug.keystore
            -storepass android -keypass android
</code>```

I get this error:

'keytool' is not recognized as an internal or external command, operable program or batch file.

I'm not able to get the certificate fingerprint(MD5) on my computer.

I have ensured that the keystore file is present in the appropriate location.

Any help?

答:
If you use flutter and have downloaded openssl-for-windows:

Open Command Prompt

Type flutter doctor -v

Under Android toolchain you will see Java binary at: C:\Program Files\Android\jre\bin\java

Now copy the line of code and do cd C:\Program Files\Android\jre\bin

Type keytool -exportcert -alias androiddebugkey -keystore "C:\Users\Username\.android\debug.keystore" | "Location to openssl.exe" sha1 -binary | "Location to openssl.exe" base64

(Double quotes are necessary)

Enter keystore password:  android (default password)

This will give you Key Hash.

Now,

if you are trying to get your SHA fingerprint, this is the easiest way to get it -->

Step 1: Open terminal in your project directory

Step 2: cd android

Step 3: Run ".\gradlew signingReport"

Done!

Body:
When I use the command:

C:\>keytool -list -alias androiddebugkey
            -keystore .android\debug.keystore
            -storepass android -keypass android

I get this error:

'keytool' is not recognized as an internal or external command, operable program or batch file.

I'm not able to get the certificate fingerprint(MD5) on my computer.

I have ensured that the keystore file is present in the appropriate location.

Any help?


问:
can someone tell me what dose it mean 4/ 32768.0
Am using arduino nano 33 Ble and am using the Lib  Arduino_LSM9DS1
am trying to understand the equation but i dont get it

the say data[0]*4/32768 wher the lsb 32768.
it should be a 16 bit rigester where the lsb should 2^16 = 65536.  or hier they use -+ 32768 ?
and what exactly 4 ? why the use this rang not a an 8 or 16 ?

can somone explin it to me ?
and how exactly get the acceleration and in which unit ?

```<code>int LSM9DS1Class::readAcceleration(float& x, float& y, float& z)
{
  int16_t data[3];

  if (!readRegisters(LSM9DS1_ADDRESS, LSM9DS1_OUT_X_XL, (uint8_t*)data, sizeof(data))) {
    x = NAN;
    y = NAN;
    z = NAN;

    return 0;
  }

  x = data[0] * 4.0 / 32768.0;
  y = data[1] * 4.0 / 32768.0;
  z = data[2] * 4.0 / 32768.0;

  return 1;
}
</code>```

答:
The documentation states that:

Accelerometer range is set at [-4,+4]g -/+0.122 mg

So, the value returned by the function readAcceleration is in the range [-4,4], representing -4g to 4g

g is the gravitational acceleration = 9.81 m/s2

The code you're showing is the implementation of the function readAcceleration. As I understand it, the raw acceleration data represented as a 16-bit signed integer (between −32,768 to 32,767), which is then normalized (divided by 32,768) and multiplied by 4 to put in the correct range of [-4,4].

Body:
Am using arduino nano 33 Ble and am using the Lib  Arduino_LSM9DS1
am trying to understand the equation but i dont get it

the say data[0]*4/32768 wher the lsb 32768.
it should be a 16 bit rigester where the lsb should 2^16 = 65536.  or hier they use -+ 32768 ?
and what exactly 4 ? why the use this rang not a an 8 or 16 ?

can somone explin it to me ?
and how exactly get the acceleration and in which unit ?

int LSM9DS1Class::readAcceleration(float& x, float& y, float& z)
{
  int16_t data[3];

  if (!readRegisters(LSM9DS1_ADDRESS, LSM9DS1_OUT_X_XL, (uint8_t*)data, sizeof(data))) {
    x = NAN;
    y = NAN;
    z = NAN;

    return 0;
  }

  x = data[0] * 4.0 / 32768.0;
  y = data[1] * 4.0 / 32768.0;
  z = data[2] * 4.0 / 32768.0;

  return 1;
}


问:
python choose random word from list
I am working on a project where I want a program that makes a string containing 5 random words from a list. The list contains 5 words and I want all possible combinations where only one word from the list can be used once per string.</p>
```<code>import time
import random

lista = ["w1", "w2", "w3", "Vickpix", "siplse"]

database = []

count = 0

while True:
    nu = random.choice(lista) + random.choice(lista) + random.choice(lista) + random.choice(lista) + random.choice(lista)
    if nu in database:
        pass
    else:
        count += 1
        print(count)
        database.insert(1, nu)
</code>```

答:
random.sample doc</p>
```<code>import time
import random

lista = ["w1", "w2", "w3", "Vickpix", "siplse"]

database = []

count = 0

while True:
    nu = random.sample(lista, 5)
    if nu in database:
        pass
    else:
        count += 1
        print(count)
        database.insert(1, nu)
</code>```

Title: python choose random word from list

Body:
I am working on a project where I want a program that makes a string containing 5 random words from a list. The list contains 5 words and I want all possible combinations where only one word from the list can be used once per string.

import time
import random

lista = ["w1", "w2", "w3", "Vickpix", "siplse"]

database = []

count = 0

while True:
    nu = random.choice(lista) + random.choice(lista) + random.choice(lista) + random.choice(lista) + random.choice(lista)
    if nu in database:
        pass
    else:
        count += 1
        print(count)
        database.insert(1, nu)

Body:
random.sample doc

import time
import random

lista = ["w1", "w2", "w3", "Vickpix", "siplse"]

database = []

count = 0

while True:
    nu = random.sample(lista, 5)
    if nu in database:
        pass
    else:
        count += 1
        print(count)
        database.insert(1, nu)


问:
Django template doesn't display the model items
sorry, I'm very new as a member (and as developer too). I've recently started to work with Django, and I'm trying to display on a page, a list of articles with some elements (title, image, created_at, content), already done in a model.

The views, the template and the path (urls) were  bilt too. But when I Run the server and open the browser it only displays the title I passed as the render parameter in the view, not the object (articles = Article.objects.all()), created in the view.

blog/models.py

```<code>from email.mime import image
from email.policy import default
from tabnanny import verbose
from turtle import update
from unicodedata import category
from venv import create
from django.db import models
from ckeditor.fields import RichTextField
from django.contrib.auth.models import User

# Create your models here.
class Category(models.Model):
    name = models.CharField(max_length=100, verbose_name='name')
    description = models.CharField(max_length=250, verbose_name='description')
    create_at = models.DateTimeField(auto_now_add=True, verbose_name='created_at')

    class Meta:
        verbose_name = 'Category'
        verbose_name_plural= 'Categories'

    def __str__(self):
        return self.name

class Article(models.Model):
    title= models.CharField(max_length=150, verbose_name="title")
    content= RichTextField(verbose_name='Content')
    image= models.ImageField(default='null', verbose_name="Image")
    public = models.BooleanField(verbose_name="Public?")
    user= models.ForeignKey(User, verbose_name="User", on_delete=models.CASCADE )
    categories = models.ManyToManyField(Category, verbose_name='Category',  blank=True)
    create_at= models.DateTimeField(auto_now_add=True, verbose_name="Created at")
    update_at= models.DateTimeField(auto_now=True, verbose_name="update at")

    class Meta:
        verbose_name = 'Article'
        verbose_name_plural= 'Articles'

    def __str__(self):
        return self.title
</code>```

blog/views.py

```<code>from django.shortcuts import render
from blog.models import Article, Category

# Create your views here.

def list(request):
    articles = Article.objects.all()

    return render(request, 'articles/list.html', {
         'title' : 'Articles',
         'articles': articles
      } )
</code>```

blog/list.html

```<code>  {% extends 'layouts/layout.html' %}

    {% block title  %}
        {{title}}
    {% endblock  %}
    {% block content  %}
        <h1 class= "title">{{title}}</h1>
        {% for article in articles %}
                <article class="article-item">
                    {% if article.image != 'null' and article.image|length >= 1 %}
                        <div class="image ">
                            <img src="{{article.image.url}}" />
                        </div>
                    {% endif %}
                    <div class="data">
                        <h2>
                            {{article.title}}
                        </h2>
                        <span class="date">{{article.create_at}}</span>
                         <p>{{article.content|safe}} </p>
                    </div>
                    <div class="clearfix"></div>
                </article>
        {%endfor%}

     {% endblock  %}
</code>```

Any help will be very appreciated

答: It looks like the whole block content is not rendered - Do you have a {% block content %} in the layout.html? You can check in your browser if the source code contains the html of the content block and just the tags are missing</p>

Body:
sorry, I'm very new as a member (and as developer too). I've recently started to work with Django, and I'm trying to display on a page, a list of articles with some elements (title, image, created_at, content), already done in a model.

The views, the template and the path (urls) were  bilt too. But when I Run the server and open the browser it only displays the title I passed as the render parameter in the view, not the object (articles = Article.objects.all()), created in the view.

blog/models.py

from email.mime import image
from email.policy import default
from tabnanny import verbose
from turtle import update
from unicodedata import category
from venv import create
from django.db import models
from ckeditor.fields import RichTextField
from django.contrib.auth.models import User

# Create your models here.
class Category(models.Model):
    name = models.CharField(max_length=100, verbose_name='name')
    description = models.CharField(max_length=250, verbose_name='description')
    create_at = models.DateTimeField(auto_now_add=True, verbose_name='created_at')

    class Meta:
        verbose_name = 'Category'
        verbose_name_plural= 'Categories'

    def __str__(self):
        return self.name

class Article(models.Model):
    title= models.CharField(max_length=150, verbose_name="title")
    content= RichTextField(verbose_name='Content')
    image= models.ImageField(default='null', verbose_name="Image")
    public = models.BooleanField(verbose_name="Public?")
    user= models.ForeignKey(User, verbose_name="User", on_delete=models.CASCADE )
    categories = models.ManyToManyField(Category, verbose_name='Category',  blank=True)
    create_at= models.DateTimeField(auto_now_add=True, verbose_name="Created at")
    update_at= models.DateTimeField(auto_now=True, verbose_name="update at")

    class Meta:
        verbose_name = 'Article'
        verbose_name_plural= 'Articles'

    def __str__(self):
        return self.title

blog/views.py

from django.shortcuts import render
from blog.models import Article, Category

# Create your views here.

def list(request):
    articles = Article.objects.all()

    return render(request, 'articles/list.html', {
         'title' : 'Articles',
         'articles': articles
      } )

blog/list.html

  {% extends 'layouts/layout.html' %}

    {% block title  %}
        {{title}}
    {% endblock  %}
    {% block content  %}

{{title}}

        {% for article in articles %}

                    {% if article.image != 'null' and article.image|length >= 1 %}

                    {% endif %}

                            {{article.title}}

                        {{article.create_at}}

{{article.content|safe}}

        {%endfor%}

     {% endblock  %}

Any help will be very appreciated


问:
Lookahead for "=>" token with crate syn
I'm working on a little domain-specific language with proc-macros and syn, and there I want to parse a sequence of operators on the form

 lhs + rsh => res
 lhs - rsh => res
```
<p>or</p>
<pre class="lang-rust prettyprint-override"><code> lhs += rsh
 lhs -= rsh
</code>```

and such.

I'm doing this using the syn crate, implementing Parser for the various structures I need. My thought was that I could parse these using a look-ahead after the first three tokens, with something like this:

let lookahead = input.lookahead1();

let lhs = input.parse()?;
let op = input.parse()?;
let rhs = input.parse()?;

// now, conditionally parse the res part of an operator
let res = if lookahead.peek(syn::token::FatArrow) {
    input.parse::<syn::token::FatArrow>()?;
    Some(input.parse()?)
} else { None };
```
<p>The problem is that while <code>syn::token::FatArrow</code> is the token for <code>=></code> when invoking <code>parse</code>, it doesn't seem to be when invoking <code>peek</code>.</p>
<pre class="lang-rust prettyprint-override"><code>// This says false
println!("do we see =>? {}", lookahead.peek(syn::token::FatArrow));
// this also says false
println!("do we see =>? {}", lookahead.peek(Token![=>]));
</code>```

The parsing works fine, but if I can't look ahead, then I can't distinguish between the two cases. (Well, I can by forking the input stream and trying both rules, then replacing the stream with the one that worked, but that seems a bit dramatic when a peak at the next token, if only I knew how to, would solve the problem).

What am I doing wrong here? Do I need to call peek with some other argument to match the token =>?

答:
There is a significance to when the Lookahead1 is created: it points to the location where the cursor was at the call to lookahead1(). Lookahead1 is meant to use when you have a list of possible values, and you want to provide a nice error message when the value is invalid, listing all possible values. If you just want to peek the next token, use ParseBuffer::peek():

let res = if input.peek(syn::token::FatArrow) {
    input.parse::<syn::token::FatArrow>()?;
    Some(input.parse()?)
} else { None };
```

Title: Lookahead for "=>" token with crate syn

Body:
I'm working on a little domain-specific language with proc-macros and syn, and there I want to parse a sequence of operators on the form

 lhs + rsh => res
 lhs - rsh => res

or

 lhs += rsh
 lhs -= rsh

and such.

I'm doing this using the syn crate, implementing Parser for the various structures I need. My thought was that I could parse these using a look-ahead after the first three tokens, with something like this:

let lookahead = input.lookahead1();

let lhs = input.parse()?;
let op = input.parse()?;
let rhs = input.parse()?;

// now, conditionally parse the res part of an operator
let res = if lookahead.peek(syn::token::FatArrow) {
    input.parse::<syn::token::FatArrow>()?;
    Some(input.parse()?)
} else { None };

The problem is that while syn::token::FatArrow is the token for => when invoking parse, it doesn't seem to be when invoking peek.

// This says false
println!("do we see =>? {}", lookahead.peek(syn::token::FatArrow));
// this also says false
println!("do we see =>? {}", lookahead.peek(Token![=>]));

The parsing works fine, but if I can't look ahead, then I can't distinguish between the two cases. (Well, I can by forking the input stream and trying both rules, then replacing the stream with the one that worked, but that seems a bit dramatic when a peak at the next token, if only I knew how to, would solve the problem).

What am I doing wrong here? Do I need to call peek with some other argument to match the token =>?


问:
UINotificationFeedbackGenerator in VIPER?
This is a kind of question regarding best practice.

I am using VIPER architecture in my iOS project. I use haptic feedback for some use cases. Where would be the best place to invoke UINotificationFeedbackGenerator in VIPER? I believe it is View.

答:
You should place it in presenter , why ?

View => It's not a view

Interactor => It doesn't involve intercalation with data

Entity => It's not a model

Router => It's not used to navigate to other pages

you can learn more about that architecture Here


问:
Rails friendly_id gem not working with link_to helpers?
I’ve set the friendly_id gem up, and generated slugs for my model.

The slugs are all shown in my DB column, and if I run Event.friendly.find('my-event-name') in the console, it works perfectly.

My URL’s are still showing as organisation/1/events/1 though, when I check the result of the following link_to:-

```<code><%= link_to organisation_event_path(event.organisation.id, event.id), class: 'btn btn-primary' do %>
</code>```

I’ve also added

```<code>  extend FriendlyId
  friendly_id :title, use: :slugged
</code>```

to my model.

When I visit the URL manually, it works with the friendly id - so it seems to be just the link_to helper that isn't working.

Could possibly be related to some additional setup required for nested routes here - but I can’t seem to find anything when I search.

```<code>  resources :organisations do
    resources :events
  end
</code>```

答:
This is way more explicit then you need to be. As long as you're following the conventions you can let them do the work for you:

```<code><%= link_to [event.organisation, event], class: 'btn btn-primary do %>
  # ...
<% end %>
</code>```

Under the covers rails will look up the organisation_event_path helper (by looking at the model names) - and call its to_param method.

Body:
I’ve set the friendly_id gem up, and generated slugs for my model.

The slugs are all shown in my DB column, and if I run Event.friendly.find('my-event-name') in the console, it works perfectly.

My URL’s are still showing as organisation/1/events/1 though, when I check the result of the following link_to:-

<%= link_to organisation_event_path(event.organisation.id, event.id), class: 'btn btn-primary' do %>

I’ve also added

  extend FriendlyId
  friendly_id :title, use: :slugged

to my model.

When I visit the URL manually, it works with the friendly id - so it seems to be just the link_to helper that isn't working.

Could possibly be related to some additional setup required for nested routes here - but I can’t seem to find anything when I search.

  resources :organisations do
    resources :events
  end

Body:
This is way more explicit then you need to be. As long as you're following the conventions you can let them do the work for you:

<%= link_to [event.organisation, event], class: 'btn btn-primary do %>
  # ...
<% end %>

Under the covers rails will look up the organisation_event_path helper (by looking at the model names) - and call its to_param method.