问:
Node.js DNS lookup - how to set timeout?
I'm very new to Node.js and I'm having an issue using node.dns.resolveNs function. </p>

<p>Some domains are completely down and it takes about a minute to get the response, which is usually "queryNs ETIMEOUT". Is there a way for me to set it to a shorter period, for example 10 seconds? </p>

答:
Wrapper for resolveNs with timeout:</p>
```<code>const dns = require("dns");

const nsLookup = (domain, timeout) => {
  return new Promise((resolve, reject) => {
    let finished = false;

    const timer = setTimeout(()=>{
      finished = true;
      reject();
    }, timeout);

    const callback = (_err, result) => {
      clearTimeout(timer);
      if (!finished) resolve(result);
    };

    dns.resolveNs(domain, callback);
  });
};
</code>```

Body:
I'm very new to Node.js and I'm having an issue using node.dns.resolveNs function.

Some domains are completely down and it takes about a minute to get the response, which is usually "queryNs ETIMEOUT". Is there a way for me to set it to a shorter period, for example 10 seconds?

Body:
Wrapper for resolveNs with timeout:

const dns = require("dns");

const nsLookup = (domain, timeout) => {
  return new Promise((resolve, reject) => {
    let finished = false;

    const timer = setTimeout(()=>{
      finished = true;
      reject();
    }, timeout);

    const callback = (_err, result) => {
      clearTimeout(timer);
      if (!finished) resolve(result);
    };

    dns.resolveNs(domain, callback);
  });
};


来源: stackexchange

问:
Change the default React Native <Picker> drop-down arrow icon
I want to change its color specifically:</p>

```<code><Picker selectedValue={this.state.selected}
        onValueChange={(value) => this.setState({selected:value})}  >
  {data.map ((value)=><Picker.Item label={value} value={value} key={value}/>)}
</Picker>
</code>```

答:
I made a workaround is to make the picker disappear by setting its display property to none as well as its opacity to 0 and by making another view make do the job by referencing the actual picker;

Here is an example of a year picker.

import { View, Text, TouchableOpacity } from 'react-native';
import React, { useState, useRef } from 'react';
import { Picker } from '@react-native-picker/picker';

const renderYears = () =>
  [
    ...Array.from(
      { length: new Date().getFullYear() - 1900 },
      (value, index) => 1900 + index,
    ),
  ]
    .reverse()
    .map(n => <Picker.Item key={n + ''} label={n + ''} value={n + ''} />);

const YearPicker = () => {
  const ref = useRef();
  const [selectedYear, setSelectedYear] = useState();

  const handleOpenPicker = () => {
    ref.current.focus();
  };

  const handleClosePicker = () => {
    ref.current.blur();
  }

  return (
    <>
      <TouchableOpacity
        onPress={handleOpenPicker}
        style={{
          backgroundColor: 'pink',
          height: 48,
          justifyContent: 'center',
          alignItems: 'center',
        }}>
        <Text>Select Year</Text>
        <Picker
          style={{ display: 'none', opacity: 0, height: 0, width: 0 }}
          ref={ref}
          selectedValue={selectedYear}
          onValueChange={(v, i) => setSelectedYear(v)}>
          {renderYears()}
        </Picker>
      </TouchableOpacity>
      <Text>{selectedYear}</Text>
    </>
  );
};

export default YearPicker;

```

ContentLicense: CC BY-SA 3.0

Body:
I want to change its color specifically:

<Picker selectedValue={this.state.selected}
        onValueChange={(value) => this.setState({selected:value})}  >
  {data.map ((value)=><Picker.Item label={value} value={value} key={value}/>)}
</Picker>

ContentLicense: CC BY-SA 4.0


问:
How to Change VS Code Code.exe Path for Update?
[Windows 10] I have "Microsoft VS Code (User Setup)" installed in a custom directory and whenever I try to update it this shows up:

and then this

```<code>Log Info

Dec 23 11:42:40.673 INFO Starting: C:\Users\jeremy\AppData\Local\Programs\Microsoft VS Code\Code.exe, false
Dec 23 11:42:40.674 ERRO Bad arguments: Code path doesn't seem to exist: C:\Users\jeremy\AppData\Local\Programs\Microsoft VS Code\Code.exe
</code>```

How do I change the path to point it to the right directory where "Code.exe" exists?

答:
Create a hard link for Code.exe using mklink, works for me.

Command should look like this (depends where your custom installation is, my in C:/Program Files/Microsoft VS Code/):

```<code>mklink /H "C:/Users/$username/AppData/Local/Programs/Microsoft VS Code/Code.exe" "C:/Program Files/Microsoft VS Code/Code.exe"
</code>```

Body:
[Windows 10] I have "Microsoft VS Code (User Setup)" installed in a custom directory and whenever I try to update it this shows up:

and then this

Log Info

Dec 23 11:42:40.673 INFO Starting: C:\Users\jeremy\AppData\Local\Programs\Microsoft VS Code\Code.exe, false
Dec 23 11:42:40.674 ERRO Bad arguments: Code path doesn't seem to exist: C:\Users\jeremy\AppData\Local\Programs\Microsoft VS Code\Code.exe

How do I change the path to point it to the right directory where "Code.exe" exists?

Body:
Create a hard link for Code.exe using mklink, works for me.

Command should look like this (depends where your custom installation is, my in C:/Program Files/Microsoft VS Code/):

mklink /H "C:/Users/$username/AppData/Local/Programs/Microsoft VS Code/Code.exe" "C:/Program Files/Microsoft VS Code/Code.exe"


问:
Django: Access related object attributes from a form field in a template?
I'm building a page that allows users to edit Task and related Activity records (one task can have many activities), all on the same page.  Here are extracts from my code...

models.py

```<code>from django.contrib.auth.models import User

class Task(models.Model):
    category    = models.CharField(max_length=300)
    description = models.CharField(max_length=300)

class Activity(models.Model):
    task  = models.ForeignKey(Task, on_delete=models.CASCADE)
    title = models.CharField(max_length=150)
    notes = models.TextField(blank=True)
    owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
</code>```

The activity "owner" is linked to a User from the Django standard user model.

views.py

```<code>def manage_task(request, pk):
    task = Task.objects.get(pk = pk)
    TaskInlineFormSet = inlineformset_factory(Task, Activity,
        form = ActivityForm)
    if request.method == "POST":
        form = TaskForm(request.POST, instance = task)
        formset = TaskInlineFormSet(request.POST, instance = task)
        if form.has_changed() and form.is_valid():
            form.save()
        if formset.has_changed() and formset.is_valid():
            formset.save()
        return redirect('manage_task',pk=task.id)
    else:
        form = TaskForm(instance = task)
        formset = TaskInlineFormSet(instance = task)
    context = {'task': task, 'task_form': form, 'formset': formset}
    return render(request, 'tasks/manage_task.html', context)

</code>```

And manage_task.html excerpt:

```<code><h2>{{ task.category }}</h2>
<form method="post">
    {% csrf_token %}
    {{ task_form.description }}
    {% for form in formset %}
        {{ form.id }}
        {{ form.title }}</br>
        {{ form.notes }}</br>
        {% if user.id == form.owner.value %}
            You own this Activity!</br>
        {% else %}
            {{ form.owner.first_name }} owns this Activity</br>
        {% endif %}
    {% endfor %}
    <input class="save" type="submit" value="SAVE">
</form>
</code>```

Perhaps obviously, {{ form.owner.first_name }} doesn't return anything.  form.owner understandably renders as a select drop down with all the Users listed - it's some sort of iterable object so it doesn't have a first_name attribute.

I think I need to have the first_name field in each form in the formset so it ties up properly with the correct Activity form.

I feel like I might have to adapt the view in some way to go through all the forms in the formset and use the owner.id (if it exists) to access the related User and add the first_name attribute as an extra field in the form somehow?  That doesn't feel very Djangoish, there must be a better way.

How can I use the form field form.owner to get the first_name attribute from the User object that's related to the Activity so I can use it in the template?

答:
You should not take such value from form directly. It may be risky (i.e. changing real-life). But if you are aware of it and ok with that, try pointing to specific instance of form:

```<code>{{ form.instance.owner.first_name }}
</code>```

Body:
I'm building a page that allows users to edit Task and related Activity records (one task can have many activities), all on the same page.  Here are extracts from my code...

models.py

from django.contrib.auth.models import User

class Task(models.Model):
    category    = models.CharField(max_length=300)
    description = models.CharField(max_length=300)

class Activity(models.Model):
    task  = models.ForeignKey(Task, on_delete=models.CASCADE)
    title = models.CharField(max_length=150)
    notes = models.TextField(blank=True)
    owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)

The activity "owner" is linked to a User from the Django standard user model.

views.py

def manage_task(request, pk):
    task = Task.objects.get(pk = pk)
    TaskInlineFormSet = inlineformset_factory(Task, Activity,
        form = ActivityForm)
    if request.method == "POST":
        form = TaskForm(request.POST, instance = task)
        formset = TaskInlineFormSet(request.POST, instance = task)
        if form.has_changed() and form.is_valid():
            form.save()
        if formset.has_changed() and formset.is_valid():
            formset.save()
        return redirect('manage_task',pk=task.id)
    else:
        form = TaskForm(instance = task)
        formset = TaskInlineFormSet(instance = task)
    context = {'task': task, 'task_form': form, 'formset': formset}
    return render(request, 'tasks/manage_task.html', context)

And manage_task.html excerpt:

{{ task.category }}

<form method="post">
    {% csrf_token %}
    {{ task_form.description }}
    {% for form in formset %}
        {{ form.id }}
        {{ form.title }}

        {{ form.notes }}

        {% if user.id == form.owner.value %}
            You own this Activity!

        {% else %}
            {{ form.owner.first_name }} owns this Activity

        {% endif %}
    {% endfor %}
    <input class="save" type="submit" value="SAVE">
</form>

Perhaps obviously, {{ form.owner.first_name }} doesn't return anything.  form.owner understandably renders as a select drop down with all the Users listed - it's some sort of iterable object so it doesn't have a first_name attribute.

I think I need to have the first_name field in each form in the formset so it ties up properly with the correct Activity form.

I feel like I might have to adapt the view in some way to go through all the forms in the formset and use the owner.id (if it exists) to access the related User and add the first_name attribute as an extra field in the form somehow?  That doesn't feel very Djangoish, there must be a better way.

How can I use the form field form.owner to get the first_name attribute from the User object that's related to the Activity so I can use it in the template?

Body:
You should not take such value from form directly. It may be risky (i.e. changing real-life). But if you are aware of it and ok with that, try pointing to specific instance of form:

{{ form.instance.owner.first_name }}


问:
C# beginner has a problem with class attributes
I am a C# beginner and and I've been working on object-orientation for the past few days.
That is why please excuse my if the question is dumb.

I wrote 2 attributes for a class. Can anyone say to me where is the difference between the first and the second?

```<code>public class house
{
    private int Height;
    public int _Height
    {
        get { return Height; }
    }

    public int height { get; }
}
</code>```

Is there a difference between?

答:
C# knows fields and properties. A field stores data, a property accesses it. In the basic form, this looks as follows:

public class House
{
    private int _height; // a field storing an integer
    public int Height // A property that can be used to access the _height field
    {
        get
        {
            return _height;
        }
        set
        {
            _height = value;
        }
    }
}
```
<p>The above is, for an outside viewer (almost) equivalent to:</p>
<pre class="lang-cs prettyprint-override"><code>public class House
{
    public int Height; // a public field storing an integer
}
</code>```

but this is discouraged, because fields should not be public. If you want to change something inside your class later, that gets more difficult.

The property has different advantages, one of them being that you can debug when the value gets changed, or you can verify that the value is in range (e.g that no one is setting a negative height). You can also leave away the setter, which allows the users of the class to only read the field, but not set it.

Since properties are so common in C#, the following abbreviation is allowed:

public class House
{
    public int Height // An auto-implemented property
    {
        get;
        set;
    }
}
```
<p>These properties are called auto-implemented. Again, for an outsider, this looks exactly the same and the compiler actually converts this to exactly the same code as the first example above. The only difference is that you cannot directly access the field. And you cannot add verification code with this syntax.</p>
<p>So basically, the three variants achieve almost the same result and it is mostly a matter of taste which one to use. By convention, the last variant is mostly used if no verification needs to be done, otherwise variant 1.</p>
<p>Per comment, here is an example with verification:</p>
<pre class="lang-cs prettyprint-override"><code>public class House
{
    private int _height; // a field storing an integer
    public int Height // A property that can be used to access the _height field
    {
        get
        {
            return _height;
        }
        set
        {
            if (value < 0)
            {
                 throw new InvalidOperationException("The height of a house cannot be less than 0");
            }
            _height = value;
        }
    }
}
</code>```

Body:
I am a C# beginner and and I've been working on object-orientation for the past few days.
That is why please excuse my if the question is dumb.

I wrote 2 attributes for a class. Can anyone say to me where is the difference between the first and the second?

public class house
{
    private int Height;
    public int _Height
    {
        get { return Height; }
    }

    public int height { get; }
}

Is there a difference between?

Body:
C# knows fields and properties. A field stores data, a property accesses it. In the basic form, this looks as follows:

public class House
{
    private int _height; // a field storing an integer
    public int Height // A property that can be used to access the _height field
    {
        get
        {
            return _height;
        }
        set
        {
            _height = value;
        }
    }
}

The above is, for an outside viewer (almost) equivalent to:

public class House
{
    public int Height; // a public field storing an integer
}

but this is discouraged, because fields should not be public. If you want to change something inside your class later, that gets more difficult.

The property has different advantages, one of them being that you can debug when the value gets changed, or you can verify that the value is in range (e.g that no one is setting a negative height). You can also leave away the setter, which allows the users of the class to only read the field, but not set it.

Since properties are so common in C#, the following abbreviation is allowed:

public class House
{
    public int Height // An auto-implemented property
    {
        get;
        set;
    }
}

These properties are called auto-implemented. Again, for an outsider, this looks exactly the same and the compiler actually converts this to exactly the same code as the first example above. The only difference is that you cannot directly access the field. And you cannot add verification code with this syntax.

So basically, the three variants achieve almost the same result and it is mostly a matter of taste which one to use. By convention, the last variant is mostly used if no verification needs to be done, otherwise variant 1.

Per comment, here is an example with verification:

public class House
{
    private int _height; // a field storing an integer
    public int Height // A property that can be used to access the _height field
    {
        get
        {
            return _height;
        }
        set
        {
            if (value < 0)
            {
                 throw new InvalidOperationException("The height of a house cannot be less than 0");
            }
            _height = value;
        }
    }
}


问:
Accessing User.currentUser from Boot.scala onAboutToShutdownSession
I'm working on an eShop project in Lift right now. For convenience reasons every user that visits the shop is assigned a persistent ProtoUser entry in Mapper. This entry is flagged temporary.
I now have to delete the DB-entry on session termination using onAboutToShutdownSession

Obviously i don't have access to User.currentUser there, as i'm outside a session. (?) I still have the LiftSession Reference in my function.

The question is: How can I access the currentUser (or even currentUserId) SessionVar from either the context of LiftSession or Boot.scala

Thanks for your answers!

Andreas

答:
You can't access a SessionVar outside a session.

If you've constructed a function during the servicing of a request, you can do something like:

```<code>val id = User.currentUserId.get
val f: () => Unit = () => {
   id.foreach{realId => deleteFromDatabase(realId)
}
</code>```

Because the id val is captured within the scope of a request and f closes over scope, the value of User.currentUserId will be captured and the function will be able to delete the user from the database.

Body:
You can't access a SessionVar outside a session.

If you've constructed a function during the servicing of a request, you can do something like:

val id = User.currentUserId.get
val f: () => Unit = () => {
   id.foreach{realId => deleteFromDatabase(realId)
}

Because the id val is captured within the scope of a request and f closes over scope, the value of User.currentUserId will be captured and the function will be able to delete the user from the database.


问:
ValueError: Cannot assign "": "Message.name" must be a "CustomUser" instance
I am building a live chat for my website and encountered this error message while trying to save messages to database. I used this tutorial to create the live chat and am now trying to implement it to my site. The difference is that I do not need different rooms and I want only authorized users to access the chat. The problem comes because I use foreign key on my Messages model to create a link with CustomUser model. I am using channels.

template where the data comes from:

```<code>const chatSocket = new WebSocket(
            'ws://'
            + window.location.host
        )

        chatSocket.onmessage = function(e) {
            console.log(e);

            const data = JSON.parse(e.data)

            if(data.message) {
                document.querySelector('#chat-messages').innerHTML += ('<b>' + data.username + ': </b>' + data.message + '<br>')
            } else {
                alert('Empty!')
            }

        }

        chatSocket.onclose = function(e) {
            console.log('The socket closed unexpectedly');
        }

        document.querySelector('#chat-message-submit').onclick = function(e) {
            const messageInputDom = document.querySelector('#chat-message-input')
            const message = messageInputDom.value

            chatSocket.send(JSON.stringify({
                'message': message,
                'name': {{request.user}},
            }))

            messageInputDom.value = ''
        }
</code>```

code used for saving into database in consumers.py

```<code>def save_message(self, name, message):
        Message.objects.create(name=name, content=message)
</code>```

models.py

```<code>from django.db import models

from django.contrib.auth.models import AbstractUser

from .managers import CustomUserManager

# Create your models here.

class CustomUser(AbstractUser):
    username = models.CharField(max_length=32, blank=True, null=True)

    name = models.CharField(max_length=200, unique=True)

    steam_id = models.CharField(max_length=17, unique=True, blank=True, null=True, db_column='steam_id')
    player = models.TextField(null=True)
    user_coins = models.FloatField(default=0.00)

    is_active = models.BooleanField(default=True, db_column='status')
    is_staff = models.BooleanField(default=False, db_column='isstaff')
    is_superuser = models.BooleanField(default=False, db_column='issuperuser')

    USERNAME_FIELD = "name"
    REQUIRED_FIELDS = []

    objects = CustomUserManager()

    def __str__(self):
        return self.username

    def has_perm(self, perm, obj=None):
        return self.is_superuser

    def has_module_perms(self, app_label):
        return self.is_superuser

class Message(models.Model):
    name = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True)
    content = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('date_added',)
</code>```

答:
By looking at your Message model, name is a ForeignKey to CustomUser model. So problem is in your save_message as you provide name as string but it must be CustomUser instance.
So change save_message in your consumers.py from this

```<code>def save_message(self, name, message):
    Message.objects.create(name=name, content=message)
</code>```

To

```<code>def save_message(self, name, message):
    Message.objects.create(name=user_obj, content=message) <--- add custom user object accordingly
</code>```

Body:
I am building a live chat for my website and encountered this error message while trying to save messages to database. I used this tutorial to create the live chat and am now trying to implement it to my site. The difference is that I do not need different rooms and I want only authorized users to access the chat. The problem comes because I use foreign key on my Messages model to create a link with CustomUser model. I am using channels.

template where the data comes from:

const chatSocket = new WebSocket(
            'ws://'
            + window.location.host
        )

        chatSocket.onmessage = function(e) {
            console.log(e);

            const data = JSON.parse(e.data)

            if(data.message) {
                document.querySelector('#chat-messages').innerHTML += ('' + data.username + ': ' + data.message + '
')
            } else {
                alert('Empty!')
            }

        }

        chatSocket.onclose = function(e) {
            console.log('The socket closed unexpectedly');
        }

        document.querySelector('#chat-message-submit').onclick = function(e) {
            const messageInputDom = document.querySelector('#chat-message-input')
            const message = messageInputDom.value

            chatSocket.send(JSON.stringify({
                'message': message,
                'name': {{request.user}},
            }))

            messageInputDom.value = ''
        }

code used for saving into database in consumers.py

def save_message(self, name, message):
        Message.objects.create(name=name, content=message)

models.py

from django.db import models

from django.contrib.auth.models import AbstractUser

from .managers import CustomUserManager

# Create your models here.

class CustomUser(AbstractUser):
    username = models.CharField(max_length=32, blank=True, null=True)

    name = models.CharField(max_length=200, unique=True)

    steam_id = models.CharField(max_length=17, unique=True, blank=True, null=True, db_column='steam_id')
    player = models.TextField(null=True)
    user_coins = models.FloatField(default=0.00)

    is_active = models.BooleanField(default=True, db_column='status')
    is_staff = models.BooleanField(default=False, db_column='isstaff')
    is_superuser = models.BooleanField(default=False, db_column='issuperuser')

    USERNAME_FIELD = "name"
    REQUIRED_FIELDS = []

    objects = CustomUserManager()

    def __str__(self):
        return self.username

    def has_perm(self, perm, obj=None):
        return self.is_superuser

    def has_module_perms(self, app_label):
        return self.is_superuser

class Message(models.Model):
    name = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True)
    content = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('date_added',)

Body:
By looking at your Message model, name is a ForeignKey to CustomUser model. So problem is in your save_message as you provide name as string but it must be CustomUser instance.
So change save_message in your consumers.py from this

def save_message(self, name, message):
    Message.objects.create(name=name, content=message)

To

def save_message(self, name, message):
    Message.objects.create(name=user_obj, content=message) <--- add custom user object accordingly


问:
Split words from datraframe by space to rows while duplicating the info from other columns ( python,pandas)
I have a df which is composed by 5 columns one being a comment column where people leave a comment.

What I would like to do is split that comment column by space into multiple rows while duplicating the other columns:

df:

r_id
start
comments

1
2021-01-01
i am the text that needs splitting by space to rows

2
2021-01-02
hello hello

wanted result:

r_id
start
comments

1
2021-01-01
i

1
2021-01-01
am

1
2021-01-01
the

1
2021-01-01
text

2
2021-01-02
hello

2
2021-01-02
hello

I've tried anything from str.split() to regex without result.

-- le with code:

```<code>df = df.apply(lambda x: x.str.lower() if x.dtype == "object" else x)
(df
 .assign(comments=df['comments'].str.split())
 .explode('comments')
)
print(df)

df['comments'] = df['comments'].str.replace('ă','a')
df['comments'] = df['comments'].str.replace('â','a')
df['comments'] = df['comments'].str.replace('î','i')
df['comments'] = df['comments'].str.replace('ș','s')
df['comments'] = df['comments'].str.replace('ț','t')
df.replace('[^a-zA-Z0-9]', ' ',regex=True)
df.dropna(inplace=True)
print(df)
</code>```

yet it wouldn't  split the comment

Body:
I have a df which is composed by 5 columns one being a comment column where people leave a comment.

What I would like to do is split that comment column by space into multiple rows while duplicating the other columns:

df:

r_id
start
comments

1
2021-01-01
i am the text that needs splitting by space to rows

2
2021-01-02
hello hello

wanted result:

r_id
start
comments

1
2021-01-01
i

1
2021-01-01
am

1
2021-01-01
the

1
2021-01-01
text

2
2021-01-02
hello

2
2021-01-02
hello

I've tried anything from str.split() to regex without result.

-- le with code:

df = df.apply(lambda x: x.str.lower() if x.dtype == "object" else x)
(df
 .assign(comments=df['comments'].str.split())
 .explode('comments')
)
print(df)

df['comments'] = df['comments'].str.replace('ă','a')
df['comments'] = df['comments'].str.replace('â','a')
df['comments'] = df['comments'].str.replace('î','i')
df['comments'] = df['comments'].str.replace('ș','s')
df['comments'] = df['comments'].str.replace('ț','t')
df.replace('[^a-zA-Z0-9]', ' ',regex=True)
df.dropna(inplace=True)
print(df)

yet it wouldn't  split the comment

Body:
You need to split and explode:

df2 = (df
 .assign(comments=df['comments'].str.split())
 .explode('comments')
)

output:

   r_id        start    comments
0      1  2021-01-01           i
0      1  2021-01-01          am
0      1  2021-01-01         the
0      1  2021-01-01        text
0      1  2021-01-01        that
0      1  2021-01-01       needs
0      1  2021-01-01   splitting
0      1  2021-01-01          by
0      1  2021-01-01       space
0      1  2021-01-01          to
0      1  2021-01-01        rows
1      2  2021-01-02       hello
1      2  2021-01-02       hello


问:
replace list of sentence to the text
I am trying to replace the text if it contains the sentences from a list1.

I tried the following code, but it's not working:

```<code>text = "what a lovely car it is , i love it by the way it looks and the color is so good . i am feeling very happy after ) seeing it"
list1 = ['lovely car it is', 'color is so good','happy after )']

#code i tried
for i in list1:
  if i in text:
    text.replace(i,"")

#wrong output:
'what a lovely car it is , i love it by the way it looks and the color is so good. i am feeling very happy after seeing it'
</code>```

Expected output:

```<code>'what a , i love it by the way it looks and the . i am feeling very seeing it'
</code>```

答:
You are almost correct, the only error is the statement: , text.replace() This function does not make changes to the original variable, it returns an object that is a copy of the original object, so you need to assign it to text.
Code:

```<code>text = "what a lovely car it is , i love it by the way it looks and the color is so good . i am feeling very happy after ) seeing it"
list1 = ['lovely car it is', 'color is so good','happy after )']

#code i tried
for i in list1:
    if i in text:
        text = text.replace(i,"")
</code>```

Title: replace list of sentence to the text

Body:
I am trying to replace the text if it contains the sentences from a list1.

I tried the following code, but it's not working:

text = "what a lovely car it is , i love it by the way it looks and the color is so good . i am feeling very happy after ) seeing it"
list1 = ['lovely car it is', 'color is so good','happy after )']

#code i tried
for i in list1:
  if i in text:
    text.replace(i,"")

#wrong output:
'what a lovely car it is , i love it by the way it looks and the color is so good. i am feeling very happy after seeing it'

Expected output:

'what a , i love it by the way it looks and the . i am feeling very seeing it'

Body:
You are almost correct, the only error is the statement: , text.replace() This function does not make changes to the original variable, it returns an object that is a copy of the original object, so you need to assign it to text.
Code:

text = "what a lovely car it is , i love it by the way it looks and the color is so good . i am feeling very happy after ) seeing it"
list1 = ['lovely car it is', 'color is so good','happy after )']

#code i tried
for i in list1:
    if i in text:
        text = text.replace(i,"")


问:
Flutter text field showing label on center
I want to use the max line for my TextField to show the Textfield height a little more. But the issue is my label goes centered if I use max line. I want to show the label at the start not on center

My code

```<code>  TextFormField(
    maxLines: 3,
    decoration: new InputDecoration(
      labelText: "Description",
      labelStyle: TextStyle(
          color: textGreyColor,
          fontFamily: 'SegoeUI'),
      fillColor: Colors.white,
      focusedBorder: OutlineInputBorder(
        borderSide: BorderSide(
            color: kPrimaryColor, width: 1.0),
      ),
      enabledBorder: OutlineInputBorder(
        borderSide: BorderSide(
            color: Color(0xffE6E6E6), width: 1.0),
      ),

      border: new OutlineInputBorder(
        borderRadius: new BorderRadius.circular(10),
        borderSide: new BorderSide(
            color: Color(0xffE6E6E6)),
      ),
      //fillColor: Colors.green
    ),
    keyboardType: TextInputType.emailAddress,
    style: new TextStyle(
        fontFamily: "SegoeUI",
        color: kPrimaryColor),
  )
</code>```

答: You can pass alignLabelWithHint: true to InputDecoration to cause the label to align to the top.

Body:
I want to use the max line for my TextField to show the Textfield height a little more. But the issue is my label goes centered if I use max line. I want to show the label at the start not on center

My code

  TextFormField(
    maxLines: 3,
    decoration: new InputDecoration(
      labelText: "Description",
      labelStyle: TextStyle(
          color: textGreyColor,
          fontFamily: 'SegoeUI'),
      fillColor: Colors.white,
      focusedBorder: OutlineInputBorder(
        borderSide: BorderSide(
            color: kPrimaryColor, width: 1.0),
      ),
      enabledBorder: OutlineInputBorder(
        borderSide: BorderSide(
            color: Color(0xffE6E6E6), width: 1.0),
      ),

      border: new OutlineInputBorder(
        borderRadius: new BorderRadius.circular(10),
        borderSide: new BorderSide(
            color: Color(0xffE6E6E6)),
      ),
      //fillColor: Colors.green
    ),
    keyboardType: TextInputType.emailAddress,
    style: new TextStyle(
        fontFamily: "SegoeUI",
        color: kPrimaryColor),
  )


问:
How can I display a bing map in any HTML page?
Bing's got something they call "an AJAX control" that can dynamically embed generated maps into any webpage. There's an online interactive demo for the control. </p>

<p>How can I use this control? </p>

答:
See the demonstration.

There's a Javascript class library available at

http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0

You need to include it into your page like this:

```<code>  <script type="text/javascript"
          src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
</code>```

And then call it from within javascript like this:

```<code>var map = new Microsoft.Maps.Map(document.getElementById('SDKmap'),
                                 {credentials: 'Your Bing Maps Key'});
</code>```

To get a bing maps key, go to  this page.

You need a div with that id in your HTML page, and it should be sized and styled position:relative:

```<code><div id="SDKmap" style="position:relative; height:400px; width:400px">
</code>```

You can then add information boxes and pushpins to that map.

I also built a javascript helper that can extract custom attributes form the div element, and generate the map for you, complete with pushpins and infoboxes.  like this:

```<code>  <div id='map3'
       class='map'
       data-mapdata='center: 42.3 -78.0; zoom:7;pushpin:42.323 -78.80; pushpin:42.93 -77.189; pushpin: 41.13 -78.389'></div>
</code>```

And then the javascript:

```<code>        bingMap.displayMap("map3");
</code>```

The js module containing the helper class is available on the jsfiddle link.

Body:
Bing's got something they call "an AJAX control" that can dynamically embed generated maps into any webpage. There's an online interactive demo for the control.

How can I use this control?

Body:
See the demonstration.

There's a Javascript class library available at

http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0

You need to include it into your page like this:

  <script type="text/javascript"
          src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

And then call it from within javascript like this:

var map = new Microsoft.Maps.Map(document.getElementById('SDKmap'),
                                 {credentials: 'Your Bing Maps Key'});

To get a bing maps key, go to  this page.

You need a div with that id in your HTML page, and it should be sized and styled position:relative:

<div id="SDKmap" style="position:relative; height:400px; width:400px">

You can then add information boxes and pushpins to that map.

I also built a javascript helper that can extract custom attributes form the div element, and generate the map for you, complete with pushpins and infoboxes.  like this:

  <div id='map3'
       class='map'
       data-mapdata='center: 42.3 -78.0; zoom:7;pushpin:42.323 -78.80; pushpin:42.93 -77.189; pushpin: 41.13 -78.389'></div>

And then the javascript:

        bingMap.displayMap("map3");

The js module containing the helper class is available on the jsfiddle link.


问:
How to make a tkinter window align to the right
i have made a tkinter window like this

```<code>from tkinter import *
root = Tk()

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

now I need to align this window to the top-right without using root.geometry(). If anyone knows please help.

Thank You.

答:
The geometry method is tkinter's tool specifically for positioning the window. There isn't a better solution.

From the geometry documentation:

X and y specify the desired location of window on the screen, in pixels. If x is preceded by +, it specifies the number of pixels between the left edge of the screen and the left edge of window's border; if preceded by - then x specifies the number of pixels between the right edge of the screen and the right edge of window's border. If y is preceded by + then it specifies the number of pixels between the top of the screen and the top of window's border; if y is preceded by - then it specifies the number of pixels between the bottom of window's border and the bottom of the screen.

Thus, to position a window along the right edge of the window you can use an x of -0. If you want it in the top-right of the display you would use root.geometry("-0+0")

Body:
i have made a tkinter window like this

from tkinter import *
root = Tk()

root.mainloop()

now I need to align this window to the top-right without using root.geometry(). If anyone knows please help.

Thank You.


问:
How do I export import a template function
I have a template function, that I want to call from several .cpp files. Normally, I would have written this template function in a .h file and #include it, but I heard of C++20 modules and was curious how it could be imported / exported using this new C++20 feature.</p>
```<code>//latuile_test_json_output.cpp

template <unsigned N>
void latuile_test_json_output(const vector<MyRect> &input_rectangles,
                               int (&edges)[N][2],
                               const vector<MyRect> &expected_rectangles,
                               const char* test_name,
                               int test_number)
{
...
}
</code>```

答:
Your API is C++, but is to much influenced by C style code.
This N template parameter is completely useless.

Since you are using C++20 just use std::span and you are done:

void latuile_test_json_output(const vector<MyRect> &input_rectangles,
                              std::span<std::array<int, 2> edges,
                              const vector<MyRect> &expected_rectangles,
                              std::string_view test_name,
                              int test_number)
{
...
}
// or if you think std::array is to much:
void latuile_test_json_output(const vector<MyRect> &input_rectangles,
                              std::span<int[2]> edges,
                              const vector<MyRect> &expected_rectangles,
                              std::string_view test_name,
                              int test_number)
{
...
}
```

In this form function is no longer a template, so no problem to export this function from dll.

Note that std::span has respective constructor to handle c-style arrays:
std::span<T,Extent>::span - cppreference.com

template< std::size_t N >

constexpr span( element_type (&arr)[N] ) noexcept; (4)

Body:
I have a template function, that I want to call from several .cpp files. Normally, I would have written this template function in a .h file and #include it, but I heard of C++20 modules and was curious how it could be imported / exported using this new C++20 feature.

//latuile_test_json_output.cpp

template <unsigned N>
void latuile_test_json_output(const vector<MyRect> &input_rectangles,
                               int (&edges)[N][2],
                               const vector<MyRect> &expected_rectangles,
                               const char* test_name,
                               int test_number)
{
...
}

Body:
Your API is C++, but is to much influenced by C style code.
This N template parameter is completely useless.

Since you are using C++20 just use std::span and you are done:

void latuile_test_json_output(const vector<MyRect> &input_rectangles,
                              std::span<std::array<int, 2> edges,
                              const vector<MyRect> &expected_rectangles,
                              std::string_view test_name,
                              int test_number)
{
...
}
// or if you think std::array is to much:
void latuile_test_json_output(const vector<MyRect> &input_rectangles,
                              std::span<int[2]> edges,
                              const vector<MyRect> &expected_rectangles,
                              std::string_view test_name,
                              int test_number)
{
...
}

In this form function is no longer a template, so no problem to export this function from dll.

Note that std::span has respective constructor to handle c-style arrays:
std::span<T,Extent>::span - cppreference.com

template< std::size_t N >

constexpr span( element_type (&arr)[N] ) noexcept; (4)


问:
Docker container getting connection refused from postgres container in docker-compose
I've been beating my head against this for a few days now and I'm finally asking for help after trying to find the solution myself from all over.

I have a docker-compose file that looks like this:

```<code>services:
   db:
      image: ...
      container_name: db
      ports:
         - "8095:5432"
      networks:
         - mynetwork
   springservice:
      image: ...
      container_name: springservice
      depends_on:
         - db
      ports:
         - "8090:8090"
      networks:
         - mynetwork
      environment:
         - SPRING_DATASOURCE_URL: jdbc:postgresql://db:8095/dbname
         - SPRING_DATASOURCE_USER: user
         - SPRING_DATASOURCE_PASSWORD: password
networks:
   mynetwork:
      driver: bridge
      name: mynetwork
</code>```

Postgres has to be put to another port because we've got 3 postgres containers in that compose, so each get their own port.

Postgres's listen_address is set to "*".
pg_hba is set with "host all 0.0.0.0/0 md5"

Both containers come up, but when I curl from the service container to http://db:8095/ , I get connection refused.

What am I missing here?

答:
Your port mapping is meaningless inside the docker network. This is only a mapping to the host system. Inside the network, the container is always available on its native port.

 - SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/dbname
```

Also note that you don't need to publish the port to access it from inside the network. Doing so for a database can impose security risks. If you can, you should not publish it. That way, it will be only accessible from inside the docker network.

Body:
I've been beating my head against this for a few days now and I'm finally asking for help after trying to find the solution myself from all over.

I have a docker-compose file that looks like this:

services:
   db:
      image: ...
      container_name: db
      ports:
         - "8095:5432"
      networks:
         - mynetwork
   springservice:
      image: ...
      container_name: springservice
      depends_on:
         - db
      ports:
         - "8090:8090"
      networks:
         - mynetwork
      environment:
         - SPRING_DATASOURCE_URL: jdbc:postgresql://db:8095/dbname
         - SPRING_DATASOURCE_USER: user
         - SPRING_DATASOURCE_PASSWORD: password
networks:
   mynetwork:
      driver: bridge
      name: mynetwork

Postgres has to be put to another port because we've got 3 postgres containers in that compose, so each get their own port.

Postgres's listen_address is set to "*".
pg_hba is set with "host all 0.0.0.0/0 md5"

Both containers come up, but when I curl from the service container to http://db:8095/ , I get connection refused.

What am I missing here?

Body:
Your port mapping is meaningless inside the docker network. This is only a mapping to the host system. Inside the network, the container is always available on its native port.

 - SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/dbname

Also note that you don't need to publish the port to access it from inside the network. Doing so for a database can impose security risks. If you can, you should not publish it. That way, it will be only accessible from inside the docker network.


问:
Any real Silverlight projects?
Appart from projects funded/pushed by MS itself, are there any real-world examples of projects that opted for Silverlight?

What were your experiences? Learning curve? Advantages? Resources? Pitfalls? Sacrifices?

--EDIT--

I'm most interested in the developing (team)'s story.

答: I even developed an Android app with Silverlight and Java mixture. Without SL it would be really damn boring and probably impossible what I wanted to achieve, check it out: https://market.android.com/details?id=uk.co.aloneguid.todash&feature=search_result</p>

OwnerDisplayName: boris callens

ContentLicense: CC BY-SA 2.5

Title: Any real Silverlight projects?

LastEditorDisplayName: boris callens


问:
Regular expression to parse css
I hope I find you well.

I realise that a generic regular expression to fit all css won't cut it in all cases, however I am parsing a particular piece of css so I can tweak this expression to fit my needs.

Having scoured SO, I did find some very useful regular expressions which I have combined with great success into the following:

```<code>parsed_css = re.findall(r'([\[\]=\"\#\.\w\-\,\s\n\r\t:@*]+)(\{[^\{\}].*?\})', css, re.DOTALL)
</code>```

This produces something like:

```<code>Selector: '.div-wrapper' rules: '{position:absolute;z-index:4;background:none!important;border:none!important}'
</code>```

However, I encounter problems when coming across keyframes rules like this:

```<code>@keyframes mymove { from {top: 0px;} to {top: 200px;}}
</code>```

Obviously the curlies are the problem but I'm hoping someone has some look ahead / look behind magic to produce the following in these rare instances:

```<code>Selector: '@keyframes mymove'
Rules: '{from {top: 0px;} to {top: 200px;}}'
</code>```

Many thanks!
Darren

答:
You can use pyparsing to parse such nested parentheses.

import pyparsing as pp

string = '@keyframes mymove {from {top: 0px;} to {top: 200px;}}'
pattern = pp.Regex(r'^.*?(?= \{)') + pp.original_text_for(pp.nested_expr('{', '}'))
selector, rules = pattern.parse_string(string)

# Tests
assert selector == '@keyframes mymove'
assert rules == '{from {top: 0px;} to {top: 200px;}}'
```

* pyparsing can be installed by pip install pyparsing

See also this post: Python: How to match nested parentheses with regex?

Title: Regular expression to parse css

Body:
I hope I find you well.

I realise that a generic regular expression to fit all css won't cut it in all cases, however I am parsing a particular piece of css so I can tweak this expression to fit my needs.

Having scoured SO, I did find some very useful regular expressions which I have combined with great success into the following:

parsed_css = re.findall(r'([\[\]=\"\#\.\w\-\,\s\n\r\t:@*]+)(\{[^\{\}].*?\})', css, re.DOTALL)

This produces something like:

Selector: '.div-wrapper' rules: '{position:absolute;z-index:4;background:none!important;border:none!important}'

However, I encounter problems when coming across keyframes rules like this:

@keyframes mymove { from {top: 0px;} to {top: 200px;}}

Obviously the curlies are the problem but I'm hoping someone has some look ahead / look behind magic to produce the following in these rare instances:

Selector: '@keyframes mymove'
Rules: '{from {top: 0px;} to {top: 200px;}}'

Many thanks!
Darren

Body:
You can use pyparsing to parse such nested parentheses.

import pyparsing as pp

string = '@keyframes mymove {from {top: 0px;} to {top: 200px;}}'
pattern = pp.Regex(r'^.*?(?= \{)') + pp.original_text_for(pp.nested_expr('{', '}'))
selector, rules = pattern.parse_string(string)

# Tests
assert selector == '@keyframes mymove'
assert rules == '{from {top: 0px;} to {top: 200px;}}'

* pyparsing can be installed by pip install pyparsing

See also this post: Python: How to match nested parentheses with regex?


问:
How to add SQLCLR to AWS with certificate?
I have created a SQLCLR functions works with RabbitMQ.
Added them to SQL Server as described here
https://nielsberglund.com/2017/07/01/sqlclr-and-certificates/
using certificate: created it, added to database, created Login etc.
It works fine.
Can add my SQLCLR functions to AWS RDS SQL Server database using the same way?
In particular SQL Server I do this way:

```<code>use master;
IF exists(select * from sys.syslogins where name = N''login21'') DROP LOGIN [login21];
IF exists(select * from sys.certificates where name = N''login21Cert21'')    DROP CERTIFICATE [login21Cert21];
CREATE CERTIFICATE [login21Cert21] FROM BINARY =
0x30820....;
CREATE LOGIN [login21] FROM CERTIFICATE [login21Cert21];
GRANT UNSAFE ASSEMBLY TO [login21];
</code>```

But the question is if it is possible to add certificate/login to AWS RDS SQLServer master database?

答:
I did a quick google search (literally "RDS CLR") and the first page is a link to AWS' documentation which says:

Common Runtime Language (CLR). On RDS for SQL Server 2016 and lower versions, CLR is supported in SAFE mode and using assembly bits only. CLR isn't supported on RDS for SQL Server 2017 and higher versions. For more information, see Common Runtime Language Integration in the Microsoft documentation."

Also, regarding your comment of not trying it because you don't have access to AWS, everyone has access. To try out what you're proposing would take about five minutes on a personal account. I'd guess that it would cost less than $1 USD and certainly less than $10.

Body:
I have created a SQLCLR functions works with RabbitMQ.
Added them to SQL Server as described here
https://nielsberglund.com/2017/07/01/sqlclr-and-certificates/
using certificate: created it, added to database, created Login etc.
It works fine.
Can add my SQLCLR functions to AWS RDS SQL Server database using the same way?
In particular SQL Server I do this way:

use master;
IF exists(select * from sys.syslogins where name = N''login21'') DROP LOGIN [login21];
IF exists(select * from sys.certificates where name = N''login21Cert21'')    DROP CERTIFICATE [login21Cert21];
CREATE CERTIFICATE [login21Cert21] FROM BINARY =
0x30820....;
CREATE LOGIN [login21] FROM CERTIFICATE [login21Cert21];
GRANT UNSAFE ASSEMBLY TO [login21];

But the question is if it is possible to add certificate/login to AWS RDS SQLServer master database?


问:
Azure Durable Functions - where's the HostBuilder equivalent?
I'm using an Azure Durable Function to orchestrate other functions, currently contained in the same project. I want to configure services and logging for those orchestrated functions. How can I do that?

Here is some more detail:

In a "normal" Azure Function I have a Program.cs and a Main method with the following code that sets up the environment for the function execution:

```<code>var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .ConfigureLogging(loggingBuilder => { loggingBuilder.SetMinimumLevel(LogLevel.Trace); })... etc. pp.
</code>```

Using the HostBuilder I can add additional logging providers, add caching services etc. Those services are then injected via the constructor of the Azure Function.

Now in comparison when creating a Durable Function project via the VS Code "Durable Function Orchestration" template there is no Program.cs, no HostBuilder and no constructor. There are just some static methods representing the orchestrator and an orchestrated function.

As there is no out-of-the-box HostBuilder in the "Durable Function Orchestration" template - how does the HostBuilder equivalent look like for Durable Functions? Whats the pattern or convention here? Do I write it myself? Or is there some instance floating around or initialization I can hook into? Or should orchestrated functions be put into separate Azure Function projects where I can make use of the HostBuilder?

Any hints are appreciated.

答:
By default the ILogger instance is injected in your functions, unless you are using DI.All you need to do is Use the ILogger.

```<code>[FunctionName("funcname")]
public async static Task RunOrchestrator(
    [OrchestrationTrigger] DurableOrchestrationContext context,
    ILogger log)
{
    log.LogInformation("Starting Orchestration");
}
</code>```

Check
Incase if you using Dependency injection you should just do the below in your startup builder.Services.AddLogging();

Also check

Body:
I'm using an Azure Durable Function to orchestrate other functions, currently contained in the same project. I want to configure services and logging for those orchestrated functions. How can I do that?

Here is some more detail:

In a "normal" Azure Function I have a Program.cs and a Main method with the following code that sets up the environment for the function execution:

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .ConfigureLogging(loggingBuilder => { loggingBuilder.SetMinimumLevel(LogLevel.Trace); })... etc. pp.

Using the HostBuilder I can add additional logging providers, add caching services etc. Those services are then injected via the constructor of the Azure Function.

Now in comparison when creating a Durable Function project via the VS Code "Durable Function Orchestration" template there is no Program.cs, no HostBuilder and no constructor. There are just some static methods representing the orchestrator and an orchestrated function.

As there is no out-of-the-box HostBuilder in the "Durable Function Orchestration" template - how does the HostBuilder equivalent look like for Durable Functions? Whats the pattern or convention here? Do I write it myself? Or is there some instance floating around or initialization I can hook into? Or should orchestrated functions be put into separate Azure Function projects where I can make use of the HostBuilder?

Any hints are appreciated.

Body:
By default the ILogger instance is injected in your functions, unless you are using DI.All you need to do is Use the ILogger.

[FunctionName("funcname")]
public async static Task RunOrchestrator(
    [OrchestrationTrigger] DurableOrchestrationContext context,
    ILogger log)
{
    log.LogInformation("Starting Orchestration");
}

Check
Incase if you using Dependency injection you should just do the below in your startup builder.Services.AddLogging();

Also check


问:
Timeout Pattern - How bad is Thread.Abort really?
I've read at various websites that Thread.Abort is not very good to use. In this case, how do you implement a timeout pattern? For instance, I've read that MS uses the pattern below (which I've wrapped in an extension method) throughout the framework. Personally, I think this is a pretty cool extension, but I'm worried about the Thread.Abort. Does anyone have a better way?</p>

```<code> public static bool CallandWait(this Action action, int timeout)
    {
        Thread subThread = null;
        Action wrappedAction = () =>
        {
            subThread = Thread.CurrentThread;
            action();
        };

        IAsyncResult result = wrappedAction.BeginInvoke(null, null);

        if (((timeout != -1) && !result.IsCompleted) && (!result.AsyncWaitHandle.WaitOne(timeout, false) || !result.IsCompleted))
        {
            if (subThread != null)
            {
                subThread.Abort();
            }

            return false;
        }
        else
        {
            wrappedAction.EndInvoke(result);
            return true;
        }
    }
</code>```

答:
Potentially very bad.

The aborted thread could leave shared state corrupted, could leave asynchronous operations running, ...

See Joe Duffy's blog: "Managed code and asynchronous exception hardening".

OwnerDisplayName: Steve

Body:
I've read at various websites that Thread.Abort is not very good to use. In this case, how do you implement a timeout pattern? For instance, I've read that MS uses the pattern below (which I've wrapped in an extension method) throughout the framework. Personally, I think this is a pretty cool extension, but I'm worried about the Thread.Abort. Does anyone have a better way?

 public static bool CallandWait(this Action action, int timeout)
    {
        Thread subThread = null;
        Action wrappedAction = () =>
        {
            subThread = Thread.CurrentThread;
            action();
        };

        IAsyncResult result = wrappedAction.BeginInvoke(null, null);

        if (((timeout != -1) && !result.IsCompleted) && (!result.AsyncWaitHandle.WaitOne(timeout, false) || !result.IsCompleted))
        {
            if (subThread != null)
            {
                subThread.Abort();
            }

            return false;
        }
        else
        {
            wrappedAction.EndInvoke(result);
            return true;
        }
    }

OwnerDisplayName: Richard


问:
Call variable inside class from function inside class without $this
I recently needed to change my function to static and now $this does not work, and i need to get variable in the same class is there way to do it without $this?</p>

答: Static functions, by definition, are never called on an instantiated object, so $this is meaningless in that context (doesn't point to the current object).


答:
I solved simply by putting an array of colors... it's not specified anywhere but when you concatenate you can keep the original colors by adding an array like color=['r', 'g', 'b']).
Here is the modification I used, in case anyone would know:</p>
```<code>    concat = pd.concat(merged_data_frames, axis=0, sort=True)
    concat = concat.sort_index(key=lambda x: x.str.split().str[1].str.zfill(5))
    concat.plot(kind='bar', y='total_mean', use_index=True, yerr='error_mean', edgecolor='black', color=['r', 'g', 'b'])
</code>```

Title: Pandas plot three dataframes on the same figure

Body:
I have tried many different solutions, but it seems I can't make it work.
I have nine dataframes (each 3 describe a system):

df = pd.read_csv('purged_0.csv', sep=',', header=6, usecols=['Location', 'TOTAL', 'Unnamed: 19'])
df2 = pd.read_csv('purged_1.csv', sep=',', header=6, usecols=['Location', 'TOTAL', 'Unnamed: 19'])
df3 = pd.read_csv('purged_2.csv', sep=',', header=6, usecols=['Location', 'TOTAL', 'Unnamed: 19'])
...
df9 = pd.read_csv('purged_8.csv', sep=',', header=6, usecols=['Location', 'TOTAL', 'Unnamed: 19'])

which look like this:

               TOTAL_x  Unnamed: 19_x   TOTAL_y  Unnamed: 19_y     TOTAL  Unnamed: 19  total_mean  error_mean
Location
LEU 455  -2.000507       0.043331 -1.822317       0.037883 -1.818721     0.030111   -1.880515    0.037108
PHE 456  -1.956130       0.041076 -2.305222       0.033210 -2.281509     0.042238   -2.180954    0.038842
ALA 475  -1.493856       0.085664 -2.950011       0.053675 -1.387676     0.068704   -1.943848    0.069348
GLY 476  -0.941795       0.079101 -2.383338       0.056897 -0.871813     0.062222   -1.398982    0.066073
PHE 486  -2.999369       0.081517 -3.688329       0.074005 -2.439233     0.093345   -3.042310    0.082956
ASN 487  -0.828214       0.080111  0.497831       0.029272 -0.969843     0.130934   -0.433409    0.080106
GLN 493  -1.323107       0.152173 -1.902454       0.121394 -2.320519     0.131299   -1.848694    0.134955
GLY 496  -0.603422       0.094210  0.069107       0.009226  0.120265     0.015929   -0.138017    0.039788
GLN 498  -2.692248       0.163207 -0.345707       0.051059 -1.610146     0.135108   -1.549367    0.116458
PRO 499  -0.256722       0.016657  0.042420       0.020137 -0.198196     0.011229   -0.137499    0.016008
THR 500  -0.650186       0.099639 -0.862829       0.113726 -0.996115     0.093840   -0.836377    0.102402
ASN 501  -3.513380       0.093578 -3.364489       0.090704 -4.055331     0.081724   -3.644400    0.088669
GLY 502  -1.011485       0.042847 -0.848697       0.054364 -0.712001     0.046970   -0.857395    0.048060
VAL 503  -0.680188       0.046426 -0.825084       0.082318 -0.635653     0.034014   -0.713642    0.054252
TYR 505  -1.868647       0.089418 -2.091676       0.084795 -1.777963     0.089681   -1.912762    0.087965

I have then merged them 3 by 3 (the argv is just a number I put to correct the labels,nothing big):

merge1 = pd.merge(df, df2, how='inner', on='Location')
merge2 = pd.merge(merge1, df3, how='inner', on='Location')
merge2 = merge2.loc[(df['TOTAL'] <= -0.25) & df['Location'].str.startswith("L")]
merge2.dropna(how='all', inplace=True)
merge2.set_index('Location', inplace=True)
merge2.index = merge2.index.str.split()
merge2.index = merge2.index.str[1] + ' ' + ((merge2.index.str[2].astype(int)) + int(sys.argv[10]) - 1).astype(str)
merge2['total_mean'] = merge2[['TOTAL_x', 'TOTAL_y', 'TOTAL']].mean(axis=1)
merge2['error_mean'] = merge2[['Unnamed: 19_x', 'Unnamed: 19_y', 'Unnamed: 19']].mean(axis=1)

I can correctly plot them one by one with:

concat = pd.concat([merge2,merge4,merge6])
pd.DataFrame.plot(concat)
plt.show()

But since it's a comparison, I would like to plot everything on the same figure(something like this):

So far I have tried to concatenate the different dataframes,and tried pyplot as well, and experimented with pandas.DataFrame.plot:

plt.bar(merge2.index, merge2['total_mean'])
plt.bar(merge4.index, merge4['total_mean'])
plt.bar(merge6.index, merge4['total_mean'])

test = pd.merge(merge2, merge4, how='inner', on='Location')
test.plot(y='total_mean', kind='bar', yerr='error_mean', legend=False)

But to no avail.

I would like to plot the three independent merged dataframes (merged2(which is (df+df2)+df3, merged4 (df4+df5)+df6, merged6 (df7+df8)+df9) showing only the 'total_mean' colum and using the 'error_mean' as error bar.

I can make it work with one, and independently I can plot them, but it's a total disaster if I try to put them all sharing the y axis.

Thank you for your help!

Ludovico

Body:
I solved simply by putting an array of colors... it's not specified anywhere but when you concatenate you can keep the original colors by adding an array like color=['r', 'g', 'b']).
Here is the modification I used, in case anyone would know:

    concat = pd.concat(merged_data_frames, axis=0, sort=True)
    concat = concat.sort_index(key=lambda x: x.str.split().str[1].str.zfill(5))
    concat.plot(kind='bar', y='total_mean', use_index=True, yerr='error_mean', edgecolor='black', color=['r', 'g', 'b'])


问:
Counting Prime Numbers in python
I am trying to make a program that will count prime numbers.
I tried and tried and it didn't work.
This is the code:

```<code>def count_primes(num):
primes = 0
if num % num==0 and num  % 1 == 0:
    primes = primes + 1
else:
    pass
return primes
</code>```

I put 100 as the value for num and the program just gives me one.

答:
There are two problems here:

Your code only checks the number inputted, not all the numbers up to it

You check whether the number is divisible by itself and 1, but you don't check whether or not it is divisible by anything else - so any integer will be accepted

The best way to do this is probably to create a list of primes and use a for loop to iterate over all the numbers up to the input and check if they are primes. If a number is prime, add it to the list. At the end, return the length of the list.

The reason I would create a list of primes, not just a number, is because this makes testing whether or not a number is prime more efficient - to check if a number is prime it only has to be verified that it is not divisible by any of the primes before it. Here is the completed code:

def count_primes(num):
    primes = []
    for i in range(2, num + 1):
        for j in primes:
            if i % j == 0:
                break
        else:
            primes.append(i)
    return len(primes)
```
<p>Here the <code>for i in range...</code> is iterating over all the numbers between 2 and <code>num</code> and checking if they are prime, adding them to the list if they are. The <code>for j in primes...</code> checks if the number is prime by iterating over the current list of primes and checking if the number is divisible by any of them. This is more efficient than checking all the numbers up to <code>num</code> because less checks must be made.</p>
<p>If you wanted to be able to specify which number to start counting at, then you would add an aditional <code>count</code> variable to store the number of primes currently counted, and only add to the <code>count</code> variable if the number was above the starting point:</p>
<pre class="lang-py prettyprint-override"><code>def count_primes(start, end):
    count = 0
    primes = []
    for i in range(2, end + 1):
        for j in primes:
            if i % j == 0:
                break
        else:
            primes.append(i)
            if i >= start:
                count += 1
    return count
</code>```

Title: Counting Prime Numbers in python

Body:
I am trying to make a program that will count prime numbers.
I tried and tried and it didn't work.
This is the code:

def count_primes(num):
primes = 0
if num % num==0 and num  % 1 == 0:
    primes = primes + 1
else:
    pass
return primes

I put 100 as the value for num and the program just gives me one.

Body:
There are two problems here:

Your code only checks the number inputted, not all the numbers up to it

You check whether the number is divisible by itself and 1, but you don't check whether or not it is divisible by anything else - so any integer will be accepted

The best way to do this is probably to create a list of primes and use a for loop to iterate over all the numbers up to the input and check if they are primes. If a number is prime, add it to the list. At the end, return the length of the list.

The reason I would create a list of primes, not just a number, is because this makes testing whether or not a number is prime more efficient - to check if a number is prime it only has to be verified that it is not divisible by any of the primes before it. Here is the completed code:

def count_primes(num):
    primes = []
    for i in range(2, num + 1):
        for j in primes:
            if i % j == 0:
                break
        else:
            primes.append(i)
    return len(primes)

Here the for i in range... is iterating over all the numbers between 2 and num and checking if they are prime, adding them to the list if they are. The for j in primes... checks if the number is prime by iterating over the current list of primes and checking if the number is divisible by any of them. This is more efficient than checking all the numbers up to num because less checks must be made.

If you wanted to be able to specify which number to start counting at, then you would add an aditional count variable to store the number of primes currently counted, and only add to the count variable if the number was above the starting point:

def count_primes(start, end):
    count = 0
    primes = []
    for i in range(2, end + 1):
        for j in primes:
            if i % j == 0:
                break
        else:
            primes.append(i)
            if i >= start:
                count += 1
    return count


问:
Getting started with Create React App - "Cannot find module"
I'm using the "Getting Started" guide because I've been experiencing endless errors trying to create a react app so far when following tutorials.

And straight away I'm running into a problem. When I run npx create-react-app my-app I get the following:

```<code>Cannot find module 'C:\Users\Aristophanes\node_modules\create-react-app\index.js'
</code>```

Can anyone advise me what I'm doing wrong? Thanks.

答:
I had same issue a few times. Every time I was searching thru net for a solution, and for every time i just typed in terminal

npm i node

and its just started working

Body:
I'm using the "Getting Started" guide because I've been experiencing endless errors trying to create a react app so far when following tutorials.

And straight away I'm running into a problem. When I run npx create-react-app my-app I get the following:

Cannot find module 'C:\Users\Aristophanes\node_modules\create-react-app\index.js'

Can anyone advise me what I'm doing wrong? Thanks.


问:
Is there a way to change the device output of officedown::rdocx_document() from .jpg to .emf?
When using officedown::rdocx_document in R Mardown, the Office Word output will include the plots as a .jpg image although my desire is to automatically include the plots of my R markdown in format .emf (Enhanched Metafile).

I know that with the function ggsave() you can adapt the device to .emf like in this example:

```<code>plot(mtcars$mpg)

ggsave("plot.emf", width = 10, height = 6, scale = 1, device = {function(filename, ...) devEMF::emf(file = filename, ...)})
</code>```

Is there a way to do a workaround ggsave to change the device output of the plots in a RMarkdown (.Rmd) using officedown::rdocx_document as the output?

答:
Here the answer to my own question after some research.
If you don't want to ggsave() and then knitr::include_graphics() every plot of your .Rmd in .emf (Enchanced Metafile) because there are a lot of them, then consider changing the graphic device of your .Rmd so that when it is exported to Word through the amazing package officedown (shout out to David Gohel) all the plots would be inserted in .emf extension that is more suitable for print publications than .png o .svg. Here the code workaround (is a simple change in your setup chunk but really makes the difference):

```<code>```{r setup, include=FALSE}

pacman::p_load("devEMF")

knitr::opts_chunk$set(echo = FALSE,
                      warning = FALSE,
                      message = FALSE,
                      dev = "emf",
                      fig.ext = "emf")

```
</code>```

I hope it helps the community that uses officedown for Office Word Reports.

Body:
When using officedown::rdocx_document in R Mardown, the Office Word output will include the plots as a .jpg image although my desire is to automatically include the plots of my R markdown in format .emf (Enhanched Metafile).

I know that with the function ggsave() you can adapt the device to .emf like in this example:

plot(mtcars$mpg)

ggsave("plot.emf", width = 10, height = 6, scale = 1, device = {function(filename, ...) devEMF::emf(file = filename, ...)})

Is there a way to do a workaround ggsave to change the device output of the plots in a RMarkdown (.Rmd) using officedown::rdocx_document as the output?

Body:
Here the answer to my own question after some research.
If you don't want to ggsave() and then knitr::include_graphics() every plot of your .Rmd in .emf (Enchanced Metafile) because there are a lot of them, then consider changing the graphic device of your .Rmd so that when it is exported to Word through the amazing package officedown (shout out to David Gohel) all the plots would be inserted in .emf extension that is more suitable for print publications than .png o .svg. Here the code workaround (is a simple change in your setup chunk but really makes the difference):

```{r setup, include=FALSE}

pacman::p_load("devEMF")

knitr::opts_chunk$set(echo = FALSE,
                      warning = FALSE,
                      message = FALSE,
                      dev = "emf",
                      fig.ext = "emf")

```

I hope it helps the community that uses officedown for Office Word Reports.


问:
Python package raises ModuleNotFoundError on calling an entry-point except if installed in editable mode
I have a Python package that at first appears to install just fine, but when calling on one of the entry points raises a ModuleNotFoundException. The module is otherwise found just fine with both import package from the interactive interpreter as well as with python -m package.etc. But if I try to call on the entry-point directly (flike python -m package.etc.main) it will raise an AttributeError saying that the module has no attribute __path__.

I can see the package if I do pip list.

The project is currently set up with the "template" pyproject.toml and only setup.cfg, but the behaviour is essentially the same (the traceback looks slightly different but the error is the same) when using setup.py over pyproject.toml, both with pip but also if I invoke setup.py directly. The structure of the project is:

```<code>package
├── __init__.py
├── cli
│   ├── __init__.py
│   ├── entry.py
├── file.py
</code>```

I get the same behaviour if doing this in a virtual environment as when I do it with a userspace (--user) install.

Modifying the environment variable ${PYTHONPATH} fixes the issue, and installing the package in editable mode works just fine.

答:
Turns out that the issue was that I had something like:

```<code>[options]
packages = find:

[options.packages.find]
include =
  README.md
</code>```

in my setup.cfg, and it appears as if the declaration of include was exclusive which led to the package not being included in the installation, which still worked when installed in editable mode (presumably because editable mode only sets up some sort of links or appends the source code directories to some path).

Body:
I have a Python package that at first appears to install just fine, but when calling on one of the entry points raises a ModuleNotFoundException. The module is otherwise found just fine with both import package from the interactive interpreter as well as with python -m package.etc. But if I try to call on the entry-point directly (flike python -m package.etc.main) it will raise an AttributeError saying that the module has no attribute __path__.

I can see the package if I do pip list.

The project is currently set up with the "template" pyproject.toml and only setup.cfg, but the behaviour is essentially the same (the traceback looks slightly different but the error is the same) when using setup.py over pyproject.toml, both with pip but also if I invoke setup.py directly. The structure of the project is:

package
├── __init__.py
├── cli
│   ├── __init__.py
│   ├── entry.py
├── file.py

I get the same behaviour if doing this in a virtual environment as when I do it with a userspace (--user) install.

Modifying the environment variable ${PYTHONPATH} fixes the issue, and installing the package in editable mode works just fine.

Body:
Turns out that the issue was that I had something like:

[options]
packages = find:

[options.packages.find]
include =
  README.md

in my setup.cfg, and it appears as if the declaration of include was exclusive which led to the package not being included in the installation, which still worked when installed in editable mode (presumably because editable mode only sets up some sort of links or appends the source code directories to some path).


答:
```<code>def is_prime(n):
    if n < 1:
        return False
    for i in range(2, 1+n//2):
        if (n % i) == 0:
            return False

    return True

def count_primes(start, end):
    count = 0
    for i in range(start, end+1):
        # if is_prime(i): print(i)
        count = count+1 if is_prime(i) else count
    return count

count_primes(1,100)
</code>```

Title: Counting Prime Numbers in python


问:
json to sqflite create table query Flutter
Is there an automatic way to generate sqflite create table queries according to json data?
I m building Erp apps.So, i have to deal with 40-50 tables each time and
i think there should be an automatic way to do it like json to dart.</p>
```<code>    {
        "sto_code": "120.001",
        "sto_name": "NORMAL STOK",
        "sto_amount": 1
    }

</code>```

答:
No package that I know of does that yet. But you could use this code snippet to generate a CREATE TABLE statement with an example json file.</p>
```<code>  String getType(Type type){
    if(type is int){
      return 'INTEGER';
    }else if(type is String){
      return 'TEXT';
    }else if(type is double){
      return 'REAL';
    }else{
      return 'TEXT';
    }
  }

  String createColumns(Map<dynamic, dynamic> map){
    String columns = '';
    map.forEach((key, value){
      columns += '$key ${getType(value.runtimeType)}, ';
    });

    return columns.endsWith(', ') ? columns.substring(0,columns.length - 2) : columns;
  }

  String createTable(String tableName, Map<dynamic, dynamic> map){
    String columns = createColumns(map);
    String table = 'CREATE TABLE $tableName ($columns)';

    return table;
  }

</code>```

Body:
Is there an automatic way to generate sqflite create table queries according to json data?
I m building Erp apps.So, i have to deal with 40-50 tables each time and
i think there should be an automatic way to do it like json to dart.

    {
        "sto_code": "120.001",
        "sto_name": "NORMAL STOK",
        "sto_amount": 1
    }

Body:
No package that I know of does that yet. But you could use this code snippet to generate a CREATE TABLE statement with an example json file.

  String getType(Type type){
    if(type is int){
      return 'INTEGER';
    }else if(type is String){
      return 'TEXT';
    }else if(type is double){
      return 'REAL';
    }else{
      return 'TEXT';
    }
  }

  String createColumns(Map<dynamic, dynamic> map){
    String columns = '';
    map.forEach((key, value){
      columns += '$key ${getType(value.runtimeType)}, ';
    });

    return columns.endsWith(', ') ? columns.substring(0,columns.length - 2) : columns;
  }

  String createTable(String tableName, Map<dynamic, dynamic> map){
    String columns = createColumns(map);
    String table = 'CREATE TABLE $tableName ($columns)';

    return table;
  }


问:
How to import/include a CSS file using PHP code and not HTML code?
I have googled a lot but it seems that I am doing something wrong.

I want to do this:

```<code><?php
include 'header.php';
include'CSS/main.css';
...
?>
</code>```

However, my page prints the CSS code.

Note: I want to use PHP to include the CSS file, and not use

I also do you want to rename my CSS file to a PHP file as some website mentioned.

Any clues?

Many thanks.

答:
The file name must be something other than a .CSS index. Write the following:

<link rel="stylesheet" href="style.css" type="text/css" />
```

Body:
I have googled a lot but it seems that I am doing something wrong.

I want to do this:

<?php
include 'header.php';
include'CSS/main.css';
...
?>

However, my page prints the CSS code.

Note: I want to use PHP to include the CSS file, and not use

I also do you want to rename my CSS file to a PHP file as some website mentioned.

Any clues?

Many thanks.


问:
Delete json block with jq command
I have json file with multiple domains which is formated as is showed below. How can I delete whole blocks with domains? For example if I will want to delete whole block in json for domain domain.tld?

I tryed this, but output is error:

```<code>jq '."http-01"."domain"[]."main"="domain.tld"' acme.json
jq: error (at acme.json:11483): Cannot iterate over null (null)
</code>```

formating example file:

```<code>    {
  "http-01": {
    "Account": {
      "Email": "mail@placeholder.tld",
      "Registration": {
        "body": {
          "status": "valid",
          "contact": [
            "mailto:mail@placeholder.tld"
          ]
        },
        "uri": "https://acme-v02.api.letsencrypt.org/acme/acct/110801506"
      },
      "PrivateKey": "main_priv_key_string",
      "KeyType": "4096"
    },
    "Certificates": [
      {
        "domain": {
          "main": "www.some_domain.tld"
        },
        "certificate": "cert_string",
        "key": "key_string",
        "Store": "default"
      },
      {
        "domain": {
          "main": "some_domain.tld"
        },
        "certificate": "cert_string",
        "key": "key_string",
        "Store": "default"
      },
      {
        "domain": {
          "main": "www.some_domain2.tld"
        },
        "certificate": "cert_string",
        "key": "key_string",
        "Store": "default"
      },
      {
        "domain": {
          "main": "some_domain2.tld"
        },
        "certificate": "cert_string",
        "key": "key_string",
        "Store": "default"
      }
    ]
  }
}
</code>```

答:
To delete domain block "www.some_domain.tld" :</p>
```<code>jq '."http-01".Certificates |= map(select(.domain.main != "www.some_domain.tld"))' input.json
</code>```

Title: Delete json block with jq command

Body:
I have json file with multiple domains which is formated as is showed below. How can I delete whole blocks with domains? For example if I will want to delete whole block in json for domain domain.tld?

I tryed this, but output is error:

jq '."http-01"."domain"[]."main"="domain.tld"' acme.json
jq: error (at acme.json:11483): Cannot iterate over null (null)

formating example file:

    {
  "http-01": {
    "Account": {
      "Email": "mail@placeholder.tld",
      "Registration": {
        "body": {
          "status": "valid",
          "contact": [
            "mailto:mail@placeholder.tld"
          ]
        },
        "uri": "https://acme-v02.api.letsencrypt.org/acme/acct/110801506"
      },
      "PrivateKey": "main_priv_key_string",
      "KeyType": "4096"
    },
    "Certificates": [
      {
        "domain": {
          "main": "www.some_domain.tld"
        },
        "certificate": "cert_string",
        "key": "key_string",
        "Store": "default"
      },
      {
        "domain": {
          "main": "some_domain.tld"
        },
        "certificate": "cert_string",
        "key": "key_string",
        "Store": "default"
      },
      {
        "domain": {
          "main": "www.some_domain2.tld"
        },
        "certificate": "cert_string",
        "key": "key_string",
        "Store": "default"
      },
      {
        "domain": {
          "main": "some_domain2.tld"
        },
        "certificate": "cert_string",
        "key": "key_string",
        "Store": "default"
      }
    ]
  }
}

Body:
To delete domain block "www.some_domain.tld" :

jq '."http-01".Certificates |= map(select(.domain.main != "www.some_domain.tld"))' input.json


问:
A large database or several smaller?
After reading a lot about it and similar questions, I am still not clear about the following case.

I have an schema like this in one mysql database, where I store the probabilities of matches of more than 10 sports depending on the type of result
(is intended for an application that shows the odds for each sport on different pages but I will never mix sports on the same page):

Design 1: a single database

```<code>SPORT
id
name

TEAM
id
sportId
name
birth

MATCHES
id
sportId
teamId_1
teamId_2
result
date

PROBABILITIES
id
matchId
type
percentage
</code>```

(table Probabilities is very long, almost a billion rows, and will grow over time)

All necessary fields are correctly indexed. Then to see all the probabilities of the matches that do not have result with the football sport with id = 1, I would make the following query:

```<code>SELECT s.name, t1.name as nameTeam1, t2.name as nameTeam2, t1.birth as birthTeam1, t2.birth as birthTeam2, m.date, p.type, p.percentage
FROM matches m
INNER JOIN team t1 ON t1.id = m.teamId_1
INNER JOIN team t2 ON t2.id = m.teamId_2
INNER JOIN sport s ON s.id = m.sportId
INNER JOIN probabilities p ON p.matchId = m.id
WHERE result IS NULL
AND s.id = 1
</code>```

This database design is great because it allows me to work comfortably with ORM like Prisma. But for my team the most important thing is speed and performance.

Knowing this, is it a good idea to do it this way or would it be better to separate the tables into several databases?

Design 2: one database per sport

Database Football

```<code>TEAM
id
sportId
name
birth

MATCHES
id
teamId_1
teamId_2
date

PROBABILITIES
id
matchId
type
percentage
</code>```

Database Basketball

```<code>TEAM
id
sportId
name
birth

MATCHES
id
teamId_1
teamId_2
date

PROBABILITIES
id
matchId
type
percentage
</code>```

The probabilities table is much smaller, in some sports only thousands of rows.

So if, for example, I only need to take the football probabilities I make a query like this:

```<code>SELECT t1.name as nameTeam1, t2.name as nameTeam2, t1.birth as birthTeam1, t2.birth as birthTeam2, m.date, p.type, p.percentage
FROM football.matches m
INNER JOIN football.team t1 ON t1.id = m.teamId_1
INNER JOIN football.team t2 ON t2.id = m.teamId_2
INNER JOIN football.probabilities p ON p.matchId = m.id
WHERE result IS NULL
</code>```

Or is there some other way to improve the speed and performance of the database such as partitioning the probabilities table when we only query the most recent rows in the database?

答:
If you make one database per sport you are locking the application into that decision. If you put them all together in one you can separate them later if necessary. I doubt it will be.

But for my team the most important thing is speed and performance.

At this early stage the most important thing is getting something working so you can use it and discover what it actually needs to do. Then adapt the schema as you learn..

Your major performance problems won't come from whether you have one database or many, but more pedestrian issues of indexing, bad queries, and schema design.

To that end...

Keep the schema simple

Keep the schema flexible

Consider a data warehouse

To the first, that means one database. Don't add the complication of maintaining multiple copies of the schema if you don't need to.

To the second, use schema migrations and keep the details of the schema out of the application code. An ORM is a good start, but also employ the Respository Pattern, Decorator Pattern, Service Pattern, and others to keep details of your tables from leaking out into your code. Then when it inevitably comes time to change your schema you can without having to rewrite all the code which uses it.

Your concerns can be solved with indexing and partitioning, probably partition probabilities, but without knowing your queries I can't say on what. For example, you might want to partition by the age of the match since newer matches are more interesting than old ones. It's hard to say. Fortunately partitioning can be added later.

The rest of the tables should be relatively small, partitioning by team isn't likely to help. Poor partitioning choices can even slow things down.

Finally, what might be best for performance is to separate the statsistical tables into a data warehouse optimized for big data and statistics. Do the stats there and have the application query them. This separates the runtime schema which must have low latency and benefits from being kept small, from the statistical database which is mostly reporting on pre-calculated statisitical queries.

Some notes on your schema.

Remove "sport" from the matches. It's redundant. Get it from the teams. Add a constraint to ensure both teams are playing the same sport.

Don't name a column date. First, it's a keyword. Second, date of what? What if there's another date associated with the match? Third, what about the time of the match? Make it specific: scheduled_at. Use a timestamp type.

Result should be it's own table. You're going to want to store a lot of information about the result of the match.

Title: A large database or several smaller?

Body:
After reading a lot about it and similar questions, I am still not clear about the following case.

I have an schema like this in one mysql database, where I store the probabilities of matches of more than 10 sports depending on the type of result
(is intended for an application that shows the odds for each sport on different pages but I will never mix sports on the same page):

Design 1: a single database

SPORT
id
name

TEAM
id
sportId
name
birth

MATCHES
id
sportId
teamId_1
teamId_2
result
date

PROBABILITIES
id
matchId
type
percentage

(table Probabilities is very long, almost a billion rows, and will grow over time)

All necessary fields are correctly indexed. Then to see all the probabilities of the matches that do not have result with the football sport with id = 1, I would make the following query:

SELECT s.name, t1.name as nameTeam1, t2.name as nameTeam2, t1.birth as birthTeam1, t2.birth as birthTeam2, m.date, p.type, p.percentage
FROM matches m
INNER JOIN team t1 ON t1.id = m.teamId_1
INNER JOIN team t2 ON t2.id = m.teamId_2
INNER JOIN sport s ON s.id = m.sportId
INNER JOIN probabilities p ON p.matchId = m.id
WHERE result IS NULL
AND s.id = 1

This database design is great because it allows me to work comfortably with ORM like Prisma. But for my team the most important thing is speed and performance.

Knowing this, is it a good idea to do it this way or would it be better to separate the tables into several databases?

Design 2: one database per sport

Database Football

TEAM
id
sportId
name
birth

MATCHES
id
teamId_1
teamId_2
date

PROBABILITIES
id
matchId
type
percentage

Database Basketball

TEAM
id
sportId
name
birth

MATCHES
id
teamId_1
teamId_2
date

PROBABILITIES
id
matchId
type
percentage

The probabilities table is much smaller, in some sports only thousands of rows.

So if, for example, I only need to take the football probabilities I make a query like this:

SELECT t1.name as nameTeam1, t2.name as nameTeam2, t1.birth as birthTeam1, t2.birth as birthTeam2, m.date, p.type, p.percentage
FROM football.matches m
INNER JOIN football.team t1 ON t1.id = m.teamId_1
INNER JOIN football.team t2 ON t2.id = m.teamId_2
INNER JOIN football.probabilities p ON p.matchId = m.id
WHERE result IS NULL

Or is there some other way to improve the speed and performance of the database such as partitioning the probabilities table when we only query the most recent rows in the database?


问:
Rails 7.0 + esbuild: running app gives error: Command "build" not found
Newly generated Rails 7.0 with esbuild option errors out on startup.

```<code>rails new [project name] --javascript=esbuild --css=tailwind
</code>```

On creating a new rails 7 project, I try to start the application using bin/dev which uses now uses foreman. However, it errors out with 'error command "build" not found.'

```<code>bin/dev
                                                                                !10520
16:07:31 web.1  | started with pid 53018
16:07:31 js.1   | started with pid 53019
16:07:31 css.1  | started with pid 53020
16:07:32 js.1   | yarn run v1.22.17
16:07:32 css.1  | yarn run v1.22.17                    **************
16:07:32 js.1   | error Command "build" not found. <== *****THIS*****
16:07:32 js.1   | info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
16:07:32 css.1  | error Command "build:css" not found.
16:07:32 css.1  | info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
16:07:33 css.1  | exited with code 1
16:07:33 system | sending SIGTERM to all processes
16:07:33 js.1   | exited with code 1
16:07:33 web.1  | terminated by SIGTERM
</code>```

答:
I would like to add to @notapatch answer to run the following commands after step 2:

```<code>yarn build
</code>```

and then

```<code>yarn build:css
</code>```

You're welcome.

Body:
Newly generated Rails 7.0 with esbuild option errors out on startup.

rails new [project name] --javascript=esbuild --css=tailwind

On creating a new rails 7 project, I try to start the application using bin/dev which uses now uses foreman. However, it errors out with 'error command "build" not found.'

bin/dev
                                                                                !10520
16:07:31 web.1  | started with pid 53018
16:07:31 js.1   | started with pid 53019
16:07:31 css.1  | started with pid 53020
16:07:32 js.1   | yarn run v1.22.17
16:07:32 css.1  | yarn run v1.22.17                    **************
16:07:32 js.1   | error Command "build" not found. <== *****THIS*****
16:07:32 js.1   | info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
16:07:32 css.1  | error Command "build:css" not found.
16:07:32 css.1  | info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
16:07:33 css.1  | exited with code 1
16:07:33 system | sending SIGTERM to all processes
16:07:33 js.1   | exited with code 1
16:07:33 web.1  | terminated by SIGTERM

Body:
I would like to add to @notapatch answer to run the following commands after step 2:

yarn build

and then

yarn build:css

You're welcome.


问:
Laravel DataTable - $dataTable is undefined
I created a Model, Controller, Factory and dataTable files, but laravel keeps showing me the error $dataTable is undefined

How come? Is it a routing issue or I'm not linking the controller to the blade correctly?

My controller:

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\DataTables\DataEntry\ReportsDataTable;

class ReportsController extends Controller
{
    public function index(ReportsDataTable $dataTable)
    {
        return $dataTable->render("pages.dataEntry.reports.index");
    }
}
</code>```

The Route:

```<code>// Data Entry pages
    Route::prefix('dataEntry')->name('dataEntry.')->group(function () {
        Route::resource('reports', ReportsController::class)->only(['index']);
    });
</code>```

index.blade:

```<code><x-base-layout>

    <!--begin::Card-->
    <div class="card">
        <!--begin::Card body-->
        <div class="card-body pt-6">
            <!--begin::Table-->
             {{ $dataTable->table() }}
            <!--end::Table-->

            {{-- Inject Scripts --}}
             {{ $dataTable->scripts() }}
        </div>
        <!--end::Card body-->
    </div>
    <!--end::Card-->

</x-base-layout>
</code>```

答:
```<code>public function index()
{
    return ReportsDataTable::all()->render("pages.dataEntry.reports.index");
}
</code>```

Body:
I created a Model, Controller, Factory and dataTable files, but laravel keeps showing me the error $dataTable is undefined

How come? Is it a routing issue or I'm not linking the controller to the blade correctly?

My controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\DataTables\DataEntry\ReportsDataTable;

class ReportsController extends Controller
{
    public function index(ReportsDataTable $dataTable)
    {
        return $dataTable->render("pages.dataEntry.reports.index");
    }
}

The Route:

// Data Entry pages
    Route::prefix('dataEntry')->name('dataEntry.')->group(function () {
        Route::resource('reports', ReportsController::class)->only(['index']);
    });

index.blade:

<x-base-layout>

             {{ $dataTable->table() }}

            {{-- Inject Scripts --}}
             {{ $dataTable->scripts() }}

</x-base-layout>