问:
My Java program for removing special characters and white space from user input of name fails when I test it with spaces
I'm a student and am working on an assignment that has us trying a few techniques we haven't covered. Removing special characters and spaces from user input, I figured out how to remove the special characters but when I insert a space in my name when I try my program, my name is returned to me missing whatever letters were after the space. Like, "Pat ricia" becomes "Pat". I had to go with a different technique for removing special characters because "replaceAll" didn't work for me there, and it isn't working for me with removing white space. Can I have another set of eyes to tell me what I'm missing?</p>
```<code>package edu.gmc.Course_Project;

import java.util.Scanner;

public class Input_Name {

    public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);

    //asking for user input

    System.out.print("enter your name: ");
    String name = scan.next();

    //Java won't do all this at once (2 step process) so I'm converting the whole name to lower case first

    name=name.toLowerCase();

    //now to get the first character

    char first=name.charAt(0);

    //and changing it to upper case

    first=Character.toUpperCase(first);

    String newName="";
    newName+=first;

    //I'm not really sure about this part, but it has to do with the length...without it, my name was returned to me as "P"

    for(int i=1;i<name.length();i++)

    {
    //this part ignores anything other than A-Z or a-z...I had a different method earlier but I couldn't get it to work properly

    char ch=name.charAt(i);
        if(ch>='a' && ch<='z')
            {
                newName+=ch;
            }
        }

    //removing white spaces

    newName = newName.replaceAll("\\s+", "");

    //the program is complete, now what does it do?

    System.out.println("your name is "+newName);

    }
}
</code>```

答: The reason why your program was not working was because you was using String name = scan.next(); at the very start of your program, this command will store the next string inputted, and because there is a space it is simply storing the first string before the space, instead you need to use String name = scan.nextLine(); as it will store the entire line including white space and additional strings,

Body:
I'm a student and am working on an assignment that has us trying a few techniques we haven't covered. Removing special characters and spaces from user input, I figured out how to remove the special characters but when I insert a space in my name when I try my program, my name is returned to me missing whatever letters were after the space. Like, "Pat ricia" becomes "Pat". I had to go with a different technique for removing special characters because "replaceAll" didn't work for me there, and it isn't working for me with removing white space. Can I have another set of eyes to tell me what I'm missing?

package edu.gmc.Course_Project;

import java.util.Scanner;

public class Input_Name {

    public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);

    //asking for user input

    System.out.print("enter your name: ");
    String name = scan.next();

    //Java won't do all this at once (2 step process) so I'm converting the whole name to lower case first

    name=name.toLowerCase();

    //now to get the first character

    char first=name.charAt(0);

    //and changing it to upper case

    first=Character.toUpperCase(first);

    String newName="";
    newName+=first;

    //I'm not really sure about this part, but it has to do with the length...without it, my name was returned to me as "P"

    for(int i=1;i<name.length();i++)

    {
    //this part ignores anything other than A-Z or a-z...I had a different method earlier but I couldn't get it to work properly

    char ch=name.charAt(i);
        if(ch>='a' && ch<='z')
            {
                newName+=ch;
            }
        }

    //removing white spaces

    newName = newName.replaceAll("\\s+", "");

    //the program is complete, now what does it do?

    System.out.println("your name is "+newName);

    }
}


来源: stackexchange

问:
Android: compatibility issues when publishing
I published an application at Android market but the Android market is stating that my application is not compatible with most of the devices. It gave me a list of at least 7 to 9 devices with which my application is not compatible with. ALTHOUGH I have tried my application with some of the devices that are mentioned in the uncompatible devices list and it worked fine there.. Does anyone has a clue about what could be the issue. ??

Thanks alot

答: Check your manifest for things that limit the device range - screen size, openGL requirements, minSDK version... The publisher has at the bottom of the details area an area that shows what devices you can filter, make sure you didn't invert it or something (if you can do that.)</p>

ContentLicense: CC BY-SA 3.0


问:
How to run react native 0.63 applications in XCode 13?

I'm mantaining a React Native app written with v0.63.2 of the framework.

In order to develop for iOS 15 I have upgraded XCode to v13 and I saw that the xcrun was deleted (it was already deprecated in XCode 12).
That command was needed by react-native to start by app for local development. As far as I know, to work with iOS 15 I'll have to upgrade to react-native 0.66 and I can't do that right now.
Here I have two questions:

Is there a way to develop with XCode 13 using a version of react-native minor than 0.66 (please note that upgrading to 0.64 or 0.65 is still NOT an option for me)?

Is there a fix / equivalent about the xcrun command ?

答:
There was an issue on the build for Xcode 13 here https://github.com/facebook/react-native/issues/31733

Fix:
Replace this line (in the project.pbxproj):

```<code>"\"$(TOOLCHAIN_DIR)/usr/lib/swift-5.0/$(PLATFORM_NAME)\"",
</code>```

by this one:

```<code>"\"$(SDKROOT)/usr/lib/swift\"",
</code>```

ContentLicense: CC BY-SA 4.0

Body:
There was an issue on the build for Xcode 13 here https://github.com/facebook/react-native/issues/31733

Fix:
Replace this line (in the project.pbxproj):

"\"$(TOOLCHAIN_DIR)/usr/lib/swift-5.0/$(PLATFORM_NAME)\"",

by this one:

"\"$(SDKROOT)/usr/lib/swift\"",


问:
Troubles taking a matrix from user's input, defining it as a list of lists
I want to make a program that takes inputs from the user to build an n x n matrix.

This is what I tried to do:

```<code>dim=int(input("Dimension of your matrix? "))
row=[]
matrix=[]
for i in range(dim):
    for j in range(dim):
        inp=float(input("Insert element with indeces: "+str(i+1)+" "+str(j+1)+" :"))
        row.append(inp)
    print(row)
    matrix.append(row)
    row.clear()
print("Your matrix is:")
print(matrix)
</code>```

And although the printed rows are fine, the final matrix I print consists only of empty lists. It looks something like the following:

```<code>[[],[],[]]
</code>```

Why is this happening?

答:
You are using a shallow copy when you append a row in your matrix. So it just keep the address of your row, and when you clean the row at the end of your loop the amounts in your matrix is also cleaned. You need to use a deep copy. So, use this code, the when you are appending a new row:

```<code> matrix.append(row.copy())
</code>```

The complete program will be:

```<code>dim=int(input("Dimension of your matrix? "))
row=[]
matrix=[]
for i in range(dim):
    for j in range(dim):
        inp=float(input("Insert element with indeces: "+str(i+1)+" "+str(j+1)+" :"))
        row.append(inp)
    print(row)
    matrix.append(row.copy())
    row.clear()
print("Your matrix is:")
print(matrix)
</code>```

Body:
I want to make a program that takes inputs from the user to build an n x n matrix.

This is what I tried to do:

dim=int(input("Dimension of your matrix? "))
row=[]
matrix=[]
for i in range(dim):
    for j in range(dim):
        inp=float(input("Insert element with indeces: "+str(i+1)+" "+str(j+1)+" :"))
        row.append(inp)
    print(row)
    matrix.append(row)
    row.clear()
print("Your matrix is:")
print(matrix)

And although the printed rows are fine, the final matrix I print consists only of empty lists. It looks something like the following:

[[],[],[]]

Why is this happening?

Body:
You are using a shallow copy when you append a row in your matrix. So it just keep the address of your row, and when you clean the row at the end of your loop the amounts in your matrix is also cleaned. You need to use a deep copy. So, use this code, the when you are appending a new row:

 matrix.append(row.copy())

The complete program will be:

dim=int(input("Dimension of your matrix? "))
row=[]
matrix=[]
for i in range(dim):
    for j in range(dim):
        inp=float(input("Insert element with indeces: "+str(i+1)+" "+str(j+1)+" :"))
        row.append(inp)
    print(row)
    matrix.append(row.copy())
    row.clear()
print("Your matrix is:")
print(matrix)


问:
NodeJS email-templates i18n localization
I have an issue with the localization of the pug templates combined with i18n. The language keeps rolling back to "en" language, but I've set the locale: 'sl' in the send() function, this is from the documentation of the email-templates.

Here is my code in typescript:

```<code>import * as path from 'path';
import Email = require("email-templates");
import { transporter } from '../mailerConnection';
import { I18n } from 'i18n';

export async function sendOutActivationEmail() {

  const i18n = new I18n();
  i18n.configure({
    locales: ['en', 'sl'],
    directory: path.join(__dirname, '../../locales'),
    register: global
  });

  const email = new Email({
    message: {
      from: '"test" <noreplay@test.com>'
    },
    // uncomment below to send emails in development/test env:
    //send: true,
    transport: transporter,
    i18n: i18n
  });

  email
    .send({
      template: path.join(__dirname, '../templates', 'activation'),
      message: {
        to: 'test@gmail.com'
      },
      locals: {
        locale: 'sl',
        name: 'Test'
      }
    })
    .then(console.log)
    .catch(console.error);

}
sendOutActivationEmail().catch(console.error);
</code>```

Here is html.pug template:

```<code>p= __('message')
</code>```

Here is en.json:

```<code>{
    "message": "message1"
}
</code>```

Here is sl.json:

```<code>{
    "message": "messageSLO"
}
</code>```

Here is the link to email-templates localization documentation: https://www.npmjs.com/package/email-templates#localization

What am I doing wrong that the functions doesn't switch to "sl" language? Thanks...

答:
email-templates does not seem to document how the i18n object needs to look like, but probably you need to pass there somewhere the appropriate translations…

Alternatively, this looks more promising: https://dev.to/adrai/how-does-server-side-internationalization-i18n-look-like-5f4c#email

Body:
I have an issue with the localization of the pug templates combined with i18n. The language keeps rolling back to "en" language, but I've set the locale: 'sl' in the send() function, this is from the documentation of the email-templates.

Here is my code in typescript:

import * as path from 'path';
import Email = require("email-templates");
import { transporter } from '../mailerConnection';
import { I18n } from 'i18n';

export async function sendOutActivationEmail() {

  const i18n = new I18n();
  i18n.configure({
    locales: ['en', 'sl'],
    directory: path.join(__dirname, '../../locales'),
    register: global
  });

  const email = new Email({
    message: {
      from: '"test" <noreplay@test.com>'
    },
    // uncomment below to send emails in development/test env:
    //send: true,
    transport: transporter,
    i18n: i18n
  });

  email
    .send({
      template: path.join(__dirname, '../templates', 'activation'),
      message: {
        to: 'test@gmail.com'
      },
      locals: {
        locale: 'sl',
        name: 'Test'
      }
    })
    .then(console.log)
    .catch(console.error);

}
sendOutActivationEmail().catch(console.error);

Here is html.pug template:

p= __('message')

Here is en.json:

{
    "message": "message1"
}

Here is sl.json:

{
    "message": "messageSLO"
}

Here is the link to email-templates localization documentation: https://www.npmjs.com/package/email-templates#localization

What am I doing wrong that the functions doesn't switch to "sl" language? Thanks...


问:
CSS wrap text exactly to width
I'm using white-space:nowrap; to keep my text in one line. But the text is long and goes beyond the element. How to wrap the text exactly to the width of an element?

To understand more clearly what I mean, see this JSfiddle.

Update: another JSfiddle to show more clearly what I need.

答:
AS long as you've set the width of the element, just take the whitespace:no-wrap off, and it will wrap the text exactly to the width of the element.

edit

OK -- here's what you need:

```<code>div {
  background-color:#FF00FF;
  width:200px;
  overflow:hidden;
  height:1em;
}
</code>```

Title: CSS wrap text exactly to width

Body:
AS long as you've set the width of the element, just take the whitespace:no-wrap off, and it will wrap the text exactly to the width of the element.

edit

OK -- here's what you need:

div {
  background-color:#FF00FF;
  width:200px;
  overflow:hidden;
  height:1em;
}


问:
Regex does not return all the argument
I try to parse a expression like this with my regex:

```<code>FIRST SECOND ARG1=$value ARG2="with space"
</code>```

There can be any number of arguments.

example: HELLO VERSION MIN=$min MAX=$max USER="xxx" PASSWORD="yyy"

result: HELLO - VERSION - PASSWORD - "yyy"

desired result: HELLO - VERSION - MIN - $min - MAX - $max - USER - "xxx" - PASSWORD - "yyy"

My regex is ([\w\d]+) ([\w\d]+)(?: ([\w\d]+)=("[^"]*"|[^" ]*))*

However, I do not get all the arguments, but only the last back. How can I fix it? It is too much for a regex?

答:
You can match what's between quotes first, then the rest.

(["].*?["])|([[:alnum:]_\$]+)

Test here

Title: Regex does not return all the argument

Body:
I try to parse a expression like this with my regex:

FIRST SECOND ARG1=$value ARG2="with space"

There can be any number of arguments.

example: HELLO VERSION MIN=$min MAX=$max USER="xxx" PASSWORD="yyy"

result: HELLO - VERSION - PASSWORD - "yyy"

desired result: HELLO - VERSION - MIN - $min - MAX - $max - USER - "xxx" - PASSWORD - "yyy"

My regex is ([\w\d]+) ([\w\d]+)(?: ([\w\d]+)=("[^"]*"|[^" ]*))*

However, I do not get all the arguments, but only the last back. How can I fix it? It is too much for a regex?


问:
Embedded and Internal CSS not affecting my lists
I am trying to get it so that my ingredients list is green, my equipment is red and my method list is blue. I am trying to use all different types of css to achieve this. My external works fine as that is the red one but, my two types of internal don't seem to change the other lists.</p>
```<code><!DOCTYPE html>

<html>
 <head>
    <style>
     ol {color: blue;
         font-style: italic;
        }
    </style>
  <title>Emily's Cooking Page</title>
<link rel="stylesheet" href="demo1.css" />
 </head>

<body>
 <h1>Cooking for Students</h1>
  <p>This page will show you how to make basic <b>macaroni</b> with all shop bought ingredients & how to store it properly</p>

  <img src="macaroni.jpg" width="104" height="142">

 <table>
  <tr><td>prep: 5 minutes</td></tr>
  <tr><td>cook: 30 minutes</td></tr>
  <tr><td>difficulty: easy</td></tr>
  <tr><td>quantity made: 3 to 4 meals</td></tr>
 </table>

<h2>ingredients</h2>
 <p>all found in Morrisons supermarkets</p>
  <ul style="color:green;">
    <li>250g pasta</li>
    <li>300g cheese sauce</li>
  </ul>

<h2>equipment</h2>
  <ul>
    <li>saucepan</li>
    <li>wooden spoon</li>
    <li>oven with hob</li>
    <li>two to three tubs</li>
  </ul>

<h2>method</h2>
  <ol>
    <li>On oven, turn hob to high heat. Fill a large saucepan with water and place on hob, allow water to begin boiling.</li>
    <li>Once water is boiling, put all 250g of pasta into the saucepan and begin stirring with a wooden spoon.</li>
    <li>Boiling pasta for 20 minutes or until soft. Use a knife or fork to test how hard the pasta is.</li>
    <li>Take the saucepan off the hob and turn the hob down to a low heat. Using a sieve, drain all the water out of the saucepan and place pasta back into saucepan.</li>
    <li>Place saucepan back on the hob and add 300g of cheese sauce to saucepan.</li>
    <li>Mix the cheese sauce and pasta for 5 minutes</li>
    <li>Turn hob off. Spread the macaroni into two or three separate tubs and allow them to cool down. Alternatively, you can eat one serving straight after cooking.</li>
    <li>Once cooled down, place in fridge. To eat, place in microwave for 1 minute and a half, stir, then another minute (you can even add grated cheese on top after stirring).</li>
    <li>After two days, move tubs to the freezer, to de-frost, place tub back in fridge and allow for one day of defrosting in fridge before microwaving and serving.</li>
  </ol>

 <p>Other Recipes:</p>
  <a href="https://www.bbcgoodfood.com/recipes/best-ever-macaroni-cheese-recipe">BBC GoodFood Macaroni Recipe</a>
 <p></p>
  <a href="https://www.foodnetwork.ca/everyday-cooking/photos/best-macaroni-recipes/">Food Network Macaroni Recipes</a>
</body>
</html>
</code>```

答:
The following rule applies to all ordered lists.

```<code>ol {
  color: blue;
  font-style: italic;
}
</code>```

Therefore, all ol should have blue color.

The ingredients list is a ul and has the inline styling of green color:

```<code><ul style="color:green;">
  <li>250g pasta</li>
  <li>300g cheese sauce</li>
</ul>
</code>```

Following your way, in order to apply the red color to the equipment list you can write:

```<code><ul style="color: red">
  <li>saucepan</li>
  <li>wooden spoon</li>
  <li>oven with hob</li>
  <li>two to three tubs</li>
</ul>
</code>```

However, I would suggest to create three classes for each color.

For example,

```<code>.color-blue {
  color: blue;
}

.color-red {
  color: red;
}

.color-green {
  color: green;
}
</code>```
```<code><ul class="color-green;">
  <li>250g pasta</li>
  <li>300g cheese sauce</li>
</ul>

<ul class="color-red;">
  <li>saucepan</li>
  <li>wooden spoon</li>
  <li>oven with hob</li>
  <li>two to three tubs</li>
</ul>

<ol class="color-blue">
  <li>On oven, turn hob to high heat. Fill a large saucepan with water and place on hob, allow water to begin boiling.</li>
 ...
 ...
</ol>
</code>```

Body:
I am trying to get it so that my ingredients list is green, my equipment is red and my method list is blue. I am trying to use all different types of css to achieve this. My external works fine as that is the red one but, my two types of internal don't seem to change the other lists.

<!DOCTYPE html>

  <title>Emily's Cooking Page</title>
<link rel="stylesheet" href="demo1.css" />

Cooking for Students

This page will show you how to make basic macaroni with all shop bought ingredients & how to store it properly

prep: 5 minutes

cook: 30 minutes

difficulty: easy

quantity made: 3 to 4 meals

ingredients

all found in Morrisons supermarkets

250g pasta

300g cheese sauce

equipment

saucepan

wooden spoon

oven with hob

two to three tubs

method

On oven, turn hob to high heat. Fill a large saucepan with water and place on hob, allow water to begin boiling.

Once water is boiling, put all 250g of pasta into the saucepan and begin stirring with a wooden spoon.

Boiling pasta for 20 minutes or until soft. Use a knife or fork to test how hard the pasta is.

Take the saucepan off the hob and turn the hob down to a low heat. Using a sieve, drain all the water out of the saucepan and place pasta back into saucepan.

Place saucepan back on the hob and add 300g of cheese sauce to saucepan.

Mix the cheese sauce and pasta for 5 minutes

Turn hob off. Spread the macaroni into two or three separate tubs and allow them to cool down. Alternatively, you can eat one serving straight after cooking.

Once cooled down, place in fridge. To eat, place in microwave for 1 minute and a half, stir, then another minute (you can even add grated cheese on top after stirring).

After two days, move tubs to the freezer, to de-frost, place tub back in fridge and allow for one day of defrosting in fridge before microwaving and serving.

Other Recipes:

  BBC GoodFood Macaroni Recipe

  Food Network Macaroni Recipes

Body:
The following rule applies to all ordered lists.

ol {
  color: blue;
  font-style: italic;
}

Therefore, all ol should have blue color.

The ingredients list is a ul and has the inline styling of green color:

<ul style="color:green;">
  <li>250g pasta</li>
  <li>300g cheese sauce</li>
</ul>

Following your way, in order to apply the red color to the equipment list you can write:

<ul style="color: red">
  <li>saucepan</li>
  <li>wooden spoon</li>
  <li>oven with hob</li>
  <li>two to three tubs</li>
</ul>

However, I would suggest to create three classes for each color.

For example,

.color-blue {
  color: blue;
}

.color-red {
  color: red;
}

.color-green {
  color: green;
}

<ul class="color-green;">
  <li>250g pasta</li>
  <li>300g cheese sauce</li>
</ul>

<ul class="color-red;">
  <li>saucepan</li>
  <li>wooden spoon</li>
  <li>oven with hob</li>
  <li>two to three tubs</li>
</ul>

<ol class="color-blue">
  <li>On oven, turn hob to high heat. Fill a large saucepan with water and place on hob, allow water to begin boiling.</li>
 ...
 ...
</ol>


问:
Using 'sudo apt-get install build-essentials'
I was trying to use sudo apt-get install build-essentials to install the g++ compiler on my Ubuntu Linux box. But it gave me the following message:

Reading package lists... Done

Building dependency tree

     Reading state information... Done

E: Unable to locate package build-essentials

How do I fix this problem?

答:
Manifest for installing rust and build-essentials on ubuntu 20.04.03

```<code>rustup self uninstall
apt-get update
sudo add-apt-repository "deb http://archive.ubuntu.com/ubuntu $(lsb_release -sc) main universe"
apt-get -u dist-upgrade
apt install aptitude
sudo aptitude install libc6=2.31-0ubuntu9
sudo aptitude install build-essential
apt-get update
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- --default-toolchain none -y
rustup toolchain install nightly --allow-downgrade --profile minimal --component clippy
rustup default stable
rustup update nightly
rustup update stable
rustup target add wasm32-unknown-unknown --toolchain nightly
sudo apt install -y cmake pkg-config libssl-dev git gcc build-essential clang libclang-dev
rustc --version
source $HOME/.cargo/env
</code>```

#No tested on me Fast Installation: Install all the required dependencies with a single command. (Be patient, this can take up to
30 minutes)

```<code>curl https://getsubstrate.io -sSf | bash -s -- --fast
</code>```

Finally step test:

https://doc.rust-lang.org/cargo/getting-started/first-steps.html

#ArmanRiazi.Blockchain#Substrate#Dr.GavinWood

Body:
Manifest for installing rust and build-essentials on ubuntu 20.04.03

rustup self uninstall
apt-get update
sudo add-apt-repository "deb http://archive.ubuntu.com/ubuntu $(lsb_release -sc) main universe"
apt-get -u dist-upgrade
apt install aptitude
sudo aptitude install libc6=2.31-0ubuntu9
sudo aptitude install build-essential
apt-get update
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- --default-toolchain none -y
rustup toolchain install nightly --allow-downgrade --profile minimal --component clippy
rustup default stable
rustup update nightly
rustup update stable
rustup target add wasm32-unknown-unknown --toolchain nightly
sudo apt install -y cmake pkg-config libssl-dev git gcc build-essential clang libclang-dev
rustc --version
source $HOME/.cargo/env

#No tested on me Fast Installation: Install all the required dependencies with a single command. (Be patient, this can take up to
30 minutes)

curl https://getsubstrate.io -sSf | bash -s -- --fast

Finally step test:

https://doc.rust-lang.org/cargo/getting-started/first-steps.html

#ArmanRiazi.Blockchain#Substrate#Dr.GavinWood


问:
Generically implementing a trait for all concrete types implementing another trait
I'm pretty new to rust, so this might be a stupid question with an obvious answer, but I don't know the answer yet. I've just read the book and then decided to implement some algorithms I'm familiar with, to get a feeling for the language. That, however, took me down a dark path to a side project that went a little deeper into the language than I had planned for...

Anyway, I'm now playing around with some code for working with indices and offsets in some algorithms in a type-safe way. I have indices into different arrays and strings and want to prevent using an index from one array to be used into another and things like that. So, I have defined new types for different kinds of indices, those with different domains, and for offsets between them. I don't allow comparisons between domains, I can subtract indices to get an offset and I can add and subtract indices and offsets and stuff like that. Further, I can define which types of objects indices can subscript, so an index into a string can only index a string and not, say, a suffix array, where another type is necessary.

This mostly works. I have a bunch of macros for defining what objects are allowed to do. For example, with this

def_offset!(Offset);
def_idx!(
    Idx
    with offset Offset
    with sub [
        Vec<T>[Idx] => T,
        [T][Idx] => T
    ]
);
```
<p>I define a generic <code>Offset</code> that you can do arithmics on but nothing else, and then an index type <code>Idx</code> that can do arithmics with <code>Offset</code> and index vectors and slices. The arithmetic for indices looks like this right now, but I'm not done experimenting with it</p>
<pre class="lang-rust prettyprint-override"><code>macro_rules! def_idx_ops {
    ($idx:ident with offset $offset:ident) => {
        // You can add an index and an offset
        def_op!($idx + $offset => $idx);
        def_op!($offset + $idx => $idx);
        def_op!($idx += $offset);

        // You can subtract an index and an offset
        def_op!($idx - $offset => $idx);
        def_op!($idx -= $offset);

        // You can subtract two indices, but you can't add
        // them (adding indices do not usually make sense)
        def_op!($idx - $idx => $offset);

        // You can add scalars to indices.
        def_op!($idx + usize => $idx);
        def_op!(usize + $idx => $idx);
        def_op!($idx += usize);

        // You can subtract scalars from indices.
        def_op!($idx - usize => $idx);
        def_op!(usize - $idx => $idx);
        def_op!($idx -= usize);
    };
}
</code>```

where the def_op! macro implements the appropriate trait for the types involved in the operator.

There is more code generation going on here than I like, but I couldn't figure out how to write generic code any other way. But maybe I will after this question.

See, now I got to implementing ranges over these types. They come out of the box if you just want a range

```<code>let r = Idx(0)..Idx(10)
</code>```

but you can't iterate over them. For that, you need to implement some traits. With the code below, it works for the type Idx:

// Trait for implementing iteration through i..j ranges for Idx.
// NB: This requires nightly; the iter::Step trait is unstable.
impl std::iter::Step for Idx {
    fn steps_between(start: &Self, end: &Self) -> Option<usize> {
        match (start.0, end.0) {
            (i, j) if i > j => None,
            (i, j) => Some(j - i),
        }
    }
    fn forward_checked(start: Self, count: usize) -> Option<Self> {
        Some(start + count) // Ignoring overflow here...
    }
    fn backward_checked(start: Self, count: usize) -> Option<Self> {
        match start.0 {
            i if i < count => None,
            _ => Some(start - count),
        }
    }
}
```
<p>But it only works for the concrete type <code>Idx</code>. If I try to make a generic implementation, I run into all kinds of trouble.</p>
<p>This is my current attempt, but it works as little as the others I have made:</p>
<pre class="lang-rust prettyprint-override"><code>trait RangeIndex<T>: NumWrapper<T> + std::ops::Add<T> + std::ops::Sub<T>
where
    T: num::traits::NumCast,
{
}

impl<Idx> std::iter::Step for Idx
where
    Idx: RangeIndex<usize>,
{
    fn steps_between(start: &Self, end: &Self) -> Option<usize> {
        match (start.wrapped(), end.wrapped()) {
            (i, j) if i > j => None,
            (i, j) => Some(j - i),
        }
    }
    fn forward_checked(start: Self, count: usize) -> Option<Self> {
        Some(start + count) // Ignoring overflow here...
    }
    fn backward_checked(start: Self, count: usize) -> Option<Self> {
        match start.wrapped() {
            i if i < count => None,
            _ => Some(start - count),
        }
    }
}
</code>```

The RangeIndex<T> trait puts the constraints I need on the index type, and NumWrapper is a trait for the numbers I'm wrapping in indices and offsets.

pub trait Wrapper<Wrapped> {
    fn wrapped(&self) -> Wrapped;
}

pub trait NumWrapper<Wrapped>:
    Wrapper<Wrapped> + std::cmp::PartialEq + std::cmp::PartialOrd
where
    Wrapped: num::traits::NumCast,
{
    fn cast_to_wrapped<T: num::traits::NumCast>(val: T) -> Wrapped {
        num::cast(val).unwrap()
    }
}
```
<p>(There is a little more to the wrapped objects, but this is the only relevant part for treating them as numbers).</p>
<p>This generic code does not work. The compiler suggests that I make the trait <code>dyn</code> but I assure you that I do not want to do that. I don't want any dynamic dispatch or polymorphism at all. I have concrete types; I want implementations for those. Nothing more and nothing less.</p>
<p>It is a small matter to just generate the code with macros, like I have with the operators. But I am reinventing generic code now, and that is deeply unsatisfying. I feel the same way about generating the operators instead of having code for traits and then just implementing the appropriate trait for each type.</p>
<p>Is it impossible to say "for any type that implements this particular trait, give me a concrete implementation of this trait like this"? It is really all I want. For any <code>Idx</code> that implements these traits, give me this <code>std::iter::Step</code>.</p>
<p>And if I can get that, I would love to do the same with the operators</p>
<pre class="lang-rust prettyprint-override"><code>impl<LHS, RHS, RES> std::ops::Add<RHS> for LHS {
    where //"some constraint involving both LHS and RHS and RES"
          Constraint<LHS,RHS,RES> // yeah, might not be able to do this
    type Output = RES;
    fn add(self, rhs: $rhs) -> Self::Output {
        RES(RES::cast_to_wrapped(self.wrapped()) +
            RES::cast_to_wrapped(rhs.wrapped()))
    }
}
</code>```

One can dream, at least.

Anyway, I don't mind generating the operators, but I see it as a problem if I have to give up on generic code that works with these types. If I can't even run through a range, then this project is going to die pretty soon. Using macros for every generic function just isn't an attractive idea. (Well, I can still write generic functions, I just cannot implement traits, so it is not all that bad, but it still is pretty bad).

Really, what I want to tell Rust is that "for all types that implement the following traits", "give me an instance of this generic code". Exactly what I can get with macros, I suppose, but using generics that were made for this purpose instead.

Surely there must be some well know trick to generically implementing a trait without resorting to dyn?

UPDATE

I've put a related exampled on playground. The full example where I need the ranges is a bit too long, but I think the smaller example hits the same issue. There, I have a trait for adding wrapped numbers

// Local trait for adding ... a substitute for the range code I need
trait MyAdd<Rhs> {
    type Res;
    fn my_add(self, rhs: Rhs) -> Self::Res;
}
```

I can implement std::ops::Add just from this interface, but no matter how I try, I cannot do it without explicitly implementing that trait for each type I define. There are a couple of examples of my attempts, but needless to say, they do not work.

Playground

答:
I fought it a bit more, and I think I might have a solution. Since I can't implement a trait for general types, but only types in my own crate, that is what I have to do. I didn't want to, because I wanted to use the types to define different operators, but I figured that there would be a way around that.

Here is what I have right now. I define a type to contain information about the wrapped objects I will hold. Then I am going to wrap objects, and use instances of this type as tags, to give my wrappers different underlying types, and that way define operators.

// Any of the wrapped types should have this.
pub trait TypeInfo: Copy {
    type WrappedType: Copy + num::PrimInt;
}
```
<p>This just tells me what the underlying type is, when I get to that; that turns out to be important.</p>
<p>Then I define a trait for wrapper objects. They have TypeInfo to make macros and meta-programming easier, but they are not the same as the TypeInfo objects. They implement it, and they contain one.</p>
<pre class="lang-rust prettyprint-override"><code>// A few places, this is useful for meta-programming. Mostly because I can't
// get the From<> trait to work half the time...
pub trait WrapInfo: TypeInfo {
    fn wrapped(&self) -> Self::WrappedType;
    fn wrapped_as<T: num::PrimInt + Copy>(&self) -> T {
        num::cast::<Self::WrappedType, T>(self.wrapped()).unwrap()
    }
}
</code>```

I also implement this trait for primitive integers, because otherwise I have to do a lot of case-analysis when I write macros later. If all the objects I implement operators on behave the same, then I don't need to worry about that.

// Type info for primitive types; we will wrap those for specific
// type-safe types. Having the traits for all numbers makes meta-programming
// a lot easier. Numerical types just wrap themselves.
impl<T> TypeInfo for T
where
    T: Copy + num::PrimInt,
{
    type WrappedType = T;
}
impl<T> WrapInfo for T
where
    T: Copy + num::PrimInt,
{
    fn wrapped(&self) -> Self::WrappedType {
        *self
    }
}
```
<p>My wrapper looks like this:</p>
<pre class="lang-rust prettyprint-override"><code>#[derive(Debug, Clone, Copy)]
pub struct Wrapper<_Tag>(pub _Tag::WrappedType)
where
    _Tag: TypeInfo;

impl<_Tag> TypeInfo for Wrapper<_Tag>
where
    _Tag: TypeInfo,
{
    type WrappedType = _Tag::WrappedType;
}
impl<_Tag> WrapInfo for Wrapper<_Tag>
where
    _Tag: TypeInfo,
{
    fn wrapped(&self) -> _Tag::WrappedType {
        self.0
    }
}
</code>```

It is parameterised with a _Tag of type TypeInfo, but it doesn't hold one of those types. It holds a value of _Tag::WrappedType. That way, I don't have to dereference through layers of nesting but always have the type as wrapped.0, but I still get the type safety I am going for. When I have two Wrapper<_Tag> objects with different _Tag, they are different types.

I add some other useful traits, and I am sure that there are more worth adding...

impl<_Tag> std::fmt::Display for Wrapper<_Tag>
where
    _Tag: TypeInfo,
    _Tag::WrappedType: std::fmt::Display,
{
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

// Get an ordering on it
impl<_Tag> std::cmp::PartialEq for Wrapper<_Tag>
where
    _Tag: TypeInfo,
{
    fn eq(&self, other: &Wrapper<_Tag>) -> bool {
        self.0 == other.0
    }
}
impl<_Tag> std::cmp::PartialOrd for Wrapper<_Tag>
where
    _Tag: TypeInfo,
{
    fn partial_cmp(&self, other: &Wrapper<_Tag>) -> Option<std::cmp::Ordering> {
        self.0.partial_cmp(&other.0)
    }
}

impl<T, _Tag> From<T> for Wrapper<_Tag>
where
    T: num::PrimInt,
    _Tag: TypeInfo,
{
    fn from(t: T) -> Self {
        Wrapper::<_Tag>(num::cast::<T, _Tag::WrappedType>(t).unwrap())
    }
}
```
<p>Now, for the range iterator, I can just implement it on <code>Wrapper</code>:</p>
<pre class="lang-rust prettyprint-override"><code>impl<_Tag> std::iter::Step for Wrapper<_Tag>
where
    _Tag: TypeInfo,
{
    fn steps_between(start: &Self, end: &Self) -> Option<usize> {
        match (start.wrapped(), end.wrapped()) {
            (i, j) if i > j => None,
            (i, j) => num::cast(j - i),
        }
    }
    fn forward_checked(start: Self, count: usize) -> Option<Self> {
        let count = num::cast::<usize, _Tag::WrappedType>(count)?;
        Some(Wrapper::<_Tag>(start.wrapped() + count))
    }
    fn backward_checked(start: Self, count: usize) -> Option<Self> {
        let count = num::cast::<usize, _Tag::WrappedType>(count)?;
        Some(Wrapper::<_Tag>(start.wrapped() - count))
    }
}
</code>```

Rust doesn't complain about this, since Wrapper is a type from this crate. It is still generic, though, because the _Tag can vary.

I tried to do something similar with operators, but I gave up. My problem was that I parameterise the result type in a way that I couldn't easily get into the types when you define the appropriate traits. I suspect, though, that you can get there with another level of re-direction and have a trait like Op<Lhs,Rhs,Res> that implements the various traits, and then implement Op<Wrapper<_lhsTag>,Wrapper<_rhsTag>, Wrapper<_resTag>> or something, but here I am not sure how to get primitive types into it without a lot of case analysis again.

For now, I have macros, and they suit me fine. Here is addition and subtraction:

macro_rules! def_op {
    ($lhs:ident + $rhs:ident => $res:ident) => {
        impl std::ops::Add<$rhs> for $lhs {
            type Output = $res;
            fn add(self, rhs: $rhs) -> Self::Output {
                let lhs: <$res as TypeInfo>::WrappedType = self.wrapped_as();
                let rhs: <$res as TypeInfo>::WrappedType = rhs.wrapped_as();
                (lhs + rhs).into()
            }
        }
    };

    ($lhs:ident - $rhs:ident => $res:ident) => {
        impl std::ops::Sub<$rhs> for $lhs {
            type Output = $res;
            fn sub(self, rhs: $rhs) -> Self::Output {
                let lhs: <$res as TypeInfo>::WrappedType = self.wrapped_as();
                let rhs: <$res as TypeInfo>::WrappedType = rhs.wrapped_as();
                (lhs - rhs).into()
            }
        }
    };
}
```
<p>With another macro I can automate the type declarations, and then add some operators. (I will figure out a way to automate the operator selection a little more later).</p>
<pre class="lang-rust prettyprint-override"><code>// This bit requires the paste crate
use paste::paste;
macro_rules! def_wrapped {
    ($name:ident[$wrapped:ty]) => {
        paste! {
            #[derive(Debug, Clone, Copy)]
            pub struct [<_ $name tag>]();
            impl TypeInfo for [<_ $name tag>] {
                type WrappedType = $wrapped;
            }
            pub type $name = Wrapper<[<_ $name tag>]>;
        }
    };
}

def_wrapped!(I[usize]); // Index with usize
def_wrapped!(O[isize]); // Offset with isize

// Some appropriate operators
def_op!(I + O => I);
def_op!(I - O => I);
def_op!(I - I => O);
def_op!(I + usize => I);
</code>```

And now, it seems this design is close to what I had before in functionality, but with fewer macros and more generics.

fn main() {
    let i: I = I::from(0);
    let j: I = 10.into();
    let k: O = j - i;
    println!("{} {} {}", i, j, i + k);
    println!("arithmetic with index and offset: {}", i + k);
    println!("arithmetic with index and usize: {}", i + 12);
    println!("{}", i + k);
    for i in I::from(0)..I::from(10) {
        println!("i = {}", i);
    }
    for k in O::from(-10)..O::from(10) {
        println!("k = {}", k);
    }
}
```

I fully expect to run into something that throws it into disarray next time I look at it, but at least there is something up and running for now.

Body:
I'm pretty new to rust, so this might be a stupid question with an obvious answer, but I don't know the answer yet. I've just read the book and then decided to implement some algorithms I'm familiar with, to get a feeling for the language. That, however, took me down a dark path to a side project that went a little deeper into the language than I had planned for...

Anyway, I'm now playing around with some code for working with indices and offsets in some algorithms in a type-safe way. I have indices into different arrays and strings and want to prevent using an index from one array to be used into another and things like that. So, I have defined new types for different kinds of indices, those with different domains, and for offsets between them. I don't allow comparisons between domains, I can subtract indices to get an offset and I can add and subtract indices and offsets and stuff like that. Further, I can define which types of objects indices can subscript, so an index into a string can only index a string and not, say, a suffix array, where another type is necessary.

This mostly works. I have a bunch of macros for defining what objects are allowed to do. For example, with this

def_offset!(Offset);
def_idx!(
    Idx
    with offset Offset
    with sub [
        Vec<T>[Idx] => T,
        [T][Idx] => T
    ]
);

I define a generic Offset that you can do arithmics on but nothing else, and then an index type Idx that can do arithmics with Offset and index vectors and slices. The arithmetic for indices looks like this right now, but I'm not done experimenting with it

macro_rules! def_idx_ops {
    ($idx:ident with offset $offset:ident) => {
        // You can add an index and an offset
        def_op!($idx + $offset => $idx);
        def_op!($offset + $idx => $idx);
        def_op!($idx += $offset);

        // You can subtract an index and an offset
        def_op!($idx - $offset => $idx);
        def_op!($idx -= $offset);

        // You can subtract two indices, but you can't add
        // them (adding indices do not usually make sense)
        def_op!($idx - $idx => $offset);

        // You can add scalars to indices.
        def_op!($idx + usize => $idx);
        def_op!(usize + $idx => $idx);
        def_op!($idx += usize);

        // You can subtract scalars from indices.
        def_op!($idx - usize => $idx);
        def_op!(usize - $idx => $idx);
        def_op!($idx -= usize);
    };
}

where the def_op! macro implements the appropriate trait for the types involved in the operator.

There is more code generation going on here than I like, but I couldn't figure out how to write generic code any other way. But maybe I will after this question.

See, now I got to implementing ranges over these types. They come out of the box if you just want a range

let r = Idx(0)..Idx(10)

but you can't iterate over them. For that, you need to implement some traits. With the code below, it works for the type Idx:

// Trait for implementing iteration through i..j ranges for Idx.
// NB: This requires nightly; the iter::Step trait is unstable.
impl std::iter::Step for Idx {
    fn steps_between(start: &Self, end: &Self) -> Option<usize> {
        match (start.0, end.0) {
            (i, j) if i > j => None,
            (i, j) => Some(j - i),
        }
    }
    fn forward_checked(start: Self, count: usize) -> Option<Self> {
        Some(start + count) // Ignoring overflow here...
    }
    fn backward_checked(start: Self, count: usize) -> Option<Self> {
        match start.0 {
            i if i < count => None,
            _ => Some(start - count),
        }
    }
}

But it only works for the concrete type Idx. If I try to make a generic implementation, I run into all kinds of trouble.

This is my current attempt, but it works as little as the others I have made:

trait RangeIndex<T>: NumWrapper<T> + std::ops::Add<T> + std::ops::Sub<T>
where
    T: num::traits::NumCast,
{
}

impl<Idx> std::iter::Step for Idx
where
    Idx: RangeIndex<usize>,
{
    fn steps_between(start: &Self, end: &Self) -> Option<usize> {
        match (start.wrapped(), end.wrapped()) {
            (i, j) if i > j => None,
            (i, j) => Some(j - i),
        }
    }
    fn forward_checked(start: Self, count: usize) -> Option<Self> {
        Some(start + count) // Ignoring overflow here...
    }
    fn backward_checked(start: Self, count: usize) -> Option<Self> {
        match start.wrapped() {
            i if i < count => None,
            _ => Some(start - count),
        }
    }
}

The RangeIndex<T> trait puts the constraints I need on the index type, and NumWrapper is a trait for the numbers I'm wrapping in indices and offsets.

pub trait Wrapper<Wrapped> {
    fn wrapped(&self) -> Wrapped;
}

pub trait NumWrapper<Wrapped>:
    Wrapper<Wrapped> + std::cmp::PartialEq + std::cmp::PartialOrd
where
    Wrapped: num::traits::NumCast,
{
    fn cast_to_wrapped<T: num::traits::NumCast>(val: T) -> Wrapped {
        num::cast(val).unwrap()
    }
}

(There is a little more to the wrapped objects, but this is the only relevant part for treating them as numbers).

This generic code does not work. The compiler suggests that I make the trait dyn but I assure you that I do not want to do that. I don't want any dynamic dispatch or polymorphism at all. I have concrete types; I want implementations for those. Nothing more and nothing less.

It is a small matter to just generate the code with macros, like I have with the operators. But I am reinventing generic code now, and that is deeply unsatisfying. I feel the same way about generating the operators instead of having code for traits and then just implementing the appropriate trait for each type.

Is it impossible to say "for any type that implements this particular trait, give me a concrete implementation of this trait like this"? It is really all I want. For any Idx that implements these traits, give me this std::iter::Step.

And if I can get that, I would love to do the same with the operators

impl<LHS, RHS, RES> std::ops::Add<RHS> for LHS {
    where //"some constraint involving both LHS and RHS and RES"
          Constraint<LHS,RHS,RES> // yeah, might not be able to do this
    type Output = RES;
    fn add(self, rhs: $rhs) -> Self::Output {
        RES(RES::cast_to_wrapped(self.wrapped()) +
            RES::cast_to_wrapped(rhs.wrapped()))
    }
}

One can dream, at least.

Anyway, I don't mind generating the operators, but I see it as a problem if I have to give up on generic code that works with these types. If I can't even run through a range, then this project is going to die pretty soon. Using macros for every generic function just isn't an attractive idea. (Well, I can still write generic functions, I just cannot implement traits, so it is not all that bad, but it still is pretty bad).

Really, what I want to tell Rust is that "for all types that implement the following traits", "give me an instance of this generic code". Exactly what I can get with macros, I suppose, but using generics that were made for this purpose instead.

Surely there must be some well know trick to generically implementing a trait without resorting to dyn?

UPDATE

I've put a related exampled on playground. The full example where I need the ranges is a bit too long, but I think the smaller example hits the same issue. There, I have a trait for adding wrapped numbers

// Local trait for adding ... a substitute for the range code I need
trait MyAdd<Rhs> {
    type Res;
    fn my_add(self, rhs: Rhs) -> Self::Res;
}

I can implement std::ops::Add just from this interface, but no matter how I try, I cannot do it without explicitly implementing that trait for each type I define. There are a couple of examples of my attempts, but needless to say, they do not work.

Playground

Body:
I fought it a bit more, and I think I might have a solution. Since I can't implement a trait for general types, but only types in my own crate, that is what I have to do. I didn't want to, because I wanted to use the types to define different operators, but I figured that there would be a way around that.

Here is what I have right now. I define a type to contain information about the wrapped objects I will hold. Then I am going to wrap objects, and use instances of this type as tags, to give my wrappers different underlying types, and that way define operators.

// Any of the wrapped types should have this.
pub trait TypeInfo: Copy {
    type WrappedType: Copy + num::PrimInt;
}

This just tells me what the underlying type is, when I get to that; that turns out to be important.

Then I define a trait for wrapper objects. They have TypeInfo to make macros and meta-programming easier, but they are not the same as the TypeInfo objects. They implement it, and they contain one.

// A few places, this is useful for meta-programming. Mostly because I can't
// get the From<> trait to work half the time...
pub trait WrapInfo: TypeInfo {
    fn wrapped(&self) -> Self::WrappedType;
    fn wrapped_as<T: num::PrimInt + Copy>(&self) -> T {
        num::cast::<Self::WrappedType, T>(self.wrapped()).unwrap()
    }
}

I also implement this trait for primitive integers, because otherwise I have to do a lot of case-analysis when I write macros later. If all the objects I implement operators on behave the same, then I don't need to worry about that.

// Type info for primitive types; we will wrap those for specific
// type-safe types. Having the traits for all numbers makes meta-programming
// a lot easier. Numerical types just wrap themselves.
impl<T> TypeInfo for T
where
    T: Copy + num::PrimInt,
{
    type WrappedType = T;
}
impl<T> WrapInfo for T
where
    T: Copy + num::PrimInt,
{
    fn wrapped(&self) -> Self::WrappedType {
        *self
    }
}

My wrapper looks like this:

#[derive(Debug, Clone, Copy)]
pub struct Wrapper<_Tag>(pub _Tag::WrappedType)
where
    _Tag: TypeInfo;

impl<_Tag> TypeInfo for Wrapper<_Tag>
where
    _Tag: TypeInfo,
{
    type WrappedType = _Tag::WrappedType;
}
impl<_Tag> WrapInfo for Wrapper<_Tag>
where
    _Tag: TypeInfo,
{
    fn wrapped(&self) -> _Tag::WrappedType {
        self.0
    }
}

It is parameterised with a _Tag of type TypeInfo, but it doesn't hold one of those types. It holds a value of _Tag::WrappedType. That way, I don't have to dereference through layers of nesting but always have the type as wrapped.0, but I still get the type safety I am going for. When I have two Wrapper<_Tag> objects with different _Tag, they are different types.

I add some other useful traits, and I am sure that there are more worth adding...

impl<_Tag> std::fmt::Display for Wrapper<_Tag>
where
    _Tag: TypeInfo,
    _Tag::WrappedType: std::fmt::Display,
{
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

// Get an ordering on it
impl<_Tag> std::cmp::PartialEq for Wrapper<_Tag>
where
    _Tag: TypeInfo,
{
    fn eq(&self, other: &Wrapper<_Tag>) -> bool {
        self.0 == other.0
    }
}
impl<_Tag> std::cmp::PartialOrd for Wrapper<_Tag>
where
    _Tag: TypeInfo,
{
    fn partial_cmp(&self, other: &Wrapper<_Tag>) -> Option<std::cmp::Ordering> {
        self.0.partial_cmp(&other.0)
    }
}

impl<T, _Tag> From<T> for Wrapper<_Tag>
where
    T: num::PrimInt,
    _Tag: TypeInfo,
{
    fn from(t: T) -> Self {
        Wrapper::<_Tag>(num::cast::<T, _Tag::WrappedType>(t).unwrap())
    }
}

Now, for the range iterator, I can just implement it on Wrapper:

impl<_Tag> std::iter::Step for Wrapper<_Tag>
where
    _Tag: TypeInfo,
{
    fn steps_between(start: &Self, end: &Self) -> Option<usize> {
        match (start.wrapped(), end.wrapped()) {
            (i, j) if i > j => None,
            (i, j) => num::cast(j - i),
        }
    }
    fn forward_checked(start: Self, count: usize) -> Option<Self> {
        let count = num::cast::<usize, _Tag::WrappedType>(count)?;
        Some(Wrapper::<_Tag>(start.wrapped() + count))
    }
    fn backward_checked(start: Self, count: usize) -> Option<Self> {
        let count = num::cast::<usize, _Tag::WrappedType>(count)?;
        Some(Wrapper::<_Tag>(start.wrapped() - count))
    }
}

Rust doesn't complain about this, since Wrapper is a type from this crate. It is still generic, though, because the _Tag can vary.

I tried to do something similar with operators, but I gave up. My problem was that I parameterise the result type in a way that I couldn't easily get into the types when you define the appropriate traits. I suspect, though, that you can get there with another level of re-direction and have a trait like Op<Lhs,Rhs,Res> that implements the various traits, and then implement Op<Wrapper<_lhsTag>,Wrapper<_rhsTag>, Wrapper<_resTag>> or something, but here I am not sure how to get primitive types into it without a lot of case analysis again.

For now, I have macros, and they suit me fine. Here is addition and subtraction:

macro_rules! def_op {
    ($lhs:ident + $rhs:ident => $res:ident) => {
        impl std::ops::Add<$rhs> for $lhs {
            type Output = $res;
            fn add(self, rhs: $rhs) -> Self::Output {
                let lhs: <$res as TypeInfo>::WrappedType = self.wrapped_as();
                let rhs: <$res as TypeInfo>::WrappedType = rhs.wrapped_as();
                (lhs + rhs).into()
            }
        }
    };

    ($lhs:ident - $rhs:ident => $res:ident) => {
        impl std::ops::Sub<$rhs> for $lhs {
            type Output = $res;
            fn sub(self, rhs: $rhs) -> Self::Output {
                let lhs: <$res as TypeInfo>::WrappedType = self.wrapped_as();
                let rhs: <$res as TypeInfo>::WrappedType = rhs.wrapped_as();
                (lhs - rhs).into()
            }
        }
    };
}

With another macro I can automate the type declarations, and then add some operators. (I will figure out a way to automate the operator selection a little more later).

// This bit requires the paste crate
use paste::paste;
macro_rules! def_wrapped {
    ($name:ident[$wrapped:ty]) => {
        paste! {
            #[derive(Debug, Clone, Copy)]
            pub struct [<_ $name tag>]();
            impl TypeInfo for [<_ $name tag>] {
                type WrappedType = $wrapped;
            }
            pub type $name = Wrapper<[<_ $name tag>]>;
        }
    };
}

def_wrapped!(I[usize]); // Index with usize
def_wrapped!(O[isize]); // Offset with isize

// Some appropriate operators
def_op!(I + O => I);
def_op!(I - O => I);
def_op!(I - I => O);
def_op!(I + usize => I);

And now, it seems this design is close to what I had before in functionality, but with fewer macros and more generics.

fn main() {
    let i: I = I::from(0);
    let j: I = 10.into();
    let k: O = j - i;
    println!("{} {} {}", i, j, i + k);
    println!("arithmetic with index and offset: {}", i + k);
    println!("arithmetic with index and usize: {}", i + 12);
    println!("{}", i + k);
    for i in I::from(0)..I::from(10) {
        println!("i = {}", i);
    }
    for k in O::from(-10)..O::from(10) {
        println!("k = {}", k);
    }
}

I fully expect to run into something that throws it into disarray next time I look at it, but at least there is something up and running for now.


问:
How to make a working login functions for my website?
I am just entered this game since last December. Now I finished HTML CSS and a little bit of Java Script yet I got stuck at this stage: I can do basic styling but I don't know how to make it interactive.

So my question is :

how can I make a login function for websites, which can gives visitor an account  (sign up, login, forgot password) that can do basic things like comment , add to basket and favorite a product?

Don't need to be specific, please just highlight which language is involved in which stage.

Thanks ahead.

答:
Now I finished HTML CSS and a little bit of Java Script

So your site is what is called a static website.

If you want to allow login and data storing, you need a dynamic website, that requires one of this technologies:

PHP

ASP (check also ASP.NET)

Node.js (with express or http module)

Django (Python's library)

A few others...

All this technologies are called server-side languages/technologies, and the most used for long years has been PHP, that now has some strong rivals in terms of usage.


问:
Is there a widget in flutter that allows you to create such a view?
I need to implement such a widget in Flutter. Full version of the page, where this widget is going to be used is here Maybe you know build-in widgets, which could help me. But if there are none, what is the best way to implement this widget?</p>

答:
You can use a ListTile

```<code>ListTile(
  leading: const Text("Lbikgabsb"),
  trailing: Column(
    children: [
       const Text("900 P"),
       const Text("2"), // add your decoration to the background
    ),
   ],
 ),
),
</code>```

Alternatively you can use:

```<code>SizedBox(
  height: your_height,
  width:double.infinity,
  child: Row(
    children:[
      Text("Lbikgabsb"),
      Column(
        children: [
           const Text("900 P"),
           const Text("2"), // add your decoration to the background
    ],
  ),
),
</code>```

You can choose whichever approach works best for your app

Body:
You can use a ListTile

ListTile(
  leading: const Text("Lbikgabsb"),
  trailing: Column(
    children: [
       const Text("900 P"),
       const Text("2"), // add your decoration to the background
    ),
   ],
 ),
),

Alternatively you can use:

SizedBox(
  height: your_height,
  width:double.infinity,
  child: Row(
    children:[
      Text("Lbikgabsb"),
      Column(
        children: [
           const Text("900 P"),
           const Text("2"), // add your decoration to the background
    ],
  ),
),

You can choose whichever approach works best for your app


答:
.clear() modifies the row list in-place, and you're using the same list across different iterations of the outer loop. Under the hood, matrix list consists of references that point to the same memory as row. So, the removal of all the elements in row is reflected in the matrix as well.

To resolve, reassign the row variable to an empty list at the start of each iteration of the outer loop. This separates the memory used to store each row.

dim=int(input("Dimension of your matrix? "))
matrix=[]
for i in range(dim):
    row = []
    for j in range(dim):
        inp=float(input("Insert element with indeces: "+str(i+1)+" "+str(j+1)+" :"))
        row.append(inp)
    print(row)
    matrix.append(row)
print("Your matrix is:")
print(matrix)
```

Title: Troubles taking a matrix from user's input, defining it as a list of lists


问:
How can I fix npm error running npm run build?
When I run npm run build, I had this error and I couldn't fix it reading all articles on github and same quest-s on stack:</p>
```<code>npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path C:\Users\Користувач\Desktop\test/package.json
npm ERR! errno -4058
npm ERR! enoent ENOENT: no such file or directory, open 'C:\Users\Користувач\Desktop\test\package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Користувач\AppData\Local\npm-cache\_logs\2022-02-06T18_36_44_973Z-debug-0.log
</code>```

答:
ensure you're in the correct directory. You need to cd into the right directory before running the command.

If you want to make sure package.json is there in the directory, run

ls | grep package.json
```

if this doesn't show the file, then either you're in the wrong directory or you might have deleted package.json in which case you might have to recreate it, or bring it back from version control.

Body:
When I run npm run build, I had this error and I couldn't fix it reading all articles on github and same quest-s on stack:

npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path C:\Users\Користувач\Desktop\test/package.json
npm ERR! errno -4058
npm ERR! enoent ENOENT: no such file or directory, open 'C:\Users\Користувач\Desktop\test\package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Користувач\AppData\Local\npm-cache\_logs\2022-02-06T18_36_44_973Z-debug-0.log

Body:
ensure you're in the correct directory. You need to cd into the right directory before running the command.

If you want to make sure package.json is there in the directory, run

ls | grep package.json

if this doesn't show the file, then either you're in the wrong directory or you might have deleted package.json in which case you might have to recreate it, or bring it back from version control.


问:
Execution failed for task ':audioplayers:compileDebugKotlin'
I'm facing this nasty error when trying to compile my Flutter App into an Android simulator. Here is the error log (is too long to paste it entirely):

aunching lib/main.dart on sdk gphone x86 in debug mode...
Running Gradle task 'assembleDebug'...
Note: Some input files use or override a deprecated API. Note: Recompile with -Xlint:deprecation for details.
e: Incompatible classes were found in dependencies. Remove them from
the classpath or use '-Xskip-metadata-version-check' to suppress
errors e:
/Users/reinier/.gradle/caches/transforms-2/files-2.1/24fa3aa8d2270e5eb067bbe36e9b7563/jetified-kotlin-stdlib-1.5.10.jar!/META-INF/kotlin-stdlib.kotlin_module:
Module was compiled with an incompatible version of Kotlin. The binary
version of its metadata is 1.5.1, expected version is 1.1.15. e:
/Users/reinier/.gradle/caches/transforms-2/files-2.1/4d4ccf1034ba5937e6e7ba3aa34d2661/jetified-core-ktx-1.6.0-beta02-api.jar!/META-INF/core-ktx_release.kotlin_module:
Module was compiled with an incompatible version of Kotlin. The binary
version of its metadata is 1.5.1, expected version is 1.1.15. e:
/Users/reinier/.gradle/caches/transforms-2/files-2.1/77bab1911042ab2c6d5cc0b2e2ee053c/jetified-kotlin-stdlib-common-1.5.10.jar!/META-INF/kotlin-stdlib-common.kotlin_module:
Module was compiled with an incompatible version of Kotlin. The binary
version of its metadata is 1.5.1, expected version is 1.1.15. e:
/Users/reinier/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/audioplayers-0.18.3/android/src/main/kotlin/xyz/luan/audioplayers/AudioplayersPlugin.kt:
(18, 32): Unresolved reference: mutableMapOf e:
/Users/reinier/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/audioplayers-0.18.3/android/src/main/kotlin/xyz/luan/audioplayers/AudioplayersPlugin.kt:
(25, 9): Class 'kotlin.Unit' was compiled with an incompatible version
of Kotlin. The binary version of its metadata is 1.5.1, expected
version is 1.1.15.

. . . . .

e:
/Users/reinier/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/audioplayers-0.18.3/android/src/main/kotlin/xyz/luan/audioplayers/WrappedSoundPool.kt: (235, 30): Class 'kotlin.Unit' was compiled with an incompatible
version of Kotlin. The binary version of its metadata is 1.5.1,
expected version is 1.1.15. The class is loaded from
/Users/reinier/.gradle/caches/transforms-2/files-2.1/24fa3aa8d2270e5eb067bbe36e9b7563/jetified-kotlin-stdlib-1.5.10.jar!/kotlin/Unit.class

FAILURE: Build failed with an exception.

What went wrong: Execution failed for task ':audioplayers:compileDebugKotlin'.

Compilation error. See log for more details

Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 21s Exception: Gradle task assembleDebug failed with
exit code 1

I already tried changing "minSdkVersion 16" to "minSdkVersion 23" at android/app/build.gradle:38 and is not working.

Tried using the version 0.17.0 of audioplayers and the same, not working.

Tried using the version ^0.10.0 of audioplayers and nothing.

Tried doing the previos steps and then executing on the terminal: flutter clean & flutter pub get... and nothing.

I already updated the Flutter SDK and nothing. Still not working for Android.

It compiles perfectly on an IOS simulator. This error has emerged several times after each audioplayers package update. I'm using compileSdkVersion 30 on Android Studio 4.2.1

This is my pubspec.yaml file:

```<code>name: feeddy_flutter
description: A multi screen foods listing Flutter app

publish_to: 'none' # Remove this line if you wish to publish to pub.dev

version: 1.0.0+1

environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^1.0.2
  intl: ^0.17.0
  uuid: ^3.0.4
  currency_text_input_formatter: ^2.0.1
  date_time_picker: ^2.0.0
  rflutter_alert: ^2.0.2
  faker: ^1.3.0
  fl_chart: ^0.35.0
  provider: ^5.0.0
  tinycolor: ^1.0.3
  font_awesome_flutter: ^9.0.0
  audioplayers: ^0.18.3
  empty_widget: ^0.0.2
  splashscreen: ^1.3.5
  native_device_orientation: ^1.0.0
  sqflite: ^2.0.0+3
  flutter_switch: ^0.3.1
  flutter_colorpicker: ^0.4.0
  enum_to_string: ^2.0.1
  humanizer: ^0.0.2
  route_observer_mixin: ^1.5.0+1

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:
  uses-material-design: true

  assets:
    - assets/images/
    - assets/audio/

  fonts:
    - family: Luminari
      fonts:
        - asset: assets/fonts/Luminari/Luminari-Regular.ttf
          style: normal
          weight: 500
        - asset: assets/fonts/Luminari/Luminari-Regular.woff
          style: normal
          weight: 500
    - family: SourceSansPro
      fonts:
        - asset: assets/fonts/Source_Sans_Pro/SourceSansPro-Regular.ttf
          style: normal
          weight: 500
    - family: OpenSans
      fonts:
        - asset: assets/fonts/OpenSans/OpenSans-Regular.ttf
          style: normal
          weight: 500
        - asset: assets/fonts/OpenSans/OpenSans-Bold.ttf
          weight: 700
    - family: Quicksand
      fonts:
        - asset: assets/fonts/Quicksand/Quicksand-Regular.ttf
          style: normal
          weight: 500
        - asset: assets/fonts/Quicksand/Quicksand-Medium.ttf
        - asset: assets/fonts/Quicksand/Quicksand-Light.ttf
        - asset: assets/fonts/Quicksand/Quicksand-Bold.ttf
          weight: 700
    - family: Raleway
      fonts:
        - asset: assets/fonts/Raleway/Raleway-Regular.ttf
          style: normal
          weight: 500
        - asset: assets/fonts/Raleway/Raleway-Bold.ttf
          weight: 700
        - asset: assets/fonts/Raleway/Raleway-Black.ttf
          weight: 900
    - family: RobotoCondensed
      fonts:
        - asset: assets/fonts/RobotoCondensed/RobotoCondensed-Regular.ttf
          style: normal
          weight: 500
        - asset: assets/fonts/RobotoCondensed/RobotoCondensed-Bold.ttf
          weight: 700
        - asset: assets/fonts/RobotoCondensed/RobotoCondensed-Light.ttf
          weight: 300
        - asset: assets/fonts/RobotoCondensed/RobotoCondensed-Italic.ttf
          style: italic
    - family: AppIcons
      fonts:
        - asset: assets/fonts/AppIcons/AppIcons.ttf
</code>```

答:
As for Flutter 2.10 there was a breaking change with required Kotlin version - Ref.

Here is a migration guide

This means that if you previosly created a project a long time ago (with java) then it means you need to add Kotlin plugin to build.gradle. I suggest launching flutter create --org com.sample sample which generates up-to-date configuration. Then you can check what is missing.

Body:
I'm facing this nasty error when trying to compile my Flutter App into an Android simulator. Here is the error log (is too long to paste it entirely):

aunching lib/main.dart on sdk gphone x86 in debug mode...
Running Gradle task 'assembleDebug'...
Note: Some input files use or override a deprecated API. Note: Recompile with -Xlint:deprecation for details.
e: Incompatible classes were found in dependencies. Remove them from
the classpath or use '-Xskip-metadata-version-check' to suppress
errors e:
/Users/reinier/.gradle/caches/transforms-2/files-2.1/24fa3aa8d2270e5eb067bbe36e9b7563/jetified-kotlin-stdlib-1.5.10.jar!/META-INF/kotlin-stdlib.kotlin_module:
Module was compiled with an incompatible version of Kotlin. The binary
version of its metadata is 1.5.1, expected version is 1.1.15. e:
/Users/reinier/.gradle/caches/transforms-2/files-2.1/4d4ccf1034ba5937e6e7ba3aa34d2661/jetified-core-ktx-1.6.0-beta02-api.jar!/META-INF/core-ktx_release.kotlin_module:
Module was compiled with an incompatible version of Kotlin. The binary
version of its metadata is 1.5.1, expected version is 1.1.15. e:
/Users/reinier/.gradle/caches/transforms-2/files-2.1/77bab1911042ab2c6d5cc0b2e2ee053c/jetified-kotlin-stdlib-common-1.5.10.jar!/META-INF/kotlin-stdlib-common.kotlin_module:
Module was compiled with an incompatible version of Kotlin. The binary
version of its metadata is 1.5.1, expected version is 1.1.15. e:
/Users/reinier/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/audioplayers-0.18.3/android/src/main/kotlin/xyz/luan/audioplayers/AudioplayersPlugin.kt:
(18, 32): Unresolved reference: mutableMapOf e:
/Users/reinier/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/audioplayers-0.18.3/android/src/main/kotlin/xyz/luan/audioplayers/AudioplayersPlugin.kt:
(25, 9): Class 'kotlin.Unit' was compiled with an incompatible version
of Kotlin. The binary version of its metadata is 1.5.1, expected
version is 1.1.15.

. . . . .

e:
/Users/reinier/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/audioplayers-0.18.3/android/src/main/kotlin/xyz/luan/audioplayers/WrappedSoundPool.kt: (235, 30): Class 'kotlin.Unit' was compiled with an incompatible
version of Kotlin. The binary version of its metadata is 1.5.1,
expected version is 1.1.15. The class is loaded from
/Users/reinier/.gradle/caches/transforms-2/files-2.1/24fa3aa8d2270e5eb067bbe36e9b7563/jetified-kotlin-stdlib-1.5.10.jar!/kotlin/Unit.class

FAILURE: Build failed with an exception.

What went wrong: Execution failed for task ':audioplayers:compileDebugKotlin'.

Compilation error. See log for more details

Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 21s Exception: Gradle task assembleDebug failed with
exit code 1

I already tried changing "minSdkVersion 16" to "minSdkVersion 23" at android/app/build.gradle:38 and is not working.

Tried using the version 0.17.0 of audioplayers and the same, not working.

Tried using the version ^0.10.0 of audioplayers and nothing.

Tried doing the previos steps and then executing on the terminal: flutter clean & flutter pub get... and nothing.

I already updated the Flutter SDK and nothing. Still not working for Android.

It compiles perfectly on an IOS simulator. This error has emerged several times after each audioplayers package update. I'm using compileSdkVersion 30 on Android Studio 4.2.1

This is my pubspec.yaml file:

name: feeddy_flutter
description: A multi screen foods listing Flutter app

publish_to: 'none' # Remove this line if you wish to publish to pub.dev

version: 1.0.0+1

environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^1.0.2
  intl: ^0.17.0
  uuid: ^3.0.4
  currency_text_input_formatter: ^2.0.1
  date_time_picker: ^2.0.0
  rflutter_alert: ^2.0.2
  faker: ^1.3.0
  fl_chart: ^0.35.0
  provider: ^5.0.0
  tinycolor: ^1.0.3
  font_awesome_flutter: ^9.0.0
  audioplayers: ^0.18.3
  empty_widget: ^0.0.2
  splashscreen: ^1.3.5
  native_device_orientation: ^1.0.0
  sqflite: ^2.0.0+3
  flutter_switch: ^0.3.1
  flutter_colorpicker: ^0.4.0
  enum_to_string: ^2.0.1
  humanizer: ^0.0.2
  route_observer_mixin: ^1.5.0+1

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:
  uses-material-design: true

  assets:
    - assets/images/
    - assets/audio/

  fonts:
    - family: Luminari
      fonts:
        - asset: assets/fonts/Luminari/Luminari-Regular.ttf
          style: normal
          weight: 500
        - asset: assets/fonts/Luminari/Luminari-Regular.woff
          style: normal
          weight: 500
    - family: SourceSansPro
      fonts:
        - asset: assets/fonts/Source_Sans_Pro/SourceSansPro-Regular.ttf
          style: normal
          weight: 500
    - family: OpenSans
      fonts:
        - asset: assets/fonts/OpenSans/OpenSans-Regular.ttf
          style: normal
          weight: 500
        - asset: assets/fonts/OpenSans/OpenSans-Bold.ttf
          weight: 700
    - family: Quicksand
      fonts:
        - asset: assets/fonts/Quicksand/Quicksand-Regular.ttf
          style: normal
          weight: 500
        - asset: assets/fonts/Quicksand/Quicksand-Medium.ttf
        - asset: assets/fonts/Quicksand/Quicksand-Light.ttf
        - asset: assets/fonts/Quicksand/Quicksand-Bold.ttf
          weight: 700
    - family: Raleway
      fonts:
        - asset: assets/fonts/Raleway/Raleway-Regular.ttf
          style: normal
          weight: 500
        - asset: assets/fonts/Raleway/Raleway-Bold.ttf
          weight: 700
        - asset: assets/fonts/Raleway/Raleway-Black.ttf
          weight: 900
    - family: RobotoCondensed
      fonts:
        - asset: assets/fonts/RobotoCondensed/RobotoCondensed-Regular.ttf
          style: normal
          weight: 500
        - asset: assets/fonts/RobotoCondensed/RobotoCondensed-Bold.ttf
          weight: 700
        - asset: assets/fonts/RobotoCondensed/RobotoCondensed-Light.ttf
          weight: 300
        - asset: assets/fonts/RobotoCondensed/RobotoCondensed-Italic.ttf
          style: italic
    - family: AppIcons
      fonts:
        - asset: assets/fonts/AppIcons/AppIcons.ttf


问:
How do I create a Postgres table with a column that holds an array of objects?
The documentation shows that arrays can be created as either text or integer. I did not find an example for creating an object array. An example is the items column:

```<code>CREATE TABLE cart (
_id serial PRIMARY KEY,
user_id Integer UNIQUE NOT NULL,
items varchar [],
FOREIGN KEY (user_id)
REFERENCES users (_id)
</code>```

Object stored in the items array have quotes around them making them strings instead of objects. A code segment creating objects in items is shown below:

```<code>update cart
set items =
array_append(items,
'{product_id: ${cartItem.productId}, size: ${cartItem.size}, quantity: ${cartItem.quantity}}')
where _id = ${cart._id}
and user_id = ${userId}
RETURNING *
</code>```

I am compelled to put quotes around the object value. As a result it is stored as a string in the column with quotes around it.

```<code>cart {
  _id: 1,
  user_id: 1,
  items: [
    '{product_id: 1, size: Small, quantity: 1}',
    '{product_id: 1, size: Small, quantity: 1}',
    '{product_id: 1, size: Small, quantity: 1}'
  ]
}
</code>```

Because the items in the items column are stored as string instead of objects, I cannot correctly iterate over them in my program.  For example,
items.product_id does not exist.

How do I fix this?

答:
Recommended using JSON or JSONB types. In JSON types you can perform any operations on keys or values, such as filtering, selecting, joining. If you need you can even show JSON keys and values as table record view.
Examples:

```<code>items: '[
            {"product_id": 1, "size": "Small", "quantity": 1},
            {"product_id": 1, "size": "Small", "quantity": 1},
            {"product_id": 1, "size": "Small", "quantity": 1}
        ]'

select
    json_array_elements(items)->'product_id' as product_id,
    json_array_elements(items)->'size' as "size",
    json_array_elements(items)->'quantity' as quantity
from cart
where user_id = 1;
</code>```

Result:

product_id
size
quantity

1
"Small"
1

1
"Small"
1

1
"Small"
1

Body:
The documentation shows that arrays can be created as either text or integer. I did not find an example for creating an object array. An example is the items column:

CREATE TABLE cart (
_id serial PRIMARY KEY,
user_id Integer UNIQUE NOT NULL,
items varchar [],
FOREIGN KEY (user_id)
REFERENCES users (_id)

Object stored in the items array have quotes around them making them strings instead of objects. A code segment creating objects in items is shown below:

update cart
set items =
array_append(items,
'{product_id: ${cartItem.productId}, size: ${cartItem.size}, quantity: ${cartItem.quantity}}')
where _id = ${cart._id}
and user_id = ${userId}
RETURNING *

I am compelled to put quotes around the object value. As a result it is stored as a string in the column with quotes around it.

cart {
  _id: 1,
  user_id: 1,
  items: [
    '{product_id: 1, size: Small, quantity: 1}',
    '{product_id: 1, size: Small, quantity: 1}',
    '{product_id: 1, size: Small, quantity: 1}'
  ]
}

Because the items in the items column are stored as string instead of objects, I cannot correctly iterate over them in my program.  For example,
items.product_id does not exist.

How do I fix this?

Body:
Recommended using JSON or JSONB types. In JSON types you can perform any operations on keys or values, such as filtering, selecting, joining. If you need you can even show JSON keys and values as table record view.
Examples:

items: '[
            {"product_id": 1, "size": "Small", "quantity": 1},
            {"product_id": 1, "size": "Small", "quantity": 1},
            {"product_id": 1, "size": "Small", "quantity": 1}
        ]'

select
    json_array_elements(items)->'product_id' as product_id,
    json_array_elements(items)->'size' as "size",
    json_array_elements(items)->'quantity' as quantity
from cart
where user_id = 1;

Result:

product_id
size
quantity

1
"Small"
1

1
"Small"
1

1
"Small"
1


问:
How do I link a flight schedule from an excel sheet to my AnyLogic simulation agents?
I have an excel file with the flight timetable with the following columns: Airline, destination, departure time, flight number, check-in desk, gate number, departures, number of passengers.

I have created an agent containing this database in my model called flightTimetable.

In the 1st picture, I have set the conditions for the select Output for the agents to go to their designated check-in desk according to the database but this is not working. Any suggestions on what I can do?

答:
The issue in your logis that the check-in desk parameter is a String (text) and not a number... so in your logic check in the select output you test if the check-in desk is = to an integer yet it is a String. You can test this by chaning the logic check to agent.checkInDesk.equals("1") for each of the numbers.

The alternative options is to conver the input data to number

You can see that your input variables is text by observing the little green triangule in the corenr of the cell in your Excel sheet... If you hover over it you will see that there is a littel exclamation mark that appears on the right hand side of the cell and then if you click on it it will tel you that it is a number stored as text...

You can fix this by using the text to column feature in Excel - use the wizard for more infrormation.

You should also be able to open the internal AnyLogic Database table and see that the table column is set to text


问:
iOS appendFomat cause app to crash
Is there anything wrong with the code below ? It crash my app sometimes.</p>

```<code>- (NSString*) getDisplayString
{
    NSMutableString* display = [[NSMutableString alloc] initWithString:@""];

for(NSUInteger i = 0; i < [entries count]; i++)
{
    Entry* e = [entries objectAtIndex:i];
    [display appendFormat:@"%d. %@ %30d\n", i+1, e.title, e.value];

}

    return display;
}
</code>```

答:
Found the answer to my problem. Issue is memory management where I wasn't increasing the retain count of the NSString title found in the Entry object. title is the value obtain from user input through a textfield so when the UIView is releasing the string which is done internally, its no longer in memory hence it makes the error appears to be random.

So to summarise whenever u are using a value from a textfield, you need to increase its retain count.

```<code>NSMutableArray* myArray = [[NSMutableArray alloc] init];
NSString* someStringToStore = uiTextField.text;
[someStringToStore retain];
[myArray addObject: someStringToStore];
</code>```

Title: iOS appendFomat cause app to crash

Body:
Is there anything wrong with the code below ? It crash my app sometimes.

- (NSString*) getDisplayString
{
    NSMutableString* display = [[NSMutableString alloc] initWithString:@""];

for(NSUInteger i = 0; i < [entries count]; i++)
{
    Entry* e = [entries objectAtIndex:i];
    [display appendFormat:@"%d. %@ %30d\n", i+1, e.title, e.value];

}

    return display;
}

Body:
Found the answer to my problem. Issue is memory management where I wasn't increasing the retain count of the NSString title found in the Entry object. title is the value obtain from user input through a textfield so when the UIView is releasing the string which is done internally, its no longer in memory hence it makes the error appears to be random.

So to summarise whenever u are using a value from a textfield, you need to increase its retain count.

NSMutableArray* myArray = [[NSMutableArray alloc] init];
NSString* someStringToStore = uiTextField.text;
[someStringToStore retain];
[myArray addObject: someStringToStore];


问:
Turning vectors of strings in a dataframe into categorical variables in R
I'm fairly new to R and am sure there's a way to do the following without using loops, which I'm more familiar with.

Take the following example where you have a bunch of names and fruits each person likes:

```<code>name <- c("Alice", "Bob")
preference <- list(c("apple", "pear"), c("banana", "apple"))
df <- as.data.frame(cbind(name, preference))
</code>```

How to I convert it to the following?

```<code>apple <- c(1, 1)
pear <- c(1, 0)
banana <- c(0, 1)
df2 <- data.frame(name, apple, pear, banana)
</code>```

My basic instinct is to first extract all the fruits then do a loop to check if each fruit is in each row's preference:

```<code>fruits <- unique(unlist(df$preference))
for (fruit in fruits) {
    df <- df %>% rowwise %>% mutate("{fruit}" := fruit %in% preference)
}
</code>```

This seems to work, but I'm pretty sure there's a better way to do this.

答:
Another possible solution, based on tidyr::separate_rows and janitor::tabyl:

library(tidyverse)

df %>%
  separate_rows(everything(), sep="(?<=\\w), (?=\\w)") %>%
  janitor::tabyl(name, preference)

#>   name apple banana pear
#>  Alice     1      0    1
#>    Bob     1      1    0
```

Body:
I'm fairly new to R and am sure there's a way to do the following without using loops, which I'm more familiar with.

Take the following example where you have a bunch of names and fruits each person likes:

name <- c("Alice", "Bob")
preference <- list(c("apple", "pear"), c("banana", "apple"))
df <- as.data.frame(cbind(name, preference))

How to I convert it to the following?

apple <- c(1, 1)
pear <- c(1, 0)
banana <- c(0, 1)
df2 <- data.frame(name, apple, pear, banana)

My basic instinct is to first extract all the fruits then do a loop to check if each fruit is in each row's preference:

fruits <- unique(unlist(df$preference))
for (fruit in fruits) {
    df <- df %>% rowwise %>% mutate("{fruit}" := fruit %in% preference)
}

This seems to work, but I'm pretty sure there's a better way to do this.


问:
Python(3) - store one specific link of output from soup.find_all in variable
I am working on a web scrapping function.
I want to find the latest download link ending with ".img.html" from:

"https://dl.twrp.me/gauguin/"

and store this link in a variable, not just print it.

My code so far:

```<code>from bs4 import BeautifulSoup
from urllib.request import urlopen

url = "https://dl.twrp.me/gauguin/"

html_doc = urlopen(url)
# defining html link (twrp...)

soup = BeautifulSoup(html_doc, "html.parser")

for link in soup.find_all('a'):
    links = (link.get('href'))
print(links)
</code>```

My Output:

```<code>https://twrp.me
#
https://twrp.me/about/
https://twrp.me/contactus/
https://twrp.me/Devices/
https://twrp.me/FAQ/
/public.asc
/gauguin/twrp-3.5.2_10-0-gauguin.img.html
/gauguin/twrp-3.5.1_10-0-gauguin.img.html
/gauguin/twrp-3.5.0_10-0-gauguin.img.html
https://twrp.me/terms/termsofservice.html
https://twrp.me/terms/cookiepolicy.html
https://github.com/TeamWin
</code>```

So my goal is to filter this output so I just have those one link (the latest):

```<code>/gauguin/twrp-3.5.2_10-0-gauguin.img.html
</code>```

stored in a variable, so I can call this variable later on or even directly download it with wget for example.

答:
By latest I assume you want the link with the most recent date. As such you need to capture both the URL and the date given for each link. This can then by converted into a datetime object and added to a list.

After all URLs are found, the list can be easily sorted into date order, with the newest first. The latest URL can then be used to download the img file.

For example:

```<code>from bs4 import BeautifulSoup
import requests
from datetime import datetime

base_url = "https://dl.twrp.me"
req = requests.get(f"{base_url}/gauguin")
soup = BeautifulSoup(req.content, "html.parser")

urls = []

for a in soup.find_all('a', href=True):
    link = a['href']

    if link.endswith('.img.html'):
        date_text = a.find_next('em').get_text(strip=True)
        date_dt = datetime.strptime(date_text, "%Y-%m-%d %H:%M:%S %Z")
        urls.append([date_dt, link])

latest = sorted(urls, reverse=True)[0][1]       # choose the latest url

# Download the latest img file
url_img = base_url + latest.split('.html')[0]
filename = url_img.split('/')[-1]

with requests.get(url_img, stream=True, headers={'Referer' : base_url + latest}) as req_img:
    with open(filename, 'wb') as f_img:
        for chunk in req_img.iter_content(chunk_size=2**15):
            f_img.write(chunk)
</code>```

This approach might have the advantage of still working if the naming or numbering scheme is changed. A referer header is added to avoid the website returning the HTML for the download page.

This results in a download of 131,072 KB

Note, if you prefer to ignore the date and just sort on the version number, use the following approach:

```<code>from bs4 import BeautifulSoup
import requests
from datetime import datetime
import re

base_url = "https://dl.twrp.me"
req = requests.get(f"{base_url}/gauguin")
soup = BeautifulSoup(req.content, "html.parser")

urls = []

for a in soup.find_all('a', href=True):
    link = a['href']

    if link.endswith('.img.html'):
        version = re.findall(r'(\d+)', link)
        urls.append([version, link])

latest = sorted(urls, reverse=True)[0][1]       # choose the latest url
</code>```

Body:
I am working on a web scrapping function.
I want to find the latest download link ending with ".img.html" from:

"https://dl.twrp.me/gauguin/"

and store this link in a variable, not just print it.

My code so far:

from bs4 import BeautifulSoup
from urllib.request import urlopen

url = "https://dl.twrp.me/gauguin/"

html_doc = urlopen(url)
# defining html link (twrp...)

soup = BeautifulSoup(html_doc, "html.parser")

for link in soup.find_all('a'):
    links = (link.get('href'))
print(links)

My Output:

https://twrp.me
#
https://twrp.me/about/
https://twrp.me/contactus/
https://twrp.me/Devices/
https://twrp.me/FAQ/
/public.asc
/gauguin/twrp-3.5.2_10-0-gauguin.img.html
/gauguin/twrp-3.5.1_10-0-gauguin.img.html
/gauguin/twrp-3.5.0_10-0-gauguin.img.html
https://twrp.me/terms/termsofservice.html
https://twrp.me/terms/cookiepolicy.html
https://github.com/TeamWin

So my goal is to filter this output so I just have those one link (the latest):

/gauguin/twrp-3.5.2_10-0-gauguin.img.html

stored in a variable, so I can call this variable later on or even directly download it with wget for example.

Body:
By latest I assume you want the link with the most recent date. As such you need to capture both the URL and the date given for each link. This can then by converted into a datetime object and added to a list.

After all URLs are found, the list can be easily sorted into date order, with the newest first. The latest URL can then be used to download the img file.

For example:

from bs4 import BeautifulSoup
import requests
from datetime import datetime

base_url = "https://dl.twrp.me"
req = requests.get(f"{base_url}/gauguin")
soup = BeautifulSoup(req.content, "html.parser")

urls = []

for a in soup.find_all('a', href=True):
    link = a['href']

    if link.endswith('.img.html'):
        date_text = a.find_next('em').get_text(strip=True)
        date_dt = datetime.strptime(date_text, "%Y-%m-%d %H:%M:%S %Z")
        urls.append([date_dt, link])

latest = sorted(urls, reverse=True)[0][1]       # choose the latest url

# Download the latest img file
url_img = base_url + latest.split('.html')[0]
filename = url_img.split('/')[-1]

with requests.get(url_img, stream=True, headers={'Referer' : base_url + latest}) as req_img:
    with open(filename, 'wb') as f_img:
        for chunk in req_img.iter_content(chunk_size=2**15):
            f_img.write(chunk)

This approach might have the advantage of still working if the naming or numbering scheme is changed. A referer header is added to avoid the website returning the HTML for the download page.

This results in a download of 131,072 KB

Note, if you prefer to ignore the date and just sort on the version number, use the following approach:

from bs4 import BeautifulSoup
import requests
from datetime import datetime
import re

base_url = "https://dl.twrp.me"
req = requests.get(f"{base_url}/gauguin")
soup = BeautifulSoup(req.content, "html.parser")

urls = []

for a in soup.find_all('a', href=True):
    link = a['href']

    if link.endswith('.img.html'):
        version = re.findall(r'(\d+)', link)
        urls.append([version, link])

latest = sorted(urls, reverse=True)[0][1]       # choose the latest url


问:
IIS CGI could not locate my python modules
I am trying to run my python scripts on my IIS website using CGI and I am having trouble with importing. When run on its own, the python scripts finds the mysql.connector module installed in my os perfectly fine, but when I try to run it on the website, it gives a Bad Gateway (502.2) error with the stacktrace stating ModuleNotFoundError: No module named 'mysql.connector'. I'm assuming CGI cannot find the module in my OS, how can I let it find the module? Do I have to specify my modules folder somewhere in the IIS like a PATH variable?

Here is the complete stacktrace of the bad gateway page:

The specified CGI application misbehaved by not returning a complete set of HTTP headers. The headers it did return are "Traceback (most recent call last): File "C:\Users\pedro\OneDrive\Documents\adet\ind.py", line 2, in  import python_mysql File "C:\Users\pedro\OneDrive\Documents\adet\python_mysql.py", line 1, in  import mysql.connector ModuleNotFoundError: No module named 'mysql.connector' ".

答: As a workaround, I simply copied and pasted all of my modules in my modules folder to my website's folder. I guessed that since my personal imports were working that it should also work if I added the other modules to the same folder and lo, it did. I hope there's a cleaner way to solve this, but for now I'll choose this as a solution.</p>


问:
SwiftUI - 'windows' was deprecated in iOS 15.0: Use UIWindowScene.windows
I'm having the following code block:

```<code>struct StackOverflow: View {
    var body: some View {
        Text("Hello, World!")
            .padding(.bottom,UIApplication.shared.windows.first?.safeAreaInsets.bottom ?? 15)
    }
}
</code>```

However, this returns the following error:

'windows' was deprecated in iOS 15.0: Use UIWindowScene.windows on a relevant window scene instead

I tried to utilize UIWindowScene.windows but it's not working somehow. Any ideas how to translate this into the new syntax?

答:
```<code>struct StackOverflow: View {

    var body: some View {
        let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene
        let window = windowScene?.windows.first

        Text("Hello, World!")
           .padding(.bottom, window?.safeAreaInsets.bottom ?? 15)
     }
}
</code>```

Depends on what you need, there's more about this here:

https://developer.apple.com/documentation/swiftui/text/padding(_:)-5wi61

https://www.hackingwithswift.com/quick-start/swiftui/how-to-inset-the-safe-area-with-custom-content

SwiftUI how to adjust different screen sizes

https://developer.apple.com/news/?id=nixcb564

https://developer.apple.com/design/human-interface-guidelines/ios/visual-design/adaptivity-and-layout/

Body:
I'm having the following code block:

struct StackOverflow: View {
    var body: some View {
        Text("Hello, World!")
            .padding(.bottom,UIApplication.shared.windows.first?.safeAreaInsets.bottom ?? 15)
    }
}

However, this returns the following error:

'windows' was deprecated in iOS 15.0: Use UIWindowScene.windows on a relevant window scene instead

I tried to utilize UIWindowScene.windows but it's not working somehow. Any ideas how to translate this into the new syntax?

Body:
struct StackOverflow: View {

    var body: some View {
        let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene
        let window = windowScene?.windows.first

        Text("Hello, World!")
           .padding(.bottom, window?.safeAreaInsets.bottom ?? 15)
     }
}

Depends on what you need, there's more about this here:

https://developer.apple.com/documentation/swiftui/text/padding(_:)-5wi61

https://www.hackingwithswift.com/quick-start/swiftui/how-to-inset-the-safe-area-with-custom-content

SwiftUI how to adjust different screen sizes

https://developer.apple.com/news/?id=nixcb564

https://developer.apple.com/design/human-interface-guidelines/ios/visual-design/adaptivity-and-layout/


问:
Match RegEx with Caret Negation (exclude)
I want to filter my array with an exclusion so I did

```<code>const exclude = include.filter((d) => {
                let negate1 = '[^'
                let negate2 = ']'
                let negate = negate1.concat(letterexc).concat(negate2)
                let exclRegex = new RegExp(negate,'g')
                console.log(exclRegex) //return --> /[^anyletter]/g
                return d.list.match(exclRegex)
            })
</code>```

I add [^ and letterexc variable from an input field and ] to make a negation regex, but its not working. not filtering anything.

I read and tried my pattern here https://regexr.com/ and found if my pattern actually works, but not on my own.

Another article from MDN and link says the similar pattern works (with caret after bracket)

EDIT:
I added a pen link. It's filtering with 2 input field for letter included and excluded. The included filter works fine

答:
I found it

I change

```<code>d.list.match(exclRegex)
</code>```

to

```<code>!d.list.match(exclRegex)
</code>```

while removing the carat ^ from the concat

complete code excerpt :

```<code>const exclude = include.filter((d) => {
                let negate1 = '['
                let negate2 = ']'
                let negate = negate1.concat(letterexc).concat(negate2)
                let exclRegex = new RegExp(negate,'g')
                console.log(exclRegex) //return --> /[^anyletter]/g
                return !d.list.match(exclRegex)
            })
</code>```

Body:
I want to filter my array with an exclusion so I did

const exclude = include.filter((d) => {
                let negate1 = '[^'
                let negate2 = ']'
                let negate = negate1.concat(letterexc).concat(negate2)
                let exclRegex = new RegExp(negate,'g')
                console.log(exclRegex) //return --> /[^anyletter]/g
                return d.list.match(exclRegex)
            })

I add [^ and letterexc variable from an input field and ] to make a negation regex, but its not working. not filtering anything.

I read and tried my pattern here https://regexr.com/ and found if my pattern actually works, but not on my own.

Another article from MDN and link says the similar pattern works (with caret after bracket)

EDIT:
I added a pen link. It's filtering with 2 input field for letter included and excluded. The included filter works fine

Body:
I found it

I change

d.list.match(exclRegex)

to

!d.list.match(exclRegex)

while removing the carat ^ from the concat

complete code excerpt :

const exclude = include.filter((d) => {
                let negate1 = '['
                let negate2 = ']'
                let negate = negate1.concat(letterexc).concat(negate2)
                let exclRegex = new RegExp(negate,'g')
                console.log(exclRegex) //return --> /[^anyletter]/g
                return !d.list.match(exclRegex)
            })