问:
how to replace strings with path objects in python?
I have the following dictionary:

config = {
'base_dir': Path(__file__).resolve(strict=True).parent.absolute(),
'app_dir': '<base_dir>/app'
}
```

<p>I want to replace <code><base_dir></code> with the value of <code><base_dir></code>
so I did this:</p>

<pre class="lang-py prettyprint-override"><code>for key, value in config.items():
    if type(value) == str:
        vars_to_replace = re.findall(r'\<.+\>',value)
        for var in vars_to_replace:
            config[key] = value.replace(var,config[var[1:-1]])
</code>```

Currently getting the error: TypeError: replace() argument 2 must be str, not WindowsPath

If I wrap my config[var[1:-1]] with str(). It gets rid of the error but I lose the WindowsPath and now app_dir becomes a string. I want to reserve the object as WindowsPath.

答:
I'd say extract both base_dir and app and then construct a path with them:

```<code>for key, value in config.items():
    if isinstance(value, str):
        # parent_str will be "base_dir" and name_str will be "app"
        parent_str, name_str = re.fullmatch(r"\<(.+)?>/(\w+)", value).groups()
        parent_path = config[parent_str]
        config[key] = parent_path / Path(name_str)
</code>```

I did not use for loop, assumed only one such match is possible in a value. If that's not the case, you could wrap a for loop with finditer.

Body:
I have the following dictionary:

config = {
'base_dir': Path(__file__).resolve(strict=True).parent.absolute(),
'app_dir': '<base_dir>/app'
}

I want to replace <base_dir> with the value of <base_dir>
so I did this:

for key, value in config.items():
    if type(value) == str:
        vars_to_replace = re.findall(r'\<.+\>',value)
        for var in vars_to_replace:
            config[key] = value.replace(var,config[var[1:-1]])

Currently getting the error: TypeError: replace() argument 2 must be str, not WindowsPath

If I wrap my config[var[1:-1]] with str(). It gets rid of the error but I lose the WindowsPath and now app_dir becomes a string. I want to reserve the object as WindowsPath.

Body:
I'd say extract both base_dir and app and then construct a path with them:

for key, value in config.items():
    if isinstance(value, str):
        # parent_str will be "base_dir" and name_str will be "app"
        parent_str, name_str = re.fullmatch(r"\<(.+)?>/(\w+)", value).groups()
        parent_path = config[parent_str]
        config[key] = parent_path / Path(name_str)

I did not use for loop, assumed only one such match is possible in a value. If that's not the case, you could wrap a for loop with finditer.


来源: stackexchange

问:
Works on WPF. But on VSTO project, throws error: Could not load file or assembly 'SQLitePCLRaw.core, Version=2.0.2.669, Culture=neutral
I've created a .NET Standard 2.0 class library project that works fine when referenced by a WPF App (.NET Framework 4.8) project. But when the same library is referenced by a MS Office VSTO Project (also using .NET Framework 4.8), I get the following error on the code line shown below:

Remarks:

I'm using VS2019, Windows20 Pro, Microsoft.Data.Sqlite and following example from same link.

Exact same code works fine on WPF app.

I also tried installing SQLitePCLRaw.core package (as mentioned in the error) but still the same error. Although, I think I should not have to install this package since I did not have to do it with WPF app.

Same copies of MySQLiteDb.db file reside in the bin\Debug folder of VSTO as well as WPF folder. So, that should probably not be an issue

Error:

```<code>FileLoadException: Could not load file or assembly 'SQLitePCLRaw.core, Version=2.0.2.669, Culture=neutral, PublicKeyToken=1488e028ca7ab535' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
</code>```

Code [error occurs at line using (SqliteConnection db = ....):

```<code>string SQLiteDbpath = System.IO.Path.Combine(GetAppInstalPath, "MySQLiteDb.db");

using (SqliteConnection db = new SqliteConnection($"Filename={SQLiteDbpath}"))
{
    db.Open();

    using (SqliteCommand insertCommand = new SqliteCommand())
    {
        ......
        insertCommand.ExecuteNonQuery();
    }
}
</code>```

答:
FileLoadException: Could not load file or assembly 'SQLitePCLRaw.core, Version=2.0.2.669, Culture=neutral, PublicKeyToken=1488e028ca7ab535' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

You need to include the missed file (SQLitePCLRaw.core) to the folder with the add-in files.

ContentLicense: CC BY-SA 4.0

Body:
I've created a .NET Standard 2.0 class library project that works fine when referenced by a WPF App (.NET Framework 4.8) project. But when the same library is referenced by a MS Office VSTO Project (also using .NET Framework 4.8), I get the following error on the code line shown below:

Remarks:

I'm using VS2019, Windows20 Pro, Microsoft.Data.Sqlite and following example from same link.

Exact same code works fine on WPF app.

I also tried installing SQLitePCLRaw.core package (as mentioned in the error) but still the same error. Although, I think I should not have to install this package since I did not have to do it with WPF app.

Same copies of MySQLiteDb.db file reside in the bin\Debug folder of VSTO as well as WPF folder. So, that should probably not be an issue

Error:

FileLoadException: Could not load file or assembly 'SQLitePCLRaw.core, Version=2.0.2.669, Culture=neutral, PublicKeyToken=1488e028ca7ab535' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Code [error occurs at line using (SqliteConnection db = ....):

string SQLiteDbpath = System.IO.Path.Combine(GetAppInstalPath, "MySQLiteDb.db");

using (SqliteConnection db = new SqliteConnection($"Filename={SQLiteDbpath}"))
{
    db.Open();

    using (SqliteCommand insertCommand = new SqliteCommand())
    {
        ......
        insertCommand.ExecuteNonQuery();
    }
}


问:
How to count unique values over multiple columns using R?
Let's say I have the following df:

```<code>1               2                    3
home, work      work, home           home, work
leisure, work   work, home, leisure  work, home
home, leisure   work, home           home, work
</code>```

I want to count all unique variables over the entire data.frame (not by columns or row, I'm interested in the cell values)

So the output should look like this:

```<code>                    freq
home, work          3
leisure, work       1
home, leisure       1
work, home          3
work, home, leisure 1
</code>```

I have not found a way to do that. The count() function seems to work only with single columns.

Thank you very much for the help:)

答:
With tidyverse, we can use gather

```<code>library(dplyr)
library(tidyr)
df %>%
   gather %>%
   count(value)
#              value n
#1      home,leisure 1
#2         home,work 3
#3      leisure,work 1
#4         work,home 3
#5 work,home,leisure 1
</code>```

data

```<code>df <- structure(list(X1 = c("home,work", "leisure,work", "home,leisure"
), X2 = c("work,home", "work,home,leisure", "work,home"), X3 = c("home,work",
"work,home", "home,work")), class = "data.frame", row.names = c(NA, -3L))
</code>```

Body:
Let's say I have the following df:

1               2                    3
home, work      work, home           home, work
leisure, work   work, home, leisure  work, home
home, leisure   work, home           home, work

I want to count all unique variables over the entire data.frame (not by columns or row, I'm interested in the cell values)

So the output should look like this:

                    freq
home, work          3
leisure, work       1
home, leisure       1
work, home          3
work, home, leisure 1

I have not found a way to do that. The count() function seems to work only with single columns.

Thank you very much for the help:)

Body:
With tidyverse, we can use gather

library(dplyr)
library(tidyr)
df %>%
   gather %>%
   count(value)
#              value n
#1      home,leisure 1
#2         home,work 3
#3      leisure,work 1
#4         work,home 3
#5 work,home,leisure 1

data

df <- structure(list(X1 = c("home,work", "leisure,work", "home,leisure"
), X2 = c("work,home", "work,home,leisure", "work,home"), X3 = c("home,work",
"work,home", "home,work")), class = "data.frame", row.names = c(NA, -3L))


问:
Deserialize JSON array which has mixed values System.Text.JSON
I'm trying to create a page rendered in .net core 3.1 which renders pages based on JSON.

How can I deserialzie the JSON at the end of this post?

I've tried to deserialize this however it doesn't work because I loose the data for each Component,
since the Page class has a List<Component> - but I need this to be a list of varying different components.

Page Model :

```<code>public class Page
    {
        public int id { get; set; }
        public string pagename { get; set; }
        public string metatitle { get; set; }
        public string metadescription { get; set; }
        public string created_at { get; set; }
        public string updated_at { get; set; }
        public List<Component> components { get; set; }
    }

    public class Pages
    {
        public List<Page> pages { get; set; }
    }
</code>```

Component Model:

```<code>public class Component
    {
        public string component { get; set; }
        public int id { get; set; }
    }
</code>```

A Component :

```<code>public class Title : Component
    {
        public string component { get; set; }
        public int id { get; set; {
        public string titletext { get; set; }
    }
</code>```

This is the JSON:

```<code>{
      "id":1,
      "pagename":"home",
      "metatitle":"no title",
      "metadescription":"no meta",
      "created_at":"2020-05-31T16:35:52.084Z",
      "updated_at":"2020-05-31T16:35:52.084Z",
      "components":[
         {
            "component":"components.titletext",
            "id":1,
            "titletext":"hello"
         },
         {
            "component":"components.section",
            "id":2,
            "titletext":"hello",
            "descriptiontext":"its a beatiful day in lost santos",
            "buttonlink":"/go"
         },
         {
            "component":"components.cta",
            "id":3,
            "sectiontitle":"hello",
            "buttonlink":"/go",
            "buttontext":"click me"
         }
      ]
   }
</code>```

答:
If you don't want to add all properties to the Component class like that:

```<code>public class Component
{
    public string component { get; set; }
    public int id { get; set; }
    public string titletext { get; set; }
    public string sectiontitle { get; set; }
    public string buttonlink { get; set; }
    public string descriptiontext { get; set; }
}
</code>```

You will need to write custom JsonConverter for example (not very performant implementation but works with your json and you will not need to parse every field by hand):

```<code>public class ComponentConverter : JsonConverter<Component>
{
    public override Component Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        using (var doc = JsonDocument.ParseValue(ref reader))
        {
            var type = doc.RootElement.GetProperty(@"component").GetString();
            switch(type)
            {
                case "components.titletext":
                    return JsonSerializer.Deserialize<Title>(doc.RootElement.GetRawText());
                // other types handling
                default: return JsonSerializer.Deserialize<Component>(doc.RootElement.GetRawText());
            }
        }
    }

    public override void Write(Utf8JsonWriter writer, Component value, JsonSerializerOptions options)
    {
        throw new NotImplementedException();
    }
}

public class Component
{
    public string component { get; set; }
    public int id { get; set; }
}

public class Title : Component
{
    public string titletext { get; set; }
}
</code>```

And usage example:

```<code>var json = @"[
     {
        ""component"":""components.titletext"",
        ""id"":1,
        ""titletext"":""hello""
     },
     {
""component"":""components.section"",
        ""id"":2,
        ""titletext"":""hello"",
        ""descriptiontext"":""its a beatiful day in lost santos"",
        ""buttonlink"":""/go""
     },
     {
""component"":""components.cta"",
        ""id"":3,
        ""sectiontitle"":""hello"",
        ""buttonlink"":""/go"",
        ""buttontext"":""click me""
     }
  ]";
var deserializeOptions = new JsonSerializerOptions();
deserializeOptions.Converters.Add(new ComponentConverter());
JsonSerializer.Deserialize<List<Component>>(json, deserializeOptions).Dump();
</code>```

Also do not use this converter as parameter for JsonConverterAttribute cause it will end in stackoverflow.

Body:
I'm trying to create a page rendered in .net core 3.1 which renders pages based on JSON.

How can I deserialzie the JSON at the end of this post?

I've tried to deserialize this however it doesn't work because I loose the data for each Component,
since the Page class has a List<Component> - but I need this to be a list of varying different components.

Page Model :

public class Page
    {
        public int id { get; set; }
        public string pagename { get; set; }
        public string metatitle { get; set; }
        public string metadescription { get; set; }
        public string created_at { get; set; }
        public string updated_at { get; set; }
        public List<Component> components { get; set; }
    }

    public class Pages
    {
        public List<Page> pages { get; set; }
    }

Component Model:

public class Component
    {
        public string component { get; set; }
        public int id { get; set; }
    }

A Component :

public class Title : Component
    {
        public string component { get; set; }
        public int id { get; set; {
        public string titletext { get; set; }
    }

This is the JSON:

{
      "id":1,
      "pagename":"home",
      "metatitle":"no title",
      "metadescription":"no meta",
      "created_at":"2020-05-31T16:35:52.084Z",
      "updated_at":"2020-05-31T16:35:52.084Z",
      "components":[
         {
            "component":"components.titletext",
            "id":1,
            "titletext":"hello"
         },
         {
            "component":"components.section",
            "id":2,
            "titletext":"hello",
            "descriptiontext":"its a beatiful day in lost santos",
            "buttonlink":"/go"
         },
         {
            "component":"components.cta",
            "id":3,
            "sectiontitle":"hello",
            "buttonlink":"/go",
            "buttontext":"click me"
         }
      ]
   }

Body:
If you don't want to add all properties to the Component class like that:

public class Component
{
    public string component { get; set; }
    public int id { get; set; }
    public string titletext { get; set; }
    public string sectiontitle { get; set; }
    public string buttonlink { get; set; }
    public string descriptiontext { get; set; }
}

You will need to write custom JsonConverter for example (not very performant implementation but works with your json and you will not need to parse every field by hand):

public class ComponentConverter : JsonConverter<Component>
{
    public override Component Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        using (var doc = JsonDocument.ParseValue(ref reader))
        {
            var type = doc.RootElement.GetProperty(@"component").GetString();
            switch(type)
            {
                case "components.titletext":
                    return JsonSerializer.Deserialize<Title>(doc.RootElement.GetRawText());
                // other types handling
                default: return JsonSerializer.Deserialize<Component>(doc.RootElement.GetRawText());
            }
        }
    }

    public override void Write(Utf8JsonWriter writer, Component value, JsonSerializerOptions options)
    {
        throw new NotImplementedException();
    }
}

public class Component
{
    public string component { get; set; }
    public int id { get; set; }
}

public class Title : Component
{
    public string titletext { get; set; }
}

And usage example:

var json = @"[
     {
        ""component"":""components.titletext"",
        ""id"":1,
        ""titletext"":""hello""
     },
     {
""component"":""components.section"",
        ""id"":2,
        ""titletext"":""hello"",
        ""descriptiontext"":""its a beatiful day in lost santos"",
        ""buttonlink"":""/go""
     },
     {
""component"":""components.cta"",
        ""id"":3,
        ""sectiontitle"":""hello"",
        ""buttonlink"":""/go"",
        ""buttontext"":""click me""
     }
  ]";
var deserializeOptions = new JsonSerializerOptions();
deserializeOptions.Converters.Add(new ComponentConverter());
JsonSerializer.Deserialize<List<Component>>(json, deserializeOptions).Dump();

Also do not use this converter as parameter for JsonConverterAttribute cause it will end in stackoverflow.


问:
How should i connect Schema models in Mongoose?
i want to make a User, Post and comment. connect them together and when i create a Post, it should be connected to one of my users. I don't know why i get an unusual error. Error:

```<code>ID cannot represent value: <Buffer 5e 9b f1 3e e9 49 61 38 fc 1a 6f 59>
</code>```

these are all of my code so if you know whats my problem please help me fix it. Thanks

typeDefs:

```<code>import { gql } from 'apollo-server-express';

export const typeDefs = gql`

    type User {
        id: ID!
        name: String!
        email: String!
        age: Int
        posts: [Post!]!
        comments: [Comment!]!
    }

    type Post {
        id: ID!
        title: String!
        body: String!
        published: Boolean!
        author: User!
        comments: [Comment!]!
    }

    type Comment {
        id: ID!
        text: String!
        author: User!
        post: Post!
    }
`
</code>```

UserSchema:

```<code>import mongoose, { mongo } from 'mongoose';

const userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    age: {
        type: Number,
        required: false
    },
    posts: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Post'
        }
    ],
    comments: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Comment'
        }
    ]
});

module.exports = mongoose.model('User',userSchema);
</code>```

PostSchema:

```<code>import mongoose from 'mongoose';

const postSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    body: {
        type: String,
        required: true
    },
    published: {
        type: Boolean,
        required: true
    },
    author: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    comments: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Comment'
        }
    ]
});

module.exports = mongoose.model('Post',postSchema);
</code>```

CommentSchema:

```<code>import mongoose from 'mongoose';

const commentSchema = new mongoose.Schema({
    text: {
        type: String,
        required: true
    },
    author: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    post: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Post'
    }
});

module.exports = mongoose.model('Comment',commentSchema);
</code>```

Resolver:

```<code>import Users from './models/User';
import Posts from './models/Post';
import Comments from './models/Comment';

export const resolvers = {
    Mutation: {
        createUser: async (parent, args, context, info) => {
            const user = new Users(args);
            await user.save();

            return user;
        },
        createPost: async (parent, { title, body, published, author }, context, info) => {
            const user = await Users.findById(author);

            if (!user) {
                console.log("User not found")
            }
            console.log(user)

            const post = new Posts({ title, body, published, author: user.id });
            await post.save();

            user.posts.push(post);
            await user.save();

            return post;
        }
    }
}
</code>```

答: I have found the solution and you should use type: mongoose.Schema.Types.ObjectId and ref: 'Comment' and after that inside resolvers you should use population .

Body:
i want to make a User, Post and comment. connect them together and when i create a Post, it should be connected to one of my users. I don't know why i get an unusual error. Error:

ID cannot represent value: <Buffer 5e 9b f1 3e e9 49 61 38 fc 1a 6f 59>

these are all of my code so if you know whats my problem please help me fix it. Thanks

typeDefs:

import { gql } from 'apollo-server-express';

export const typeDefs = gql`

    type User {
        id: ID!
        name: String!
        email: String!
        age: Int
        posts: [Post!]!
        comments: [Comment!]!
    }

    type Post {
        id: ID!
        title: String!
        body: String!
        published: Boolean!
        author: User!
        comments: [Comment!]!
    }

    type Comment {
        id: ID!
        text: String!
        author: User!
        post: Post!
    }
`

UserSchema:

import mongoose, { mongo } from 'mongoose';

const userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    age: {
        type: Number,
        required: false
    },
    posts: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Post'
        }
    ],
    comments: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Comment'
        }
    ]
});

module.exports = mongoose.model('User',userSchema);

PostSchema:

import mongoose from 'mongoose';

const postSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    body: {
        type: String,
        required: true
    },
    published: {
        type: Boolean,
        required: true
    },
    author: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    comments: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Comment'
        }
    ]
});

module.exports = mongoose.model('Post',postSchema);

CommentSchema:

import mongoose from 'mongoose';

const commentSchema = new mongoose.Schema({
    text: {
        type: String,
        required: true
    },
    author: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    post: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Post'
    }
});

module.exports = mongoose.model('Comment',commentSchema);

Resolver:

import Users from './models/User';
import Posts from './models/Post';
import Comments from './models/Comment';

export const resolvers = {
    Mutation: {
        createUser: async (parent, args, context, info) => {
            const user = new Users(args);
            await user.save();

            return user;
        },
        createPost: async (parent, { title, body, published, author }, context, info) => {
            const user = await Users.findById(author);

            if (!user) {
                console.log("User not found")
            }
            console.log(user)

            const post = new Posts({ title, body, published, author: user.id });
            await post.save();

            user.posts.push(post);
            await user.save();

            return post;
        }
    }
}


问:
How can I make my python window more presentable?
I am studying python in high school so I am sorry if the answer to my problem seems obvious or that my code is sloppy.

I am using tkinter in python to make a window where the user puts what ingredients he has and when clicking on confirm, the window will show the recipes available to them inside a canvas. Here's what it currently looks like (apologies, the language is in French but it should be readable)

Here's what my code looks like:

```<code>def takequantity():
 mondico["Tomate"] = saisirtomate.get()
 mondico["Fromage"] = saisirfromage.get()
 mondico["Farine"]= saisirfarine.get()
 #I copy and paste this as many times as I need for about 20 ingrediants

 if (mondico["Tomate"]>=5 and
     mondico["Farine"]>=500 and
     mondico["Fromage"]>=50):
    recette=can.create_text(300, 200, text="Pizza")
    #basically, if the ingrediants pass a certain threshold, it will recommend the Pizza recipe

mondico = {}
mondico["Tomate"] = 0
mondico["Farine"] = 0
mondico["Fromage"] = 0
#I copy and paste this as many times as I need for about 20 ingrediants
</code>```

Below this, I have this:

```<code>import tkinter as tk

window=tk.Tk()
window.geometry("900x900")
window.minsize(height=900 ,  width=900)
window.config(background='#B8FAEF')

frame=tk.Frame(window, bg='#B8FAEF')

label_title = tk.Label(window, text="SmartFridgoo", font=("Comic Sans MS", 20))
label_title.pack()

label_subtitle = tk.Label(window, text="Veuillez entrez vos ingrédients", font=("Comic Sans MS", 10))
label_subtitle.pack()

frame.pack(expand=1)

Texttomate=tk.Label(window,text="Tomates",)
Texttomate.pack()
saisirtomate=tk.IntVar()
saisietomate=tk.Entry(textvariable=saisirtomate, width=9, justify='center')
saisietomate.pack()
#I copy and paste this, you get the idea

bouton=tk.Button(window,text="Confirmer et faire apparaître les recettes", command=takequantity)
bouton.pack()

can=tk.Canvas(window, bg='#B8FAEF', height=400, width=600)
can.pack()

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

What I would like is so that the slots where you put the numbers don't stack on top of each other and align like that. A grid formation would be nice, but I don't know how to do that.
I also would want to make it so the recipes appear at the center of the canvas but also that if multiple recipes are possible, I would want them to be neatly arranged and not on top of each other. How can I do that?

My apologies if I've done something wrong, it's my first post here.

EDIT: I would also like to be able to put a link attached to the text showing up. For example, when you would click on "Pizza" it would redirect you to a youtube recipe. I looked up how to do it with .bind but it doesn't work with texts from "can.create_text"

答: Grid formation is pretty easy in tkinter check effbot.org Cool thing is, you can use grid in your main window and also inside frames. For example you can create few frames and insert widgets inside with widg.grid(), and then place frames in window also using grid.

Body:
I am studying python in high school so I am sorry if the answer to my problem seems obvious or that my code is sloppy.

I am using tkinter in python to make a window where the user puts what ingredients he has and when clicking on confirm, the window will show the recipes available to them inside a canvas. Here's what it currently looks like (apologies, the language is in French but it should be readable)

Here's what my code looks like:

def takequantity():
 mondico["Tomate"] = saisirtomate.get()
 mondico["Fromage"] = saisirfromage.get()
 mondico["Farine"]= saisirfarine.get()
 #I copy and paste this as many times as I need for about 20 ingrediants

 if (mondico["Tomate"]>=5 and
     mondico["Farine"]>=500 and
     mondico["Fromage"]>=50):
    recette=can.create_text(300, 200, text="Pizza")
    #basically, if the ingrediants pass a certain threshold, it will recommend the Pizza recipe

mondico = {}
mondico["Tomate"] = 0
mondico["Farine"] = 0
mondico["Fromage"] = 0
#I copy and paste this as many times as I need for about 20 ingrediants

Below this, I have this:

import tkinter as tk

window=tk.Tk()
window.geometry("900x900")
window.minsize(height=900 ,  width=900)
window.config(background='#B8FAEF')

frame=tk.Frame(window, bg='#B8FAEF')

label_title = tk.Label(window, text="SmartFridgoo", font=("Comic Sans MS", 20))
label_title.pack()

label_subtitle = tk.Label(window, text="Veuillez entrez vos ingrédients", font=("Comic Sans MS", 10))
label_subtitle.pack()

frame.pack(expand=1)

Texttomate=tk.Label(window,text="Tomates",)
Texttomate.pack()
saisirtomate=tk.IntVar()
saisietomate=tk.Entry(textvariable=saisirtomate, width=9, justify='center')
saisietomate.pack()
#I copy and paste this, you get the idea

bouton=tk.Button(window,text="Confirmer et faire apparaître les recettes", command=takequantity)
bouton.pack()

can=tk.Canvas(window, bg='#B8FAEF', height=400, width=600)
can.pack()

window.mainloop()

What I would like is so that the slots where you put the numbers don't stack on top of each other and align like that. A grid formation would be nice, but I don't know how to do that.
I also would want to make it so the recipes appear at the center of the canvas but also that if multiple recipes are possible, I would want them to be neatly arranged and not on top of each other. How can I do that?

My apologies if I've done something wrong, it's my first post here.

EDIT: I would also like to be able to put a link attached to the text showing up. For example, when you would click on "Pizza" it would redirect you to a youtube recipe. I looked up how to do it with .bind but it doesn't work with texts from "can.create_text"


问:
How to pipeline in node.js to redis?
I have lot's of data to insert (SET \ INCR) to redis DB, so I'm looking for pipeline \ mass insertion through node.js.

I couldn't find any good example/ API for doing so in node.js, so any help would be great!

答: By default, node_redis, the Node.js library sends commands in pipelines and automatically chooses how many commands will go into each pipeline [(https://github.com/NodeRedis/node-redis/issues/539#issuecomment-32203325)][1]. Therefore, you don't need to worry about this. However, other Redis clients may not use pipelines by default; you will need to check out the client documentation to see how to take advantage of pipelines.</p>

ContentLicense: CC BY-SA 3.0

Title: How to pipeline in node.js to redis?


问:
Database Filter Issue On Laravel
I am Using Laravel

below mentioned is one of my db table columns
:

```<code>{ "body": { "age": { "dob": "1960-01-28", "age_in_years": 60, "dob_computed": false }, "gender": "female", "address": { "street": "No.341,KC De silvapura", "country": "LK", "locality": "Thimbirigaskatuwa", "postcode": "N/A" }, "comment": "", "id_type": "NID", "id_number": 869000000000, "last_name": "Dayawansa", "member_id": "", "first_name": "jj", "preferred_name": "", "contact_details": { "email": "", "phone_number_alternate": "", "phone_number_preferred": 716900761 }, "consent_obtained": true, "alternate_contacts_details": { "name": "", "email": "", "phone_alternate": "", "phone_preferred": "" } }, "meta": { "end_time": "2019-09-06", "start_time": "2019-09-06", "registered_by": "24f57630-a102-11ea-a415-23a06eeb8904" } }
</code>```

my code is
My controller
:

```<code> $start_date = $request->has('startDate') ? $request->get('startDate') : Carbon::now()->subDays(30)->format('m/d/Y');
 $end_date = $request->has('endDate') ? Carbon::parse($request->get('endDate'))->addDays(1)->format('m/d/Y') : Carbon::now()->addDays(1)->format('m/d/Y');
</code>```

if i use created at it works

```<code>$participants = Participant::Where('created_at', '>=', $start_date)
        ->where('created_at', '<=', $end_date);
</code>```

if is use start_time which is inside a array it returns empty

```<code>$participants = Participant::Where('data->meta->start_time', '>=', $start_date)
        ->where('data->meta->start_time', '<=', $end_date);
</code>```

this isn't working
any suggestion where am i wrong ?

答:
Use whereBetween method of elocuent:

```<code>$start_date = $request->has('startDate') ? $request->get('startDate') : Carbon::now()->subDays(30)->format('m/d/Y');
$end_date = $request->has('endDate') ? Carbon::parse($request->get('endDate'))->addDays(1)->format('m/d/Y') : Carbon::now()->addDays(1)->format('m/d/Y');

$participants = Participant::whereBetween('start_time', [$start_date , $end_date])->get(); // or ->first() ur choice.
</code>```

to more details

Title: Database Filter Issue On Laravel

Body:
I am Using Laravel

below mentioned is one of my db table columns
:

{ "body": { "age": { "dob": "1960-01-28", "age_in_years": 60, "dob_computed": false }, "gender": "female", "address": { "street": "No.341,KC De silvapura", "country": "LK", "locality": "Thimbirigaskatuwa", "postcode": "N/A" }, "comment": "", "id_type": "NID", "id_number": 869000000000, "last_name": "Dayawansa", "member_id": "", "first_name": "jj", "preferred_name": "", "contact_details": { "email": "", "phone_number_alternate": "", "phone_number_preferred": 716900761 }, "consent_obtained": true, "alternate_contacts_details": { "name": "", "email": "", "phone_alternate": "", "phone_preferred": "" } }, "meta": { "end_time": "2019-09-06", "start_time": "2019-09-06", "registered_by": "24f57630-a102-11ea-a415-23a06eeb8904" } }

my code is
My controller
:

 $start_date = $request->has('startDate') ? $request->get('startDate') : Carbon::now()->subDays(30)->format('m/d/Y');
 $end_date = $request->has('endDate') ? Carbon::parse($request->get('endDate'))->addDays(1)->format('m/d/Y') : Carbon::now()->addDays(1)->format('m/d/Y');

if i use created at it works

$participants = Participant::Where('created_at', '>=', $start_date)
        ->where('created_at', '<=', $end_date);

if is use start_time which is inside a array it returns empty

$participants = Participant::Where('data->meta->start_time', '>=', $start_date)
        ->where('data->meta->start_time', '<=', $end_date);

this isn't working
any suggestion where am i wrong ?

Body:
Use whereBetween method of elocuent:

$start_date = $request->has('startDate') ? $request->get('startDate') : Carbon::now()->subDays(30)->format('m/d/Y');
$end_date = $request->has('endDate') ? Carbon::parse($request->get('endDate'))->addDays(1)->format('m/d/Y') : Carbon::now()->addDays(1)->format('m/d/Y');

$participants = Participant::whereBetween('start_time', [$start_date , $end_date])->get(); // or ->first() ur choice.

to more details


问:
C#: how to handle floats properly
In my code i write the following line:

```<code>return ((value / 120) * 1440).ToString();
</code>```

Now this returns me 0 when the value in value is less than Zero because it treats the result of (value / 120) as an integer where as i need C# to treat this result as float is there any way to achieve this?

Example:
If Value = 80

Then,
This function returns me 0 whereas i want this function to return me 960

答:
Dividing by 120.0(which is a double)

converts value also to double and divides

```<code>((value / 120.0) * 1440).ToString();
</code>```

Title: C#: how to handle floats properly

Body:
In my code i write the following line:

return ((value / 120) * 1440).ToString();

Now this returns me 0 when the value in value is less than Zero because it treats the result of (value / 120) as an integer where as i need C# to treat this result as float is there any way to achieve this?

Example:
If Value = 80

Then,
This function returns me 0 whereas i want this function to return me 960

Body:
Dividing by 120.0(which is a double)

converts value also to double and divides

((value / 120.0) * 1440).ToString();


问:
How to call function from other file
structure

```<code>.
├── deck.go
└── main.go
</code>```

Here is the code in each .go file

main.go

```<code>package main

func main() {
    cards := newDeck()
    cards.print()
}
</code>```

deck.go

```<code>package main

import "fmt"

type card struct {
    value string
    suit  string
}

type deck []card

func newDeck() deck {
    cards := deck{}

    cardSuits := []string{"Spades", "Diamonds", "Hearts", "Clubs"}
    cardValues := []string{"Ace", "Two", "Three"}

    for _, suit := range cardSuits {
        for _, value := range cardValues {
            cards = append(cards, card{
                suit:  suit,
                value: value,
            })
        }
    }
    return cards
}

func (d deck) print() {
    for i, card := range d {
        fmt.Printf("%d) %s of %s\n", i, card.value, card.suit)
    }
}
</code>```

Why I can't run main.go file? please help TT

```<code>❯ go version
go version go1.14.3 darwin/amd64

❯ go run main.go
# command-line-arguments
./main.go:4:11: undefined: newDeck
</code>```

答:
Modules in Golang are determined by their parent folder. Across modules, the object must be capitalized to be exported. This is not your case.

Your error is in the compilation stage; this is similar to gcc when it can't find header files. You have to tell the Go compiler to search all files in the current module.

go run .

This tells go to include all files in the current (.) module (folder). Since newDeck is in a different file and the compiler is only running main, it can't find newDeck. But if you run all files, it will search and find the func in deck.go.

Title: How to call function from other file

Body:
structure

.
├── deck.go
└── main.go

Here is the code in each .go file

main.go

package main

func main() {
    cards := newDeck()
    cards.print()
}

deck.go

package main

import "fmt"

type card struct {
    value string
    suit  string
}

type deck []card

func newDeck() deck {
    cards := deck{}

    cardSuits := []string{"Spades", "Diamonds", "Hearts", "Clubs"}
    cardValues := []string{"Ace", "Two", "Three"}

    for _, suit := range cardSuits {
        for _, value := range cardValues {
            cards = append(cards, card{
                suit:  suit,
                value: value,
            })
        }
    }
    return cards
}

func (d deck) print() {
    for i, card := range d {
        fmt.Printf("%d) %s of %s\n", i, card.value, card.suit)
    }
}

Why I can't run main.go file? please help TT

❯ go version
go version go1.14.3 darwin/amd64

❯ go run main.go
# command-line-arguments
./main.go:4:11: undefined: newDeck


问:
Need advice with my average calculator code
Good day,

I need help with my below code. I have a problem with calculating the average.
The code works as it should expect for calculating the average of the second entry.

I have highlighted the average that does not add up in the below picture. Its weird that the average is only not adding up on the second entry?

```<code>#include <iostream>

using namespace std;

float snelheid[][50] = {{}};
float lading[] = {};
float snelheidGem[] = {0};
int ladingNo = 1;
int snelheidToets = 1;

int main()
{
    cout << "Hoeveel ladings word getoets?: ";
    cin >> ladingNo;

    for (int i = 0; i < ladingNo; i++)
    {
        int n = i + 1;
        if (n == 1 || n == 8 || n > 19)
        {
            cout <<"Wat was die " << n << "st lading?: ";
            cin >> lading[i];
            cout <<"Hoeveel skote was geskiet vir die "<< n << "st lading?: ";
            cin >> snelheidToets;
            snelheidGem[i] = {0};
            for (int t = 0; t < snelheidToets; t++)
            {
                int m = t + 1;
                if (m == 1 || m == 8 || m > 19)
                {
                    cout <<"Wat was die spoed van die " << m << "st skoot?: ";
                    cin >> snelheid[i][t];
                }
                else
                {
                    cout <<"Wat was die spoed van die " << m << "de skoot?: ";
                    cin >> snelheid[i][t];
                }
                snelheidGem[i]=snelheidGem[i]+snelheid[i][t];
            }
            snelheidGem[i] = snelheidGem[i]/snelheidToets;
            cout << snelheidGem [i] << endl;
            cout << endl;
        }
        else
        {
            cout <<"Wat is die " << n << "de lading?: ";
            cin >> lading[i];
            cout <<"Hoeveel skote was geskiet vir die "<< n << "de lading?: ";
            cin >> snelheidToets;
            snelheidGem[i] = {0};
            for (int t = 0; t < snelheidToets; t++)
            {
                snelheid[i][t] = {0};
                int m = t + 1;
                if (m == 1 || m == 8 || m > 19)
                {
                    cout <<"Wat was die spoed van die " << m << "st skoot?: ";
                    cin >> snelheid[i][t];
                }
                else
                {
                    cout <<"Wat was die spoed van die " << m << "de skoot?: ";
                    cin >> snelheid[i][t];
                }
                snelheidGem[i]=snelheidGem[i]+snelheid[i][t];
                cout << snelheid[i][t] << " snelheid" << endl;
                cout << snelheidGem[i] << " gemiddeld" << endl;

            }
            snelheidGem[i] = snelheidGem[i]/snelheidToets;
            cout << snelheidGem [i] << endl;
            cout << endl;

        }

    }

    return 0;
}
</code>```

Average calculation

答:
On this line:

```<code>float snelheidGem[] = {0};
</code>```

you are creating an array of size 1, but are then indexing elements such as snelheidGem[1], and snelheidGem[2], etc, which invokes undefined behavior (UB). UB means anything can happen, including giving the correct average sometimes, but not at other times.

You can give it a sufficiently large size:

```<code>float snelheidGem[50] = {0};
</code>```

or much better, use a std::vector, to which you can add elements by doing push_back.

Note that you have the same issue with:

```<code>float lading[] = {};
</code>```

Body:
Good day,

I need help with my below code. I have a problem with calculating the average.
The code works as it should expect for calculating the average of the second entry.

I have highlighted the average that does not add up in the below picture. Its weird that the average is only not adding up on the second entry?

#include <iostream>

using namespace std;

float snelheid[][50] = {{}};
float lading[] = {};
float snelheidGem[] = {0};
int ladingNo = 1;
int snelheidToets = 1;

int main()
{
    cout << "Hoeveel ladings word getoets?: ";
    cin >> ladingNo;

    for (int i = 0; i < ladingNo; i++)
    {
        int n = i + 1;
        if (n == 1 || n == 8 || n > 19)
        {
            cout <<"Wat was die " << n << "st lading?: ";
            cin >> lading[i];
            cout <<"Hoeveel skote was geskiet vir die "<< n << "st lading?: ";
            cin >> snelheidToets;
            snelheidGem[i] = {0};
            for (int t = 0; t < snelheidToets; t++)
            {
                int m = t + 1;
                if (m == 1 || m == 8 || m > 19)
                {
                    cout <<"Wat was die spoed van die " << m << "st skoot?: ";
                    cin >> snelheid[i][t];
                }
                else
                {
                    cout <<"Wat was die spoed van die " << m << "de skoot?: ";
                    cin >> snelheid[i][t];
                }
                snelheidGem[i]=snelheidGem[i]+snelheid[i][t];
            }
            snelheidGem[i] = snelheidGem[i]/snelheidToets;
            cout << snelheidGem [i] << endl;
            cout << endl;
        }
        else
        {
            cout <<"Wat is die " << n << "de lading?: ";
            cin >> lading[i];
            cout <<"Hoeveel skote was geskiet vir die "<< n << "de lading?: ";
            cin >> snelheidToets;
            snelheidGem[i] = {0};
            for (int t = 0; t < snelheidToets; t++)
            {
                snelheid[i][t] = {0};
                int m = t + 1;
                if (m == 1 || m == 8 || m > 19)
                {
                    cout <<"Wat was die spoed van die " << m << "st skoot?: ";
                    cin >> snelheid[i][t];
                }
                else
                {
                    cout <<"Wat was die spoed van die " << m << "de skoot?: ";
                    cin >> snelheid[i][t];
                }
                snelheidGem[i]=snelheidGem[i]+snelheid[i][t];
                cout << snelheid[i][t] << " snelheid" << endl;
                cout << snelheidGem[i] << " gemiddeld" << endl;

            }
            snelheidGem[i] = snelheidGem[i]/snelheidToets;
            cout << snelheidGem [i] << endl;
            cout << endl;

        }

    }

    return 0;
}

Average calculation

Body:
On this line:

float snelheidGem[] = {0};

you are creating an array of size 1, but are then indexing elements such as snelheidGem[1], and snelheidGem[2], etc, which invokes undefined behavior (UB). UB means anything can happen, including giving the correct average sometimes, but not at other times.

You can give it a sufficiently large size:

float snelheidGem[50] = {0};

or much better, use a std::vector, to which you can add elements by doing push_back.

Note that you have the same issue with:

float lading[] = {};


问:
Trigger button click from other button
I'm trying to trigger a button click from another button to use in my squarespace website.

I'm adding the following to the header:

```

When I click the OfferteHeader button nothing happens :(.

OfferteHeader and offerteForm seem to refference fine when I log the to the console.

Also firing offerteForm.click() from the chrome dev console seem to work fine and trigger the event.

I also checked if the listener was working with a log to the console and if it could refference to offerteForm.

What is the problem here? The site can be found on https://sturgeon-groundhog-cnzt.squarespace.com/ password is bellboy. Sorry, it's a squarespace site, can not change that.

答:
this isn't best practice but working:</p>

```<code>$(document).ready(function() {
  var offerteHeader = $("a.theme-btn--primary-inverse:contains('Offerte aanvragen')");
  var offerteForm = $("button:contains('Offerte aanvragen')");
  offerteHeader.click(function(e) {
    setTimeout(function() {
      offerteForm.trigger("click")
    });
  });
});
</code>```

Title: Trigger button click from other button

Body:
I'm trying to trigger a button click from another button to use in my squarespace website.

I'm adding the following to the header:

When I click the OfferteHeader button nothing happens :(.

OfferteHeader and offerteForm seem to refference fine when I log the to the console.

Also firing offerteForm.click() from the chrome dev console seem to work fine and trigger the event.

I also checked if the listener was working with a log to the console and if it could refference to offerteForm.

What is the problem here? The site can be found on https://sturgeon-groundhog-cnzt.squarespace.com/ password is bellboy. Sorry, it's a squarespace site, can not change that.

Body:
this isn't best practice but working:

$(document).ready(function() {
  var offerteHeader = $("a.theme-btn--primary-inverse:contains('Offerte aanvragen')");
  var offerteForm = $("button:contains('Offerte aanvragen')");
  offerteHeader.click(function(e) {
    setTimeout(function() {
      offerteForm.trigger("click")
    });
  });
});


问:
How to send a POST request with Advanced Custom Fields data
I'm trying to send a post request to the rest api with some custom fields. THis is my code

```<code>                let newCharacter = {
                    'title': $('.create-char-name').val(),
                    'acf': {
                        'char_class': $('#char-class').val(),
                        'char_subclass': $('#char-subclass').val(),
                        'char_level': $('#char-level').val()
                    },
                    'status': 'publish'
                }

                $.ajax({
                    beforeSend: (xhr) => {
                        xhr.setRequestHeader('X-WP-Nonce', spbk_data.nonce);
                    },
                    url: spbk_data.root_url + '/wp-json/wp/v2/character/',
                    method: 'POST',
                    data: newCharacter,
                    success: (response) => {
                        console.log("congrats");
                        console.log(response);
                    },
                    error: (response) => {
                        console.log("Sorry");
                        console.log(response);
                    }
                });
</code>```

The request goes through without any problems, but when I check the json, the "acf" field returns false.
I'm using the acf to wp api plugin, if that information is useful.

The only info I found about this issue was this post, but I don't really understand what the answer meant. I tried adding xhr.setRequestHeader('Content-Type', application/json); (I also tried with lower case initials), below the nonce, like the post seems to suggest, but that returns this error:

"{"code":"rest_invalid_json","message":"Invalid JSON body passed.","data":{"status":400,"json_error_code":4,"json_error_message":"Syntax error"}}"

答:
Yeah, I'm kinda dumb. I tried another plugin to make the bridge between acf and the rest api, and it worked.

It came to my mind many times to try another plugin, but I thought "they do the same thing, there's no point in trying that". It goes to show that you shouldn't just brush off solutions that seem too obvious or stupid.

Body:
I'm trying to send a post request to the rest api with some custom fields. THis is my code

                let newCharacter = {
                    'title': $('.create-char-name').val(),
                    'acf': {
                        'char_class': $('#char-class').val(),
                        'char_subclass': $('#char-subclass').val(),
                        'char_level': $('#char-level').val()
                    },
                    'status': 'publish'
                }

                $.ajax({
                    beforeSend: (xhr) => {
                        xhr.setRequestHeader('X-WP-Nonce', spbk_data.nonce);
                    },
                    url: spbk_data.root_url + '/wp-json/wp/v2/character/',
                    method: 'POST',
                    data: newCharacter,
                    success: (response) => {
                        console.log("congrats");
                        console.log(response);
                    },
                    error: (response) => {
                        console.log("Sorry");
                        console.log(response);
                    }
                });

The request goes through without any problems, but when I check the json, the "acf" field returns false.
I'm using the acf to wp api plugin, if that information is useful.

The only info I found about this issue was this post, but I don't really understand what the answer meant. I tried adding xhr.setRequestHeader('Content-Type', application/json); (I also tried with lower case initials), below the nonce, like the post seems to suggest, but that returns this error:

"{"code":"rest_invalid_json","message":"Invalid JSON body passed.","data":{"status":400,"json_error_code":4,"json_error_message":"Syntax error"}}"


问:
change expanding space of nested layouts in pyqt
I want to seperate the widgets of the mainwindow into 3 layouts and add them into a mainlayout
the center layout contains a tablewidget and shoud have a bigger width then the left/right one. so far I did not found a way to use a grid layout and adjust each column width individualy.

therefore I tryed to use 3 vboxlayouts and insert them into an hboxlayout

what if read so far is that the widgets size are fixed so they expand at the same rate if stretched.

is there an easier way to make the center layout widht bigger with for example inserting an spacer without  changing  the SizePolicy of each widget ?

```<code>import sys

from PyQt5 import QtWidgets as qtw
from PyQt5 import QtCore as qtc
from PyQt5 import QtGui as qtg

class Stretchme(qtw.QWidget):
    def __init__(self):
        super().__init__()

        # # View
        table_widget = qtw.QTableWidget()

        # -----interface--widgets--------------------------#

        # -------- parameter_widgets------------#
        parameter_label = qtw.QLabel("Parameter")

        test_time_label = qtw.QLabel("Time")
        self.clocktime = qtw.QTimeEdit()
        test_date_label = qtw.QLabel("Date")
        self.date_time = qtw.QDateEdit()

        grob_fein_label = qtw.QLabel("Grobe")
        grob_fein_combo_box = qtw.QComboBox()

        vr_label = qtw.QLabel("Lame")
        self.vr_feuchte_input = qtw.QLineEdit()

        # leftvboxlayout
        left_vboxlayout = qtw.QVBoxLayout()

        left_vboxlayout.addStretch(1)

        left_vboxlayout.addWidget(test_time_label)
        left_vboxlayout.addWidget(self.clocktime)
        left_vboxlayout.addWidget(test_date_label)
        left_vboxlayout.addWidget(self.date_time)
        left_vboxlayout.addWidget(grob_fein_label)
        left_vboxlayout.addWidget(grob_fein_combo_box)
        left_vboxlayout.addWidget(vr_label)
        left_vboxlayout.addWidget(self.vr_feuchte_input)

        # centervboxlayout
        center_voboxlayout = qtw.QVBoxLayout()
        #
        # center_voboxlayout.addStretch()
        # center_voboxlayout.setStretchFactor()
        # center_voboxlayout.addSpacing()
        # center_voboxlayout.setStretchFactor()

        #
        # table_widget.setMinimumSize(90,80)

        center_voboxlayout.addWidget(table_widget)

        # righvobxlayout
        # buttons
        self.button_1 = qtw.QPushButton("Button 1")
        self.button_2 = qtw.QPushButton("Button 2")
        self.button_2 = qtw.QPushButton("Button 3")

        rightvboxlayout = qtw.QVBoxLayout()
        rightvboxlayout.addStretch(1)
        rightvboxlayout.addWidget(self.button_1)
        rightvboxlayout.addWidget(self.button_2)
        rightvboxlayout.addWidget(self.button_2)

        #
        #
        # Separador = qtw.QFrame()
        # # Separador.Shape(QFrame.HLine)
        # Separador.setFrameShape(qtw.QFrame.HLine)
        #
        # Separador.setSizePolicy(qtw.QSizePolicy.Minimum,qtw.QSizePolicy.Expanding)
        # Separador.setLineWidth(5)
        # # HPOUT1_layout = QVBoxLayout()
        # # HPOUT1_layout.addLayout(HPOUT1L_layout)
        # # HPOUT1_layout.addWidget(Separador)
        # # HPOUT1_layout.addLayout(HPOUT1R_layout)

        ## main layout
        self.qhboxlayout = qtw.QHBoxLayout()
        self.qhboxlayout.addLayout(left_vboxlayout)
        # self.qhboxlayout.addWidget(Separador)
        self.qhboxlayout.addLayout(center_voboxlayout)
        self.qhboxlayout.addLayout(rightvboxlayout)
        #
        # ### Main Grid

        # -------------------------------------------------- #
        selected_color = qtg.QColor(0,0,255)

        # self.setGeometry(300, 300, 1850, 950)
        self.setStyleSheet("background-color: {}")
        self.setLayout(self.qhboxlayout)

        self.show()

if __name__ == '__main__':
    app = qtw.QApplication(sys.argv)
    w = Stretchme()
    sys.exit(app.exec_())
</code>```

答:
You have to set a stretch factor when adding the central layout:

```<code># ...
self.qhboxlayout.addLayout(center_voboxlayout, <b>stretch=1</b>)
# ...</code>```

Body:
I want to seperate the widgets of the mainwindow into 3 layouts and add them into a mainlayout
the center layout contains a tablewidget and shoud have a bigger width then the left/right one. so far I did not found a way to use a grid layout and adjust each column width individualy.

therefore I tryed to use 3 vboxlayouts and insert them into an hboxlayout

what if read so far is that the widgets size are fixed so they expand at the same rate if stretched.

is there an easier way to make the center layout widht bigger with for example inserting an spacer without  changing  the SizePolicy of each widget ?

import sys

from PyQt5 import QtWidgets as qtw
from PyQt5 import QtCore as qtc
from PyQt5 import QtGui as qtg

class Stretchme(qtw.QWidget):
    def __init__(self):
        super().__init__()

        # # View
        table_widget = qtw.QTableWidget()

        # -----interface--widgets--------------------------#

        # -------- parameter_widgets------------#
        parameter_label = qtw.QLabel("Parameter")

        test_time_label = qtw.QLabel("Time")
        self.clocktime = qtw.QTimeEdit()
        test_date_label = qtw.QLabel("Date")
        self.date_time = qtw.QDateEdit()

        grob_fein_label = qtw.QLabel("Grobe")
        grob_fein_combo_box = qtw.QComboBox()

        vr_label = qtw.QLabel("Lame")
        self.vr_feuchte_input = qtw.QLineEdit()

        # leftvboxlayout
        left_vboxlayout = qtw.QVBoxLayout()

        left_vboxlayout.addStretch(1)

        left_vboxlayout.addWidget(test_time_label)
        left_vboxlayout.addWidget(self.clocktime)
        left_vboxlayout.addWidget(test_date_label)
        left_vboxlayout.addWidget(self.date_time)
        left_vboxlayout.addWidget(grob_fein_label)
        left_vboxlayout.addWidget(grob_fein_combo_box)
        left_vboxlayout.addWidget(vr_label)
        left_vboxlayout.addWidget(self.vr_feuchte_input)

        # centervboxlayout
        center_voboxlayout = qtw.QVBoxLayout()
        #
        # center_voboxlayout.addStretch()
        # center_voboxlayout.setStretchFactor()
        # center_voboxlayout.addSpacing()
        # center_voboxlayout.setStretchFactor()

        #
        # table_widget.setMinimumSize(90,80)

        center_voboxlayout.addWidget(table_widget)

        # righvobxlayout
        # buttons
        self.button_1 = qtw.QPushButton("Button 1")
        self.button_2 = qtw.QPushButton("Button 2")
        self.button_2 = qtw.QPushButton("Button 3")

        rightvboxlayout = qtw.QVBoxLayout()
        rightvboxlayout.addStretch(1)
        rightvboxlayout.addWidget(self.button_1)
        rightvboxlayout.addWidget(self.button_2)
        rightvboxlayout.addWidget(self.button_2)

        #
        #
        # Separador = qtw.QFrame()
        # # Separador.Shape(QFrame.HLine)
        # Separador.setFrameShape(qtw.QFrame.HLine)
        #
        # Separador.setSizePolicy(qtw.QSizePolicy.Minimum,qtw.QSizePolicy.Expanding)
        # Separador.setLineWidth(5)
        # # HPOUT1_layout = QVBoxLayout()
        # # HPOUT1_layout.addLayout(HPOUT1L_layout)
        # # HPOUT1_layout.addWidget(Separador)
        # # HPOUT1_layout.addLayout(HPOUT1R_layout)

        ## main layout
        self.qhboxlayout = qtw.QHBoxLayout()
        self.qhboxlayout.addLayout(left_vboxlayout)
        # self.qhboxlayout.addWidget(Separador)
        self.qhboxlayout.addLayout(center_voboxlayout)
        self.qhboxlayout.addLayout(rightvboxlayout)
        #
        # ### Main Grid

        # -------------------------------------------------- #
        selected_color = qtg.QColor(0,0,255)

        # self.setGeometry(300, 300, 1850, 950)
        self.setStyleSheet("background-color: {}")
        self.setLayout(self.qhboxlayout)

        self.show()

if __name__ == '__main__':
    app = qtw.QApplication(sys.argv)
    w = Stretchme()
    sys.exit(app.exec_())

Body:
You have to set a stretch factor when adding the central layout:

# ...
self.qhboxlayout.addLayout(center_voboxlayout, stretch=1)
# ...


问:
Cleanup old refs in Ruby Version Manager (RVM)
I need to free disk space on my local machine, which is almost allocated into my Ruby Version Manager (RVM) dir.

Now, it seems I got just one ruby version ( 1.9.2p136 ) :

```<code>lsoave@ubuntu:~/rails/github/gitwatcher$ ruby -v
ruby 1.9.2p136 (2010-12-25 revision 30365) [i686-linux]
lsoave@ubuntu:~/rails/github/gitwatcher$

lsoave@ubuntu:~/rails/github/gitwatcher$ rvm list
rvm rubies
=> ruby-1.9.2-p136 [ i386 ]
lsoave@ubuntu:~/rails/github/gitwatcher$

lsoave@ubuntu:~/rails/github/gitwatcher$ which ruby
/home/lsoave/.rvm/rubies/ruby-1.9.2-p136/bin/ruby
lsoave@ubuntu:~/rails/github/gitwatcher$
</code>```

but my RVM dir, have many others unrelated dirs/versions :

```<code>lsoave@ubuntu:~/rails/github/gitwatcher$ ls -la ~/.rvm/gems
total 72
drwxr-xr-x 18 lsoave lsoave 4096 2011-05-21 15:44 .
drwxr-xr-x 23 lsoave lsoave 4096 2011-02-10 22:46 ..
drwxr-xr-x  2 lsoave lsoave 4096 2010-08-29 19:50 cache
drwxr-xr-x  2 lsoave lsoave 4096 2010-08-31 21:50 jruby-1.3.7
drwxr-xr-x  2 lsoave lsoave 4096 2010-08-31 21:50 jruby-1.3.8
drwxr-xr-x  2 lsoave lsoave 4096 2011-05-21 15:44 ree-1.8.7-2010.02
drwxr-xr-x  8 lsoave lsoave 4096 2010-09-08 11:25 ruby-1.8.7-p302
drwxr-xr-x  7 lsoave lsoave 4096 2010-08-29 22:00 ruby-1.8.7-p302@global
drwxr-xr-x  7 lsoave lsoave 4096 2010-08-29 22:24 ruby-1.9.2-head
drwxr-xr-x  7 lsoave lsoave 4096 2010-08-29 22:24 ruby-1.9.2-head@global
drwxr-xr-x  8 lsoave lsoave 4096 2010-08-31 23:47 ruby-1.9.2-p0
drwxr-xr-x  7 lsoave lsoave 4096 2010-08-29 19:50 ruby-1.9.2-p0@global
drwxr-xr-x  8 lsoave lsoave 4096 2011-02-10 19:44 ruby-1.9.2-p136
drwxr-xr-x  7 lsoave lsoave 4096 2011-02-10 19:23 ruby-1.9.2-p136@global
drwxr-xr-x  7 lsoave lsoave 4096 2011-04-08 21:21 ruby-1.9.2-p136@greendog
drwxr-xr-x  7 lsoave lsoave 4096 2011-04-09 00:57 ruby-1.9.2-p136@greendog2
drwxr-xr-x  7 lsoave lsoave 4096 2011-02-15 00:09 ruby-1.9.2-p136@greendog99
drwxr-xr-x  2 lsoave lsoave 4096 2011-02-10 19:04 system
lsoave@ubuntu:~/rails/github/gitwatcher$
</code>```

is it save to remove all dirs remaining with just "ruby-1.9.2-p136" and "ruby-1.9.2-p136@global" dirs (ruby-1.9.2-p136@greendog* are old and "rvm system" return nothing) ? Will I use "rm" command, or are there RVM embodied commands to cleanup a better way ? Is it possible cleanup the cache dir ?

Thanks in advance.
luca

答:
I suppose rvm cleanup could do the trick.

Other than that I don't see any reason that deleting the actual gem directories inside RVM if they aren't associated with RVM any more.

If the matching entry doesn't exist in environments then it is safe to delete the accompanying gem dir. As nothing else points to it that RVM would be able to use.

Body:
I need to free disk space on my local machine, which is almost allocated into my Ruby Version Manager (RVM) dir.

Now, it seems I got just one ruby version ( 1.9.2p136 ) :

lsoave@ubuntu:~/rails/github/gitwatcher$ ruby -v
ruby 1.9.2p136 (2010-12-25 revision 30365) [i686-linux]
lsoave@ubuntu:~/rails/github/gitwatcher$

lsoave@ubuntu:~/rails/github/gitwatcher$ rvm list
rvm rubies
=> ruby-1.9.2-p136 [ i386 ]
lsoave@ubuntu:~/rails/github/gitwatcher$

lsoave@ubuntu:~/rails/github/gitwatcher$ which ruby
/home/lsoave/.rvm/rubies/ruby-1.9.2-p136/bin/ruby
lsoave@ubuntu:~/rails/github/gitwatcher$

but my RVM dir, have many others unrelated dirs/versions :

lsoave@ubuntu:~/rails/github/gitwatcher$ ls -la ~/.rvm/gems
total 72
drwxr-xr-x 18 lsoave lsoave 4096 2011-05-21 15:44 .
drwxr-xr-x 23 lsoave lsoave 4096 2011-02-10 22:46 ..
drwxr-xr-x  2 lsoave lsoave 4096 2010-08-29 19:50 cache
drwxr-xr-x  2 lsoave lsoave 4096 2010-08-31 21:50 jruby-1.3.7
drwxr-xr-x  2 lsoave lsoave 4096 2010-08-31 21:50 jruby-1.3.8
drwxr-xr-x  2 lsoave lsoave 4096 2011-05-21 15:44 ree-1.8.7-2010.02
drwxr-xr-x  8 lsoave lsoave 4096 2010-09-08 11:25 ruby-1.8.7-p302
drwxr-xr-x  7 lsoave lsoave 4096 2010-08-29 22:00 ruby-1.8.7-p302@global
drwxr-xr-x  7 lsoave lsoave 4096 2010-08-29 22:24 ruby-1.9.2-head
drwxr-xr-x  7 lsoave lsoave 4096 2010-08-29 22:24 ruby-1.9.2-head@global
drwxr-xr-x  8 lsoave lsoave 4096 2010-08-31 23:47 ruby-1.9.2-p0
drwxr-xr-x  7 lsoave lsoave 4096 2010-08-29 19:50 ruby-1.9.2-p0@global
drwxr-xr-x  8 lsoave lsoave 4096 2011-02-10 19:44 ruby-1.9.2-p136
drwxr-xr-x  7 lsoave lsoave 4096 2011-02-10 19:23 ruby-1.9.2-p136@global
drwxr-xr-x  7 lsoave lsoave 4096 2011-04-08 21:21 ruby-1.9.2-p136@greendog
drwxr-xr-x  7 lsoave lsoave 4096 2011-04-09 00:57 ruby-1.9.2-p136@greendog2
drwxr-xr-x  7 lsoave lsoave 4096 2011-02-15 00:09 ruby-1.9.2-p136@greendog99
drwxr-xr-x  2 lsoave lsoave 4096 2011-02-10 19:04 system
lsoave@ubuntu:~/rails/github/gitwatcher$

is it save to remove all dirs remaining with just "ruby-1.9.2-p136" and "ruby-1.9.2-p136@global" dirs (ruby-1.9.2-p136@greendog* are old and "rvm system" return nothing) ? Will I use "rm" command, or are there RVM embodied commands to cleanup a better way ? Is it possible cleanup the cache dir ?

Thanks in advance.
luca


问:
How to convert a datetime to date in R, WITHOUT rounding the day?
I'm using R and trying to convert a datetime field into just the date? R gives me the desired format but keeps rounding up some of the day values. Specifically everything after 12 noon! I could not find any threads that address this exact problem. I actually figured out a solution but wanted to post the question because I spent a whole week troubleshooting.

```<code>#Convert the datetime field from character to a datetime
main_df$datetime <- strptime(main_df$ï..Date, format = "%m/%d/%Y %H:%M")
main_df$datetime <- as.POSIXct(main_df$datetime, tz = Sys.timezone())
head(main_df$datetime)
class(main_df$datetime)

#Remove the poorly computer-titled character field that contained datetime info
main_df <- subset(main_df, select = -c(ï..Date))

#Use the NEW datetime field to create a date field
#main_df$Date <- trunc(main_df$datetime,"days")
main_df$Date <- as.Date(main_df$datetime, format = "%m/%d/%Y")
?as.Date()
class(main_df$Date)

head(main_df$Date)
</code>```

That returned:

```<code>head(main_df$datetime)
[1] "2020-05-16 00:31:00 CDT" "2020-05-16 00:30:00 CDT" "2020-05-15 23:33:00 CDT" "2020-05-15 15:33:00 CDT"
[5] "2020-05-15 22:31:00 CDT" "2020-05-15 22:12:00 CDT"
</code>```

and

```<code>> class(main_df$Date)
[1] "Date"
>
> head(main_df$Date)
[1] "2020-05-16" "2020-05-16" "2020-05-16" "2020-05-15" "2020-05-16" "2020-05-16"
</code>```

Notice how the last 4 values for 'Date' should be 2020-05-15 but instead, they are converted to be 2020-05-16. So what are some other ways to fix this? I'm going to post one way that worked but I doubt it's the cleanest.

答:
If we don't want to make use of the 'time', then use a regex to match a space followed by other characters (" .*"), replace with blank in sub and then convert to Date class.  The issue with converting to DateTime is that there are times "23:33:00" that would make it convert to next day

```<code>main_df$Date <- as.Date(sub(" .*", "", main_df$datetime), format = "%m/%d/%Y")
</code>```

Body:
I'm using R and trying to convert a datetime field into just the date? R gives me the desired format but keeps rounding up some of the day values. Specifically everything after 12 noon! I could not find any threads that address this exact problem. I actually figured out a solution but wanted to post the question because I spent a whole week troubleshooting.

#Convert the datetime field from character to a datetime
main_df$datetime <- strptime(main_df$ï..Date, format = "%m/%d/%Y %H:%M")
main_df$datetime <- as.POSIXct(main_df$datetime, tz = Sys.timezone())
head(main_df$datetime)
class(main_df$datetime)

#Remove the poorly computer-titled character field that contained datetime info
main_df <- subset(main_df, select = -c(ï..Date))

#Use the NEW datetime field to create a date field
#main_df$Date <- trunc(main_df$datetime,"days")
main_df$Date <- as.Date(main_df$datetime, format = "%m/%d/%Y")
?as.Date()
class(main_df$Date)

head(main_df$Date)

That returned:

head(main_df$datetime)
[1] "2020-05-16 00:31:00 CDT" "2020-05-16 00:30:00 CDT" "2020-05-15 23:33:00 CDT" "2020-05-15 15:33:00 CDT"
[5] "2020-05-15 22:31:00 CDT" "2020-05-15 22:12:00 CDT"

and

> class(main_df$Date)
[1] "Date"
>
> head(main_df$Date)
[1] "2020-05-16" "2020-05-16" "2020-05-16" "2020-05-15" "2020-05-16" "2020-05-16"

Notice how the last 4 values for 'Date' should be 2020-05-15 but instead, they are converted to be 2020-05-16. So what are some other ways to fix this? I'm going to post one way that worked but I doubt it's the cleanest.

Body:
If we don't want to make use of the 'time', then use a regex to match a space followed by other characters (" .*"), replace with blank in sub and then convert to Date class.  The issue with converting to DateTime is that there are times "23:33:00" that would make it convert to next day

main_df$Date <- as.Date(sub(" .*", "", main_df$datetime), format = "%m/%d/%Y")


问:
Cumulocity HTML widget cannot access child device data
I am trying to use HTML widget to display device and child devices property. I created a group and created 3-4 child devices under it. When I am using {{device.name}} it is showing the data of the group properly since I chose it as parent asset. But when I am trying to use {{device[12345].name}} it is not shoiwng anything.

答: did a rookie mistake , it will be {{devices[12345].name}}</p>


问:
Unity3D: Field currentActivity or type signature not found
after upgrading my unity version to 2019.2.17 i get this error:

Exception: Field currentActivity or type signature  not found
  UnityEngine._AndroidJNIHelper.GetFieldID (System.IntPtr jclass,
  System.String fieldName, System.String signature, System.Boolean
  isStatic)

when trying to get currentActivity with this code:

```<code>    // Retrieve the UnityPlayer class.
    unityPlayerClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");

    // Retrieve the UnityPlayerActivity object ( a.k.a. the current context )
    unityActivity = unityPlayerClass.GetStatic<AndroidJavaObject>("currentActivity");
</code>```

how can i resolve the problem?

答:
Had a similar issue, and after my head went all bold, I noticed that I didn't get this problem when I switch off the device simulator!!!

Hope this be of help.

Body:
after upgrading my unity version to 2019.2.17 i get this error:

Exception: Field currentActivity or type signature  not found
  UnityEngine._AndroidJNIHelper.GetFieldID (System.IntPtr jclass,
  System.String fieldName, System.String signature, System.Boolean
  isStatic)

when trying to get currentActivity with this code:

    // Retrieve the UnityPlayer class.
    unityPlayerClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");

    // Retrieve the UnityPlayerActivity object ( a.k.a. the current context )
    unityActivity = unityPlayerClass.GetStatic<AndroidJavaObject>("currentActivity");

how can i resolve the problem?


问:
Pandas | How to effectively filter a column
I'm looking for a way to quickly and effectively filter through a dataframe column and remove values that don't meet a condition.

Say, I have a column with the numbers 4, 5 and 10. I want to filter the column and replace any numbers above 7 with 0. How would I go about this?

答:
There is many options. One possibility for if then... is np.where

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame({'x': [1, 200, 4, 5, 6, 11],
                'y': [4, 5, 10, 24, 4 , 3]})
df['y'] = np.where(df['y'] > 7, 0, df['y'])
</code>```

Body:
There is many options. One possibility for if then... is np.where

import pandas as pd
import numpy as np

df = pd.DataFrame({'x': [1, 200, 4, 5, 6, 11],
                'y': [4, 5, 10, 24, 4 , 3]})
df['y'] = np.where(df['y'] > 7, 0, df['y'])


问:
Finding number of digits before a decimal point in java
I have declared the variable for the double I'm using:

```<code>z= 345.876;
</code>```

Now I want to display the number of digits that come before the decimal point. I tried to do the following:

```<code>String string_form = new Double(z).toString().subString(0,string_form.indexOf('.'));
double t = Double.valueOf(string_form);
</code>```

I get an error saying: 'The method subString(int, int) is undefined for the type String'

Then a quick fix shows to change it small case s as: substring. However the error then changes to the string, 'string_form' which says it's not initialized. Any ideas on what to do?

And also how would I modify that to find the number of digits that come after a number? I know in the part

```<code>.indexOf('.')
</code>```

I'd replace the decimal point with a number but how would i change it so that it displays how many digits come AFTER the number, not before? thanks. and yes I have imported the decimalformat text lang.

答:
Could do this, for examble:</p>

```<code>Integer.parseInt(String.valueOf(possibleBirths).split(".")[0]);
</code>```

Body:
I have declared the variable for the double I'm using:

z= 345.876;

Now I want to display the number of digits that come before the decimal point. I tried to do the following:

String string_form = new Double(z).toString().subString(0,string_form.indexOf('.'));
double t = Double.valueOf(string_form);

I get an error saying: 'The method subString(int, int) is undefined for the type String'

Then a quick fix shows to change it small case s as: substring. However the error then changes to the string, 'string_form' which says it's not initialized. Any ideas on what to do?

And also how would I modify that to find the number of digits that come after a number? I know in the part

.indexOf('.')

I'd replace the decimal point with a number but how would i change it so that it displays how many digits come AFTER the number, not before? thanks. and yes I have imported the decimalformat text lang.

Body:
Could do this, for examble:

Integer.parseInt(String.valueOf(possibleBirths).split(".")[0]);


问:
Eureka client in docker not connecting with Eureka server
I have one eureka server.

```<code>server:
  port: 8761
eureka:
  client:
    registerWithEureka: false
    fetchRegistry: false
</code>```

I have one eureka client.

```<code>spring:
  application:
    name: mysearch
server:
  port: 8020
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka
  instance:
    preferIpAddress: true
</code>```

My eureka client is running in a docker container.

```<code>FROM java:8
COPY ./mysearch.jar /var/tmp/app.jar
EXPOSE 8180
CMD ["java","-jar","/var/tmp/app.jar"]
</code>```

I am starting the eureka server by java -jar eureka-server.jar
After that I am starting the docker instance of the eureka client using
 sudo docker build -t web . and sudo docker run -p 8180:8020 -it web.
I am able to access the eureka client and server from browser but the client is not connecting with Eureka server. I am not able to see the client in the eureka server dashboard. I am getting below errors and warnings.

```<code>WARN 1 --- [tbeatExecutor-0] c.n.d.s.t.d.RetryableEurekaHttpClient    : Request execution failed with message: java.net.ConnectException: Connection refused (Connection refused)
ERROR 1 --- [tbeatExecutor-0] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_FLIGHTSEARCH/98b0d95fd668:flightsearch:8020 - was unable to send heartbeat!
INFO 1 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_FLIGHTSEARCH/98b0d95fd668:flightsearch:8020: registering service...
ERROR 1 --- [nfoReplicator-0] c.n.d.s.t.d.RedirectingEurekaHttpClient  : Request execution error
WARN 1 --- [nfoReplicator-0] c.n.d.s.t.d.RetryableEurekaHttpClient    : Request execution failed with message: java.net.ConnectException: Connection refused (Connection refused)
WARN 1 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_FLIGHTSEARCH/98b0d95fd668:flightsearch:8020 - registration failed Cannot execute request on any known server
WARN 1 --- [nfoReplicator-0] c.n.discovery.InstanceInfoReplicator     : There was a problem with the instance info replicator
</code>```

I am doing it in an AWS EC2 Ubuntu instance.
Can anyone please tell me what I am doing wrong here?

答:
In the container world, the eureka server ip address can change each time the eureka server is restarted. Hence specifying the host ip address for eureka server url doesn't work all the time.

In the docker-compose.yml, I had to link the eureka client service to the eureka server container. Until I link the services, eureka client couldn't connect to the server.

This is already answered in another post recently: Applications not registering to eureka when using docker-compose

Body:
I have one eureka server.

server:
  port: 8761
eureka:
  client:
    registerWithEureka: false
    fetchRegistry: false

I have one eureka client.

spring:
  application:
    name: mysearch
server:
  port: 8020
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka
  instance:
    preferIpAddress: true

My eureka client is running in a docker container.

FROM java:8
COPY ./mysearch.jar /var/tmp/app.jar
EXPOSE 8180
CMD ["java","-jar","/var/tmp/app.jar"]

I am starting the eureka server by java -jar eureka-server.jar
After that I am starting the docker instance of the eureka client using
 sudo docker build -t web . and sudo docker run -p 8180:8020 -it web.
I am able to access the eureka client and server from browser but the client is not connecting with Eureka server. I am not able to see the client in the eureka server dashboard. I am getting below errors and warnings.

WARN 1 --- [tbeatExecutor-0] c.n.d.s.t.d.RetryableEurekaHttpClient    : Request execution failed with message: java.net.ConnectException: Connection refused (Connection refused)
ERROR 1 --- [tbeatExecutor-0] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_FLIGHTSEARCH/98b0d95fd668:flightsearch:8020 - was unable to send heartbeat!
INFO 1 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_FLIGHTSEARCH/98b0d95fd668:flightsearch:8020: registering service...
ERROR 1 --- [nfoReplicator-0] c.n.d.s.t.d.RedirectingEurekaHttpClient  : Request execution error
WARN 1 --- [nfoReplicator-0] c.n.d.s.t.d.RetryableEurekaHttpClient    : Request execution failed with message: java.net.ConnectException: Connection refused (Connection refused)
WARN 1 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_FLIGHTSEARCH/98b0d95fd668:flightsearch:8020 - registration failed Cannot execute request on any known server
WARN 1 --- [nfoReplicator-0] c.n.discovery.InstanceInfoReplicator     : There was a problem with the instance info replicator

I am doing it in an AWS EC2 Ubuntu instance.
Can anyone please tell me what I am doing wrong here?


问:
Why am I getting an error "TypeError: system() takes at most 1 argument (3 given)"
I'm trying to make a script that takes information and stores it in a file for a different program

My code is this,

```<code>import os

currentinfo = input("Enter username: ")

os.system('echo', "Username:", currentinfo, ">> info.txt")

</code>```

The error I'm getting is,

```<code>os.system('echo', "Username:", currentinfo)
TypeError: system() takes at most 1 argument (3 given)
</code>```

How do I fix this?

I'm new to python, so bear with me.

答:
The error is pretty straightforward - you are invoking the system method of the os package with 3 arguments. Checking the api confirms this takes 1 argument, not 3. So, one way to solve this would be to combine all your terms into 1 string argument. You probably also need quotes around what you are passing to echo:

```<code>os.system(f'echo "Username: {currentinfo}" >> info.txt')
</code>```

As at least 1 comment suggested, it would be more pythonic to use code to write to a file, rather than relying on a system call. As you are using >> I'll assume you want to append to the file, rather than overwriting it if it already exists:

```<code>currentinfo = input("Enter username: ")
text_to_write = f'Username: {currentinfo}'
with open('info.txt', 'a') as outfile:  # the 'a' sets append mode
    outfile.write(text_to_write)        # <-- optionally add a \n if you want a newline
</code>```

Hope that helps, happy coding!

Body:
I'm trying to make a script that takes information and stores it in a file for a different program

My code is this,

import os

currentinfo = input("Enter username: ")

os.system('echo', "Username:", currentinfo, ">> info.txt")

The error I'm getting is,

os.system('echo', "Username:", currentinfo)
TypeError: system() takes at most 1 argument (3 given)

How do I fix this?

I'm new to python, so bear with me.

Body:
The error is pretty straightforward - you are invoking the system method of the os package with 3 arguments. Checking the api confirms this takes 1 argument, not 3. So, one way to solve this would be to combine all your terms into 1 string argument. You probably also need quotes around what you are passing to echo:

os.system(f'echo "Username: {currentinfo}" >> info.txt')

As at least 1 comment suggested, it would be more pythonic to use code to write to a file, rather than relying on a system call. As you are using >> I'll assume you want to append to the file, rather than overwriting it if it already exists:

currentinfo = input("Enter username: ")
text_to_write = f'Username: {currentinfo}'
with open('info.txt', 'a') as outfile:  # the 'a' sets append mode
    outfile.write(text_to_write)        # <-- optionally add a \n if you want a newline

Hope that helps, happy coding!


问:
Stop Python script with ctrl + c
I have a script which uses threads, but it is unable to catch Ctrl + C.

Here it is the sample code to reproduce this error:

```<code>import threading
import time
import signal

class DummyThread(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)
        self._running = True
        signal.signal(signal.SIGINT, self.stop)
        signal.signal(signal.SIGTERM, self.stop)

    def stop(self, signum=None, frame=None):
        self._running = False

    def run(self):
        while self._running:
            time.sleep(1)
            print("Running")

if __name__ == "__main__":
    try:
        t = DummyThread()
        t.start()
        while True:
            print("Main thread running")
            time.sleep(0.5)
    except KeyboardInterrupt:
        print("This never gets printed")
        t.stop()
    finally:
        print("Exit")
</code>```

When I run python3 script.py it starts running, but it does not catch ctrl+c. I have googled it but I have not found a solution. I have to kill the script with SIGTERM, but I want DummyThread to stop gracefully.

答:
As shown in your code, you used KeyboardInterrupt to call stop() function. See how Listener does the same task and stops the execution which was unable to catch from Ctrl + C. You dont have to  kill the script with SIGTERM anymore

```<code>import threading
import time
import signal
import os
from pynput.keyboard import Key, Listener

class DummyThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self._running = True
        signal.signal(signal.SIGINT, self.stop)
        signal.signal(signal.SIGTERM, self.stop)

    def stop(self, signum=None, frame=None):
        self._running = False
        print ("Bye Bye . .")
        os._exit(1)

    def run(self):
        while self._running:
            time.sleep(1)
            print("Running")

if __name__ == "__main__":
    t = DummyThread()
    def func2():
        try:
            t.start()
            while True:
                print("Main thread running")
                time.sleep(0.5)
        except KeyboardInterrupt:
            print("No need for this")
            t.stop()
        finally:
            print("Exit")

    def func1():
        with Listener(on_press = t.stop) as listener :
            listener.join()

    threading.Thread(target=func1).start()
    threading.Thread(target=func2).start()
</code>```

Title: Stop Python script with ctrl + c

Body:
I have a script which uses threads, but it is unable to catch Ctrl + C.

Here it is the sample code to reproduce this error:

import threading
import time
import signal

class DummyThread(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)
        self._running = True
        signal.signal(signal.SIGINT, self.stop)
        signal.signal(signal.SIGTERM, self.stop)

    def stop(self, signum=None, frame=None):
        self._running = False

    def run(self):
        while self._running:
            time.sleep(1)
            print("Running")

if __name__ == "__main__":
    try:
        t = DummyThread()
        t.start()
        while True:
            print("Main thread running")
            time.sleep(0.5)
    except KeyboardInterrupt:
        print("This never gets printed")
        t.stop()
    finally:
        print("Exit")

When I run python3 script.py it starts running, but it does not catch ctrl+c. I have googled it but I have not found a solution. I have to kill the script with SIGTERM, but I want DummyThread to stop gracefully.

Body:
As shown in your code, you used KeyboardInterrupt to call stop() function. See how Listener does the same task and stops the execution which was unable to catch from Ctrl + C. You dont have to  kill the script with SIGTERM anymore

import threading
import time
import signal
import os
from pynput.keyboard import Key, Listener

class DummyThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self._running = True
        signal.signal(signal.SIGINT, self.stop)
        signal.signal(signal.SIGTERM, self.stop)

    def stop(self, signum=None, frame=None):
        self._running = False
        print ("Bye Bye . .")
        os._exit(1)

    def run(self):
        while self._running:
            time.sleep(1)
            print("Running")

if __name__ == "__main__":
    t = DummyThread()
    def func2():
        try:
            t.start()
            while True:
                print("Main thread running")
                time.sleep(0.5)
        except KeyboardInterrupt:
            print("No need for this")
            t.stop()
        finally:
            print("Exit")

    def func1():
        with Listener(on_press = t.stop) as listener :
            listener.join()

    threading.Thread(target=func1).start()
    threading.Thread(target=func2).start()


问:
How to export data to csv sequentially from multiple data frames in a sequential order
I have multiple dataframes like below.

DF1:

DF2

DF3

I want to store them to a file like below.So the data should be in sequential order from each dataframe. Can any one help me to find a way to store in the below format in a file.

答:
Use df.append:

```<code>df = DF1.append(DF2).append(DF3)
</code>```

Then write it to a file using df.to_csv() file:

```<code>df.to_csv('test.csv')
</code>```

OR to an excel file using df.to_excel():

```<code>df.to_excel('test.xls')
</code>```

OR (as per @anky 's comment): use pd.concat

```<code>df_list = [DF1,DF2,DF3] ## create a list with your dataframes
df = pd.concat(df_list)

df.to_csv('test.csv')
</code>```

Body:
Use df.append:

df = DF1.append(DF2).append(DF3)

Then write it to a file using df.to_csv() file:

df.to_csv('test.csv')

OR to an excel file using df.to_excel():

df.to_excel('test.xls')

OR (as per @anky 's comment): use pd.concat

df_list = [DF1,DF2,DF3] ## create a list with your dataframes
df = pd.concat(df_list)

df.to_csv('test.csv')


问:
String's content retrieved from file disappears during concatenation or equality check
I am making a program that will have to read/write plain text files. I read the text from a file and then process it to separate the string into several components (namely lines and then variable/value). When I try processing some of these components, the content of the string appears to change or disappear temporarily. This code reproduces the problem:

```<code>package spriteModder;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class ErrorThing {
    public static void main(String[] args) throws IOException {
        loadFile(new File("settings.config"));
    }
    public static void loadFile(File f) throws IOException {
        FileInputStream fis=new FileInputStream(f);
        int numread=1;
        StringBuilder contentBuilder= new StringBuilder();
        byte[] buffer=new byte[8];
        while(numread>0) {
            numread=fis.read(buffer);
            if(numread==-1){break;}
            contentBuilder.append(new String(buffer, 0, numread));
        }
        String source=contentBuilder.toString();
        System.out.println(source);
        String[] lines=source.split("\n");
        for(String s:lines){
            System.out.println(s);
            String[] a=s.split("=");
            for(String s2:a){
                System.out.println(s2);

                System.out.println(s2+"4");
                System.out.println(s2.equals("true"));
            }

        }
    }
}

</code>```

This is the output:

```<code> //these three lines are to verify the contents of the settings.config file, which works as expected
outputDir=*here
lookInSubDirectories=true
inputDir=*here
outputDir=*here //the first line of the file
outputDir //the first component of the line
outputDir4 //the first component of the line after concatenation.
false //checks if the component (w/o concatenation) is equal to "true"
*here //second component of the line
4 //second component of the line after concatenation, which is missing the entire original component
false //checks if the second component of the line is equal to "true"
lookInSubDirectories=true
lookInSubDirectories //the first component of the second line
lookInSubDirectories4
false
true // the second component
4 //this component also disappears during concatenation
false // but also fails the equality check, even though the content is "true"
inputDir=*here
inputDir
inputDir4
false
*here
*here4 //you can see concatenation working on the third line's second component here for some reason
false
</code>```

the content of settings.config is:

```<code>outputDir=*here
lookInSubDirectories=true
inputDir=*here
</code>```

I've tried changing the size of the byte buffer, using a FileReader instead of a FileInputStream, and using temporary variables with no success. I also circumvented reading the file and just hardcoded the same contents into a string, which prevented the problem. However, reading the contents from a file is a necessity. Concatenation always works when only an empty string ("") is concatenated, but anything else will cause the original contents to disappear in those two lines. The equality check fails regardless of whether .equals or == is used. Using substring() instead of split() to produce the components has no effect. What is going on? Why would concatenation cause the original string to disappear in the result, but only sometimes? Why won't the equality check work?

答:
Okay, so nothing disapopears here, and your program works correctly, even if written in unnecessarily cumbersome way. It's easiest to check that just by leaving this line:

```<code> System.out.println(s2);
</code>```

as the only output on your split String iteration. The only error is in conclusion that something 'disappears'. I'm going to take a wild guess and say you run this code on Windows, or otherwise have your settings.config file's line breaks as \r\n instead of just \n. So, splitting on just \n leaves the hanging \rs, so you have:

```<code>"*here\r" + "4"
</code>```

and this gets printed as

```<code>*here
4
</code>```

Best to check that hanging \rs using a debugger or an if statement.

So, your program works as much as splitting abc=123 to "abc" and "123" is concerned (or, rather to "abc" and "123\r"). But do consider using Java's built-in method for loading Properties from a file, or at the very least usea BufferedReader, I think it's readLine method will consume both carriage return and line feed characters.

Body:
I am making a program that will have to read/write plain text files. I read the text from a file and then process it to separate the string into several components (namely lines and then variable/value). When I try processing some of these components, the content of the string appears to change or disappear temporarily. This code reproduces the problem:

package spriteModder;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class ErrorThing {
    public static void main(String[] args) throws IOException {
        loadFile(new File("settings.config"));
    }
    public static void loadFile(File f) throws IOException {
        FileInputStream fis=new FileInputStream(f);
        int numread=1;
        StringBuilder contentBuilder= new StringBuilder();
        byte[] buffer=new byte[8];
        while(numread>0) {
            numread=fis.read(buffer);
            if(numread==-1){break;}
            contentBuilder.append(new String(buffer, 0, numread));
        }
        String source=contentBuilder.toString();
        System.out.println(source);
        String[] lines=source.split("\n");
        for(String s:lines){
            System.out.println(s);
            String[] a=s.split("=");
            for(String s2:a){
                System.out.println(s2);

                System.out.println(s2+"4");
                System.out.println(s2.equals("true"));
            }

        }
    }
}

This is the output:

 //these three lines are to verify the contents of the settings.config file, which works as expected
outputDir=*here
lookInSubDirectories=true
inputDir=*here
outputDir=*here //the first line of the file
outputDir //the first component of the line
outputDir4 //the first component of the line after concatenation.
false //checks if the component (w/o concatenation) is equal to "true"
*here //second component of the line
4 //second component of the line after concatenation, which is missing the entire original component
false //checks if the second component of the line is equal to "true"
lookInSubDirectories=true
lookInSubDirectories //the first component of the second line
lookInSubDirectories4
false
true // the second component
4 //this component also disappears during concatenation
false // but also fails the equality check, even though the content is "true"
inputDir=*here
inputDir
inputDir4
false
*here
*here4 //you can see concatenation working on the third line's second component here for some reason
false

the content of settings.config is:

outputDir=*here
lookInSubDirectories=true
inputDir=*here

I've tried changing the size of the byte buffer, using a FileReader instead of a FileInputStream, and using temporary variables with no success. I also circumvented reading the file and just hardcoded the same contents into a string, which prevented the problem. However, reading the contents from a file is a necessity. Concatenation always works when only an empty string ("") is concatenated, but anything else will cause the original contents to disappear in those two lines. The equality check fails regardless of whether .equals or == is used. Using substring() instead of split() to produce the components has no effect. What is going on? Why would concatenation cause the original string to disappear in the result, but only sometimes? Why won't the equality check work?

Body:
Okay, so nothing disapopears here, and your program works correctly, even if written in unnecessarily cumbersome way. It's easiest to check that just by leaving this line:

 System.out.println(s2);

as the only output on your split String iteration. The only error is in conclusion that something 'disappears'. I'm going to take a wild guess and say you run this code on Windows, or otherwise have your settings.config file's line breaks as \r\n instead of just \n. So, splitting on just \n leaves the hanging \rs, so you have:

"*here\r" + "4"

and this gets printed as

*here
4

Best to check that hanging \rs using a debugger or an if statement.

So, your program works as much as splitting abc=123 to "abc" and "123" is concerned (or, rather to "abc" and "123\r"). But do consider using Java's built-in method for loading Properties from a file, or at the very least usea BufferedReader, I think it's readLine method will consume both carriage return and line feed characters.


问:
Javascript use single await in ternary operator
I have a situation I want to use await in a ternary operator. I want to set a value to either a literal value or the resolve value of a promise, depending on a condition. Hopefully the code below will help describe what I want to do, but I am pretty sure it is not correct so consider it pseudo code.

```<code>const val = checkCondition ? "literal value" : await promiseGetValue();
</code>```

Where promiseGetValue() returns a promise which resolves to a literal value. What is the correct way to do this?

答:
This is actually a valid syntax, just for clarity u can surround the await promiseGetValue() with brackets. here is a demo of this syntax.

const returnPromise = () => Promise.resolve('world')
const f = async () => {
   const x = true ? 'hello' : await returnPromise()
    const y = false ? 'hello' : await returnPromise()
    console.log(x,y)

}
f()```

Body:
I have a situation I want to use await in a ternary operator. I want to set a value to either a literal value or the resolve value of a promise, depending on a condition. Hopefully the code below will help describe what I want to do, but I am pretty sure it is not correct so consider it pseudo code.

const val = checkCondition ? "literal value" : await promiseGetValue();

Where promiseGetValue() returns a promise which resolves to a literal value. What is the correct way to do this?


问:
gitignore filter - how to add a remote configuration?
I would like to add a gitignore filter for a specific lines of the code. Here is the solution.
It requires calling appropriate git config command. When some other user clones that repo the filtering doesn't work unless git configcommand is called. I need a solution where after cloning a repository filtering works without any additional actions. How to solve that problem ?

答:
You need git hooks. Git hooks are scripts that Git executes before or after events.

The post-checkout hook also runs on git-clone (when run without --no-checkout).

It is also run after git-clone, unless the --no-checkout (-n) option is used. The first parameter given to the hook is the null-ref, the second the ref of the new HEAD and the flag is always 1.

hooks-documentation


问:
Replacing multiple character instances from a string in Javascript
So I have this piece of code:

```<code>var thisValue = $("input[id*=ID222]").val();
thisValue = thisValue.replace(',','');
</code>```

Basically I want to remove all commas in this input element for taking it up for further processing. The above code works when there is only one comma in the field, but doesn't work for multiple commas. Is there another way? I tried replaceAll, and it didn't work.

答:
You have to do a global replace using a regular expression. You can't do this by passing a string to replace:

```<code>thisValue = thisValue.replace(/,/g,'');
</code>```

Body:
So I have this piece of code:

var thisValue = $("input[id*=ID222]").val();
thisValue = thisValue.replace(',','');

Basically I want to remove all commas in this input element for taking it up for further processing. The above code works when there is only one comma in the field, but doesn't work for multiple commas. Is there another way? I tried replaceAll, and it didn't work.

Body:
You have to do a global replace using a regular expression. You can't do this by passing a string to replace:

thisValue = thisValue.replace(/,/g,'');