问:
Saving DrawingVisual to an image file with a given DPI
I have got a WPF application, and I would like to save a Canvas to a file with a correct DPI value. The Canvas size is the real physical size, eg. 20x10 cm, at 300 DPI, so it's 2362x1181.

I draw images and shapes with DrawingVisual, then I create a RenderTargetBitmap. The size of the rtb is the size of the Canvas. The dpiX and dpiY are 96. I got correct image resolution only with 96 DPI. When I set it to 300, the canvas become upscale, and cropped to 2362x1181. So, it's not good. I tried to modify the canvas width and height value by dpi factor, but didn't work either.

After the RenderTargetBitmap, I use BitmapEncoder, BitmapFrame, and BinaryWriter. See code below. Working great, but the image DPI value will be 96. I've read a tons of topics about reading DPI, resaving image, using SetResolution, but I don't want to loose quality, I don't want to read file and resave it, I don't want to change pixel width/height, etc.

I just really want to save a DrawingVisual with a given DPI. I could write EXIF data for "X Resolution" (uint=282) and "Y Resoulution" (uint=283), but that didn't affect the Image DPI settings, so eg. Photoshop will read 96, not 300.

```<code>BitmapEncoder encoder = new JpegBitmapEncoder();
BitmapFrame bFrame = BitmapFrame.Create(rtb, null, meta, icc);
encoder.Frames.Add(bFrame);

using (var stream = new MemoryStream())
{
encoder.Save(stream);
byte[] imageData = stream.ToArray();
using (FileStream fs = new FileStream(path, ...)
{
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(imageData);
bw.Close();
}
}
</code>```

答:
The following method saves a UIElement to a JPEG file with the specified DPI value:

```<code>public static void SaveElement(UIElement element, double dpi, string path)
{
    var visual = new DrawingVisual();
    var width = element.RenderSize.Width;
    var height = element.RenderSize.Height;

    using (var context = visual.RenderOpen())
    {
        context.DrawRectangle(new VisualBrush(element), null,
            new Rect(0, 0, width, height));
    }

    var bitmap = new RenderTargetBitmap(
        (int)(width * dpi / 96), (int)(height * dpi / 96),
        dpi, dpi, PixelFormats.Default);
    bitmap.Render(visual);

    var encocer = new JpegBitmapEncoder();
    encocer.Frames.Add(BitmapFrame.Create(bitmap));

    using (var stream = File.OpenWrite(path))
    {
        encocer.Save(stream);
    }
}
</code>```

Alternatively, apply the DPI scaling to the DrawingVisual:

```<code>public static void SaveElement(UIElement element, double dpi, string path)
{
    var visual = new DrawingVisual();
    var width = element.RenderSize.Width;
    var height = element.RenderSize.Height;

    using (var context = visual.RenderOpen())
    {
        context.DrawRectangle(new VisualBrush(element), null,
            new Rect(0, 0, width / dpi * 96, height / dpi * 96));
    }

    var bitmap = new RenderTargetBitmap(
        (int)width, (int)height, dpi, dpi, PixelFormats.Default);
    bitmap.Render(visual);

    var encocer = new JpegBitmapEncoder();
    encocer.Frames.Add(BitmapFrame.Create(bitmap));

    using (var stream = File.OpenWrite(path))
    {
        encocer.Save(stream);
    }
}
</code>```

Body:
I have got a WPF application, and I would like to save a Canvas to a file with a correct DPI value. The Canvas size is the real physical size, eg. 20x10 cm, at 300 DPI, so it's 2362x1181.

I draw images and shapes with DrawingVisual, then I create a RenderTargetBitmap. The size of the rtb is the size of the Canvas. The dpiX and dpiY are 96. I got correct image resolution only with 96 DPI. When I set it to 300, the canvas become upscale, and cropped to 2362x1181. So, it's not good. I tried to modify the canvas width and height value by dpi factor, but didn't work either.

After the RenderTargetBitmap, I use BitmapEncoder, BitmapFrame, and BinaryWriter. See code below. Working great, but the image DPI value will be 96. I've read a tons of topics about reading DPI, resaving image, using SetResolution, but I don't want to loose quality, I don't want to read file and resave it, I don't want to change pixel width/height, etc.

I just really want to save a DrawingVisual with a given DPI. I could write EXIF data for "X Resolution" (uint=282) and "Y Resoulution" (uint=283), but that didn't affect the Image DPI settings, so eg. Photoshop will read 96, not 300.

BitmapEncoder encoder = new JpegBitmapEncoder();
BitmapFrame bFrame = BitmapFrame.Create(rtb, null, meta, icc);
encoder.Frames.Add(bFrame);

using (var stream = new MemoryStream())
{
encoder.Save(stream);
byte[] imageData = stream.ToArray();
using (FileStream fs = new FileStream(path, ...)
{
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(imageData);
bw.Close();
}
}

Body:
The following method saves a UIElement to a JPEG file with the specified DPI value:

public static void SaveElement(UIElement element, double dpi, string path)
{
    var visual = new DrawingVisual();
    var width = element.RenderSize.Width;
    var height = element.RenderSize.Height;

    using (var context = visual.RenderOpen())
    {
        context.DrawRectangle(new VisualBrush(element), null,
            new Rect(0, 0, width, height));
    }

    var bitmap = new RenderTargetBitmap(
        (int)(width * dpi / 96), (int)(height * dpi / 96),
        dpi, dpi, PixelFormats.Default);
    bitmap.Render(visual);

    var encocer = new JpegBitmapEncoder();
    encocer.Frames.Add(BitmapFrame.Create(bitmap));

    using (var stream = File.OpenWrite(path))
    {
        encocer.Save(stream);
    }
}

Alternatively, apply the DPI scaling to the DrawingVisual:

public static void SaveElement(UIElement element, double dpi, string path)
{
    var visual = new DrawingVisual();
    var width = element.RenderSize.Width;
    var height = element.RenderSize.Height;

    using (var context = visual.RenderOpen())
    {
        context.DrawRectangle(new VisualBrush(element), null,
            new Rect(0, 0, width / dpi * 96, height / dpi * 96));
    }

    var bitmap = new RenderTargetBitmap(
        (int)width, (int)height, dpi, dpi, PixelFormats.Default);
    bitmap.Render(visual);

    var encocer = new JpegBitmapEncoder();
    encocer.Frames.Add(BitmapFrame.Create(bitmap));

    using (var stream = File.OpenWrite(path))
    {
        encocer.Save(stream);
    }
}


来源: stackexchange

问:
Converting a mySQL table with id's to a MongoDB table with _id's
I'm transferring a MySQL table to MongoDB. There is a primary key id in my MySQL table and I want this id to be converted to the _id in MongoDB.

I use php's MongoCollection::insert( $mysql_array );

However it doesn't work because if I set $mysql_array['_id'] it is seen by mongo as a String instead of a MongoId. I tried $mysql_array['_id'] = new MongoId( $id ) but it doesn't allow me to override the default _id value. I saw that all my MySQL's integer columns are converted to string by MongoCollection::insert(). If I could set MongoCollection::insert() to correctly transfer an integer it would maybe work.

答:
You won't be able to convert an arbitrary String value into an Mongo ObjectId due to its specific characteristics (12 bytes -> 24 chars generated from 4 bytes timestamp, 3 bytes client hostname, 2 bytes PID, 3 bytes inc value).

Either you abandon using the MongoId type in your collection's _id-fields and use your MySQL-ID as a string instead (which is not a problem and makes the most sense) or you let Mongo to generate the documents' _id for you, which is also a suitable solution if you want to be able to use the MongoId functions (assuming you're working with PHP):
The MongoId class

Choosing the second solution you still are able to store your MySQL-IDs in another field of the doc, like id or *mysql_id* to reference them later.

Concerning your question about (int) and (string) values: Are you sure they come as a PHP integer from your MySQL DB? If so, they usually should be stored as integers in Mongo. Check it with a var_dump() and in case of incompatibility cast it with an (int). Maybe it would be helpful if you post your select/insert code...

ContentLicense: CC BY-SA 3.0


问:
Match capture group to given pattern in pandas column
I have a DataFrame 'tdf' with a column "Cars" where the values are 4 letters and then 1-6 numbers.

```<code>Cars
JAXT450678
KYXS 56746
LMOP01456
...
</code>```

I have compiled the regex to match it:

 r'(?=[a-zA-Z]{4}\s*\d{1,6}\b)([a-zA-Z]{4})(\s?\d+)'

What I want to do is strip the whitespace out and then make sure that if there are less than 6 digits in the second group, insert 0's starting at the second group until a count of 6 is reached, such that the result is:

```<code>Cars
JAXT450678
KYXS056746
LMOP001456
...
</code>```

Any help is appreciated. I have tried playing around with .replace and .sub and can get it to replace the entire match, but I don't know how to reference the group and have it dynamically match.

tdf = tdf.replace(r'(?=[a-zA-Z]{4}\s*\d{1,6}\b)([a-zA-Z]{4})(\s?\d+)','000000', regex = True)

答:
You may use

```<code>df['Cars'] = df['Cars'].str.replace(r'^([a-zA-Z]{4})\s*(\d{1,6})$', lambda x: "{}{}".format(x.group(1), x.group(2).zfill(6)))
</code>```

Details

^ - matches the start of a string

([a-zA-Z]{4}) - Group 1: four letters

\s* - 0+ whitespaces

(\d{1,6}) - Group 2: 1 to 6 digits

$ - end of string.

The lambda x: "{}{}".format(x.group(1), x.group(2).zfill(6)) callable concats Group 1 value and Group 2 value that is padded with zeros up to 6 positions.

Since \s* is out of parentheses, the whitespaces matched with this pattern are omitted from the result.

ContentLicense: CC BY-SA 4.0

Body:
I have a DataFrame 'tdf' with a column "Cars" where the values are 4 letters and then 1-6 numbers.

Cars
JAXT450678
KYXS 56746
LMOP01456
...

I have compiled the regex to match it:

 r'(?=[a-zA-Z]{4}\s*\d{1,6}\b)([a-zA-Z]{4})(\s?\d+)'

What I want to do is strip the whitespace out and then make sure that if there are less than 6 digits in the second group, insert 0's starting at the second group until a count of 6 is reached, such that the result is:

Cars
JAXT450678
KYXS056746
LMOP001456
...

Any help is appreciated. I have tried playing around with .replace and .sub and can get it to replace the entire match, but I don't know how to reference the group and have it dynamically match.

tdf = tdf.replace(r'(?=[a-zA-Z]{4}\s*\d{1,6}\b)([a-zA-Z]{4})(\s?\d+)','000000', regex = True)

Body:
You may use

df['Cars'] = df['Cars'].str.replace(r'^([a-zA-Z]{4})\s*(\d{1,6})$', lambda x: "{}{}".format(x.group(1), x.group(2).zfill(6)))

Details

^ - matches the start of a string

([a-zA-Z]{4}) - Group 1: four letters

\s* - 0+ whitespaces

(\d{1,6}) - Group 2: 1 to 6 digits

$ - end of string.

The lambda x: "{}{}".format(x.group(1), x.group(2).zfill(6)) callable concats Group 1 value and Group 2 value that is padded with zeros up to 6 positions.

Since \s* is out of parentheses, the whitespaces matched with this pattern are omitted from the result.


答:
Use replace to replace white space and zfill to fill number part of the string,</p>

```<code>df['Cars'].str.replace(' ', '').apply(lambda x: x[:4] + x[4:].zfill(6))

0    JAXT450678
1    KYXS056746
2    LMOP001456
</code>```

Title: Match capture group to given pattern in pandas column

Body:
Use replace to replace white space and zfill to fill number part of the string,

df['Cars'].str.replace(' ', '').apply(lambda x: x[:4] + x[4:].zfill(6))

0    JAXT450678
1    KYXS056746
2    LMOP001456


问:
How to compute P values for increasing sample size using a loop?
I am having trouble creating a for loop.
I want to increase my sample size from 1 to 200 and calculate a p value after each newly added observation.
So that first I sample 1 observation - calculate first p value, then sample 2 observations - calculate second p value, then 3... up to 200 observations so that I get 200 p-values.

The observations will all be sampled from one column of a data frame (with replacing).

Lets say the column of the data frame is called data$column1.
The sample size increases by one in each "round" from 1:200.

How do I create a for loop so that for each "round", one more observation is being sampled and a new p value is being computed?
Finally I want to plot all p values.

```<code>n <- 1:200

for i in length(n) {
sample(data$column1,n, replace = TRUE)
pvalue <- t.test(data$column1, alternative = "greater")
}
</code>```

答:
@r2evans has a great answer. I'll just focus on your code and trying to get it to plot.

Improvements include:

for syntax is for (i in seq_along(n)) to loop through each i. In your case, you actually want to do for (i in 2:200) because i==1 will not be able to compute a p.value.

The sample of your data needs to be assigned to a variable. As is, nothing happens. Alternatively, you can directly put the sample statement in the t.test() call.

You want to save the result of each loop into pvalue. If it worked as is, pvalue would end up with the last value of your loop.

I like the apply series because you don't have to pre-allocate anything explicitly.

```<code>set.seed(1)
n <- 50
results <- sapply(seq(2, n)
                  , function(n) {
                   t.test(sample(iris$Sepal.Length, n, replace = T), mu = 5.5, alternative = 'greater')$p.value
                  })

plot(y = results, x = seq(2, n))
</code>```

In theory, all you would need to do is replace iris$Sepal.Length with data$column1 and use whatever n you prefer.

Body:
I am having trouble creating a for loop.
I want to increase my sample size from 1 to 200 and calculate a p value after each newly added observation.
So that first I sample 1 observation - calculate first p value, then sample 2 observations - calculate second p value, then 3... up to 200 observations so that I get 200 p-values.

The observations will all be sampled from one column of a data frame (with replacing).

Lets say the column of the data frame is called data$column1.
The sample size increases by one in each "round" from 1:200.

How do I create a for loop so that for each "round", one more observation is being sampled and a new p value is being computed?
Finally I want to plot all p values.

n <- 1:200

for i in length(n) {
sample(data$column1,n, replace = TRUE)
pvalue <- t.test(data$column1, alternative = "greater")
}

Body:
@r2evans has a great answer. I'll just focus on your code and trying to get it to plot.

Improvements include:

for syntax is for (i in seq_along(n)) to loop through each i. In your case, you actually want to do for (i in 2:200) because i==1 will not be able to compute a p.value.

The sample of your data needs to be assigned to a variable. As is, nothing happens. Alternatively, you can directly put the sample statement in the t.test() call.

You want to save the result of each loop into pvalue. If it worked as is, pvalue would end up with the last value of your loop.

I like the apply series because you don't have to pre-allocate anything explicitly.

set.seed(1)
n <- 50
results <- sapply(seq(2, n)
                  , function(n) {
                   t.test(sample(iris$Sepal.Length, n, replace = T), mu = 5.5, alternative = 'greater')$p.value
                  })

plot(y = results, x = seq(2, n))

In theory, all you would need to do is replace iris$Sepal.Length with data$column1 and use whatever n you prefer.


问:
Second root module in IntelliJ's maven module view
I have a multimodule maven application with parent pom as follows:

```<code><groupId>com.test</groupId>
<artifactId>uke-management</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>uke-management</name>
<packaging>pom</packaging>

<modules>
    <module>application</module>
    <module>user-management</module>
    <module>security</module>
    <module>workflow</module>
    <module>commons</module>
    <module>database</module>
    <module>contract-management</module>
    <module>file-management</module>
    <module>communication-management</module>
</modules>
</code>```

now in intelliJ's maven module view i can see all modules however communication-management is displayed twice and i dont know why. From the structure of my application it seems like it shouldn't be visible as root but somehow is. Here is the communication-management's pom:

```<code><modelVersion>4.0.0</modelVersion>

<parent>
    <artifactId>uke-management</artifactId>
    <groupId>com.test</groupId>
    <version>0.0.1-SNAPSHOT</version>
</parent>

<artifactId>communication-management</artifactId>

<properties>
    <spring-boot-starter-mail>2.1.5.RELEASE</spring-boot-starter-mail>
</properties>

<build>
    // some build plugins
</build>

<dependencies>
    <!-- project dependencies -->
    <dependency>
        <groupId>com.test</groupId>
        <artifactId>user-managment</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.mapstruct</groupId>
        <artifactId>mapstruct</artifactId>
        <version>1.2.0.Final</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
        <version>${spring-boot-starter-mail}</version>
    </dependency>
</dependencies>
</code>```

and this is how i can see it in IntelliJ:

Why is communication-management displayed twice and why is it displayed as root?

i have already tried reimporting, cleaning etc.

答:
Turns out it was some IntelliJ issue, restarting PC solved it. I dont think it's reporoducable. I tried to create some sample project but issue did not occur.

The old "have you tried turning it off and on again" worked for me.

Body:
I have a multimodule maven application with parent pom as follows:

<groupId>com.test</groupId>
<artifactId>uke-management</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>uke-management</name>
<packaging>pom</packaging>

<modules>
    <module>application</module>
    <module>user-management</module>
    <module>security</module>
    <module>workflow</module>
    <module>commons</module>
    <module>database</module>
    <module>contract-management</module>
    <module>file-management</module>
    <module>communication-management</module>
</modules>

now in intelliJ's maven module view i can see all modules however communication-management is displayed twice and i dont know why. From the structure of my application it seems like it shouldn't be visible as root but somehow is. Here is the communication-management's pom:

<modelVersion>4.0.0</modelVersion>

<parent>
    <artifactId>uke-management</artifactId>
    <groupId>com.test</groupId>
    <version>0.0.1-SNAPSHOT</version>
</parent>

<artifactId>communication-management</artifactId>

<properties>
    <spring-boot-starter-mail>2.1.5.RELEASE</spring-boot-starter-mail>
</properties>

<build>
    // some build plugins
</build>

<dependencies>

    <dependency>
        <groupId>com.test</groupId>
        <artifactId>user-managment</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.mapstruct</groupId>
        <artifactId>mapstruct</artifactId>
        <version>1.2.0.Final</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
        <version>${spring-boot-starter-mail}</version>
    </dependency>
</dependencies>

and this is how i can see it in IntelliJ:

Why is communication-management displayed twice and why is it displayed as root?

i have already tried reimporting, cleaning etc.


答:
use jquery code that will work for hiding all other div when you click on current div

```<code>$('a').on('click', function(){
   var target = $(this).attr('vooglid');
   $("test"+target).show().siblings("div").hide();
});
</code>```

but you must change your ids for apply that code

Title: I want to hide all other div's when i click on one div

Body:
I am making a software were i need to hide all other div's when i click on another div. what happens now is that the div's just stack on top of each other. and the div only dissapears when i click the same div again.

i already tried some of the JavaScript and jQuery code on this platform but can't quite figure it out myself.

--- THIS IS THE SCRIPT IM USING TO SHOW AND HIDE THE DIV'S ---

--- THESE ARE MY CLICKABLE AREA'S WHERE THE USER CAN CLICK ON TO SHOW AND HIDE A DIV ---

        <map name="Map" id="Map">

     <area onclick="toggle_visibility('vooglid');" alt="" title="" href="#" shape="poly" coords=170,251,159,253,140,251,134,249,126,244,121,241,118,237,114,226,113,221,118,214,128,204,141,195,160,187,176,178,194,171,208,165,230,157,249,155,268,153,284,151,300,151,326,154,341,158,358,168,371,178,380,190,394,209,402,221,408,235,412,244,403,247,392,242,378,231,366,219,347,207,334,203,316,199,286,199,263,203,246,208,221,218" />
        <area onclick="toggle_visibility('vwimpers');" alt="" title="" href="#" shape="poly" coords="170,251,159,253,140,251,134,249,126,244,121,241,118,237,114,226,113,221,118,214,128,204,141,195,160,187,176,178,194,171,208,165,230,157,249,155,268,153,284,151,300,151,326,154,341,158,358,168,371,178,380,190,394,209,402,221,408,235,412,244,403,247,392,242,378,231,366,219,347,207,334,203,316,199,286,199,263,203,246,208,221,218" />
        <area onclick="toggle_visibility('vwenkbrauw');" alt="" title="" href="#" shape="poly" coords="43,157,62,120,84,103,114,85,132,75,151,65,191,47,204,38,232,31,268,31,298,31,317,31,339,33,365,42,390,47,408,51,429,59,445,61,467,69,484,74,501,85,504,127,498,141,494,146,471,136,446,123,432,119,412,113,396,108,376,100,362,96,354,93,334,90,321,90,308,89,295,87,271,83,260,81,232,75,218,74,207,73,192,73,181,76,150,95,122,109,102,118,78,138,62,149,54,158,49,163,47,167" />
        <area onclick="toggle_visibility('vooghoek');" alt="" title="" href="#" shape="poly" coords="388,275,396,270,401,270,407,266,408,263,411,258,420,263,425,269,428,273,432,278,435,280,434,282,434,285,422,284,414,279" />

    </map>

--- AND THESE ARE MY DIV'S CONTAINING THE INFORMATION IT HAS TO SHOW AND HIDE ---

 Symptoom ooglid

 Symptoom wimper

 Symptoom wenkbrauw

 Symptoom ooghoek

I want the result to be that when I click one of the areas above, the corresponding div shows and all other divs hide.

Body:
use jquery code that will work for hiding all other div when you click on current div

$('a').on('click', function(){
   var target = $(this).attr('vooglid');
   $("test"+target).show().siblings("div").hide();
});

but you must change your ids for apply that code


问:
Saving list data in python
I am wondering how I can save whatever I added to a list when I close a python file. For example, in this "my contact" program that I wrote below, if I add information about 'Jane Doe', what could I do so that next time I open up the same file, Jane Doe still exists.  </p>

```<code>def main():
    myBook = Book([{"name": 'John Doe', "phone": '123-456-7890', "address": '1000 Constitution Ave'}])
class Book:
    def __init__(self, peoples):
        self.peoples = peoples
        self.main_menu()
    def main_menu(self):
        print('Main Menu')
        print('1. Display Contact Names')
        print('2. Search For Contacts')
        print('3. Edit Contact')
        print('4. New Contact')
        print('5. Remove Contact')
        print('6. Exit')
        self.selection = input('Enter a # form the menu: ')
        if (self.selection == "1"):
            self.display_names()
        if (self.selection == "2"):
            self.search()
        if (self.selection == "3"):
            self.edit()
        if (self.selection == "4"):
            self.new()
        if (self.selection == "5"):
            self.delete()
        if (self.selection == "6"):
            self.end()
    def display_names(self):
        for people in self.peoples:
                print("Name: " + people["name"])
        self.main_menu()
    def search(self):
        searchname = input('What is the name of your contact: ')
        for index in range(len(self.peoples)):
            if (self.peoples[index]["name"] == searchname):
                print("Name: " + self.peoples[index]["name"])
                print("Address: " + self.peoples[index]["address"])
                print("Phone: " + self.peoples[index]["phone"])
        self.main_menu()
    def edit(self):
        searchname = input('What is the name of the contact that you want to edit: ')
        for index in range(len(self.peoples)):
            if (self.peoples[index]["name"] == searchname):
                self.peoples.pop(index)
                name = input('What is your name: ')
                address = input('What is your address: ')
                phone = input('What is your phone number: ')
                self.peoples.append({"name": name, "phone": phone, "address": address})
        self.main_menu()
    def new(self):
        name = input('What is your name: ')
        address = input('What is your address: ')
        phone = input('What is your phone number: ')
        self.peoples.append({"name": name, "phone": phone, "address": address})
        self.main_menu()
    def delete(self):
        searchname = input('What is the name of the contact that you want to delete: ')
        for index in reversed(range(len(self.peoples))):
            if (self.peoples[index]["name"] == searchname):
                self.peoples.pop(index)

            print(searchname, 'has been removed')
        self.main_menu()
    def end(self):
        print('Thank you for using the contact book, have a nice day')
        print('Copyright Carson147 2019©, All Rights Reserved')

main()
</code>```

答: Use a module from the Data Persistence section of the standard library, or save it as json, or as a csv file.</p>

Title: Saving list data in python

Body:
I am wondering how I can save whatever I added to a list when I close a python file. For example, in this "my contact" program that I wrote below, if I add information about 'Jane Doe', what could I do so that next time I open up the same file, Jane Doe still exists.

def main():
    myBook = Book([{"name": 'John Doe', "phone": '123-456-7890', "address": '1000 Constitution Ave'}])
class Book:
    def __init__(self, peoples):
        self.peoples = peoples
        self.main_menu()
    def main_menu(self):
        print('Main Menu')
        print('1. Display Contact Names')
        print('2. Search For Contacts')
        print('3. Edit Contact')
        print('4. New Contact')
        print('5. Remove Contact')
        print('6. Exit')
        self.selection = input('Enter a # form the menu: ')
        if (self.selection == "1"):
            self.display_names()
        if (self.selection == "2"):
            self.search()
        if (self.selection == "3"):
            self.edit()
        if (self.selection == "4"):
            self.new()
        if (self.selection == "5"):
            self.delete()
        if (self.selection == "6"):
            self.end()
    def display_names(self):
        for people in self.peoples:
                print("Name: " + people["name"])
        self.main_menu()
    def search(self):
        searchname = input('What is the name of your contact: ')
        for index in range(len(self.peoples)):
            if (self.peoples[index]["name"] == searchname):
                print("Name: " + self.peoples[index]["name"])
                print("Address: " + self.peoples[index]["address"])
                print("Phone: " + self.peoples[index]["phone"])
        self.main_menu()
    def edit(self):
        searchname = input('What is the name of the contact that you want to edit: ')
        for index in range(len(self.peoples)):
            if (self.peoples[index]["name"] == searchname):
                self.peoples.pop(index)
                name = input('What is your name: ')
                address = input('What is your address: ')
                phone = input('What is your phone number: ')
                self.peoples.append({"name": name, "phone": phone, "address": address})
        self.main_menu()
    def new(self):
        name = input('What is your name: ')
        address = input('What is your address: ')
        phone = input('What is your phone number: ')
        self.peoples.append({"name": name, "phone": phone, "address": address})
        self.main_menu()
    def delete(self):
        searchname = input('What is the name of the contact that you want to delete: ')
        for index in reversed(range(len(self.peoples))):
            if (self.peoples[index]["name"] == searchname):
                self.peoples.pop(index)

            print(searchname, 'has been removed')
        self.main_menu()
    def end(self):
        print('Thank you for using the contact book, have a nice day')
        print('Copyright Carson147 2019©, All Rights Reserved')

main()


问:
How to use some of bootstrap's mobile first classes
I am having trouble understanding bootstrap 4's mobile first behavior. I have always designed for desktops first and moved down from there.

Text centering is one such place where I don't know how to proceed.

For example, I want a paragraph to be centered on screens smaller than 768px.

So I looked up the documentation https://getbootstrap.com/docs/4.0/utilities/text/ and found out the class text-md-center and thought this is what I need. It centers text on medium width screens which are not larger than 768px.

However on using it did the opposite of what I thought - It centered the text for screen size larger than 768px.

I am assuming this is what is called 'mobile first'. Is this not mean for desktop first design? How do I center text only on smaller width devices?

答:
Apply 2 classes to your paragraph: text-center and text-md-left.

text-center means that the text is centred by default, then text-md-left means it is left-aligned on screens 768px wide and greater.


问:
The name is not activable on g_dbus_proxy_call_sync
On a GNOME Xorg session, to get the return value of method GetIdletime exposed on DBus, you can either use

```<code>$ dbus-send --print-reply --dest=org.gnome.Mutter.IdleMonitor /org/gnome/Mutter/IdleMonitor/Core org.gnome.Mutter.IdleMonitor.GetIdletime
</code>```

or

```<code>$ gdbus call --session --dest org.gnome.Mutter.IdleMonitor --object-path /org/gnome/Mutter/IdleMonitor/Core --method org.gnome.Mutter.IdleMonitor.GetIdletime
</code>```

I need to retrieve this value by using GDBus API, so I wrote the following code

```<code>/*
 * Compile with:
 *   gcc -Wall print_user_idle_time-gnome.c -o print_user_idle_time-gnome `pkg-config --libs gio-2.0 --cflags`
 */

#include <gio/gio.h>

static void
print_user_idle_time (GDBusProxy *proxy)
{
    guint64 user_idle_time;
    gchar *method = "GetIdletime";
    GError *error = NULL;
    GVariant *ret = NULL;

    ret = g_dbus_proxy_call_sync(proxy,
                                  method,
                                  NULL,
                                  G_DBUS_CALL_FLAGS_NONE, -1,
                                  NULL, &error);
    if (!ret) {
        g_dbus_error_strip_remote_error (error);
        g_print ("GetIdletime failed: %s\n", error->message);
        g_error_free (error);
        return;
    }

    user_idle_time = g_variant_get_uint64 (ret);
    g_print("%lu\n", user_idle_time);
    g_variant_unref (ret);
}

int
main (int argc, char *argv[])
{
    GDBusProxy *proxy = NULL;
    gchar *name = "org.gnome.Mutter.IdleMonitor";
    gchar *object_path = "/org/gnome/Mutter/IdleMonitor/Core";
    gchar *interface_name = "org.gnome.Mutter.IdleMonitor";
    /* Create a D-Bus proxy */
    proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SYSTEM,
                                           G_DBUS_PROXY_FLAGS_NONE,
                                           NULL,
                                           name,
                                           object_path,
                                           interface_name,
                                           NULL, NULL);
    g_assert (proxy != NULL);

    print_user_idle_time (proxy);

    g_object_unref (proxy);

    return 0;
}
</code>```

But when I run it I get error GetIdletime failed: The name is not activable. What is wrong? Thank you

答: org.gnome.Mutter.IdleMonitor is on the session bus, not the system bus; so you need to use G_BUS_TYPE_SESSION.

Body:
On a GNOME Xorg session, to get the return value of method GetIdletime exposed on DBus, you can either use

$ dbus-send --print-reply --dest=org.gnome.Mutter.IdleMonitor /org/gnome/Mutter/IdleMonitor/Core org.gnome.Mutter.IdleMonitor.GetIdletime

or

$ gdbus call --session --dest org.gnome.Mutter.IdleMonitor --object-path /org/gnome/Mutter/IdleMonitor/Core --method org.gnome.Mutter.IdleMonitor.GetIdletime

I need to retrieve this value by using GDBus API, so I wrote the following code

/*
 * Compile with:
 *   gcc -Wall print_user_idle_time-gnome.c -o print_user_idle_time-gnome `pkg-config --libs gio-2.0 --cflags`
 */

#include <gio/gio.h>

static void
print_user_idle_time (GDBusProxy *proxy)
{
    guint64 user_idle_time;
    gchar *method = "GetIdletime";
    GError *error = NULL;
    GVariant *ret = NULL;

    ret = g_dbus_proxy_call_sync(proxy,
                                  method,
                                  NULL,
                                  G_DBUS_CALL_FLAGS_NONE, -1,
                                  NULL, &error);
    if (!ret) {
        g_dbus_error_strip_remote_error (error);
        g_print ("GetIdletime failed: %s\n", error->message);
        g_error_free (error);
        return;
    }

    user_idle_time = g_variant_get_uint64 (ret);
    g_print("%lu\n", user_idle_time);
    g_variant_unref (ret);
}

int
main (int argc, char *argv[])
{
    GDBusProxy *proxy = NULL;
    gchar *name = "org.gnome.Mutter.IdleMonitor";
    gchar *object_path = "/org/gnome/Mutter/IdleMonitor/Core";
    gchar *interface_name = "org.gnome.Mutter.IdleMonitor";
    /* Create a D-Bus proxy */
    proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SYSTEM,
                                           G_DBUS_PROXY_FLAGS_NONE,
                                           NULL,
                                           name,
                                           object_path,
                                           interface_name,
                                           NULL, NULL);
    g_assert (proxy != NULL);

    print_user_idle_time (proxy);

    g_object_unref (proxy);

    return 0;
}

But when I run it I get error GetIdletime failed: The name is not activable. What is wrong? Thank you


问:
Private method returned as string
I'm developing a simple jquery plugin and im having a difficulties setting up the method structure. Could someone please enlighten me. I am using the plugin structure as described in the official Jquery Authoring documentation.

The problem I am having is when calling the private function _generateID, the function actually returns the function text ( function() { return this.. ) instead of 'hi'.

```<code>(function( $ ){

    var methods = {
        init : function( options ) {
            return this.each(function() {

            });
        },

        _generateID : function() {
            return this.each(function() {
                return 'hi';
            });
        },

        create : function( options ) {
            return this.each(function() {
                var settings = {
                    'id' : methods._generateID,
                };
                if ( options ) { $.extend( settings, options ); }
                $('<div>', {
                    id : settings.id,
                }).appendTo(this);
            });
        },

        destroy : function( id ) {
            return this.each(function(){
                $(window).unbind('#'+id);
                $('#'+id).remove();
            });
        }
    };

    $.fn.workzone = function( method ) {
        if ( methods[method] ) {
            return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.workzone' );
        }
    };

})( jQuery );
</code>```

答: you must call function with parentheses methods._generateID().

Title: Private method returned as string

Body:
I'm developing a simple jquery plugin and im having a difficulties setting up the method structure. Could someone please enlighten me. I am using the plugin structure as described in the official Jquery Authoring documentation.

The problem I am having is when calling the private function _generateID, the function actually returns the function text ( function() { return this.. ) instead of 'hi'.

(function( $ ){

    var methods = {
        init : function( options ) {
            return this.each(function() {

            });
        },

        _generateID : function() {
            return this.each(function() {
                return 'hi';
            });
        },

        create : function( options ) {
            return this.each(function() {
                var settings = {
                    'id' : methods._generateID,
                };
                if ( options ) { $.extend( settings, options ); }
                $('
', {
                    id : settings.id,
                }).appendTo(this);
            });
        },

        destroy : function( id ) {
            return this.each(function(){
                $(window).unbind('#'+id);
                $('#'+id).remove();
            });
        }
    };

    $.fn.workzone = function( method ) {
        if ( methods[method] ) {
            return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.workzone' );
        }
    };

})( jQuery );


问:
Method references to static methods or static methods which return lambdas
While developing I always have to rewrite the same lambda expression over and over again which is quite redundant and most of the cases the code formatting policy imposed by my company does not help. So I moved these common lambdas to a utility class as static methods and use them as method references. The best example I have is the Throwing merger used in conjunction with java.util.stream.Collectors.toMap(Function, Function, BinaryOperator, Supplier).
Always having to write (a,b) -> {throw new IllegalArgumentException("Some message");}; just because I want to use a custom map implementation is a lot of hassle.

//First Form

public static <E> E throwingMerger(E k1, E k2) {
    throw new IllegalArgumentException("Duplicate key " + k1 + " not allowed!");
  }

//Given a list of Car objects with proper getters
Map<String,Car> numberPlateToCar=cars.stream()//
   .collect(toMap(Car::getNumberPlate,identity(),StreamUtils::throwingMerger,LinkedHasMap::new))
```

<pre class="lang-java prettyprint-override"><code>//Second Form

  public static <E> BinaryOperator<E> throwingMerger() {
    return (k1, k2) -> {
      throw new IllegalArgumentException("Duplicate key " + k1 + " not allowed!");
    };
  }
Map<String,Car> numberPlateToCar=cars.stream()//
   .collect(toMap(Car::getNumberPlate,identity(),StreamUtils.throwingMerger(),LinkedHasMap::new))
</code>```

My questions are the following:

Which of the above is the correct approach and why?

Does either one of them offer a performance advantage or compromises performance?

答:
EDIT: Ignore my remarks about avoiding unnecessary allocations, see Holgers answer as to why.

There won't be a noticable performance difference between the two - the first variant is avoiding unnecessary allocations though. I would prefer the method reference as the function does not capture any value and thus does not need a lambda in this context. Compared to creating the IllegalArgumentException, which has to fill its stacktrace before being thrown(which is quite expensive), the performance difference is totally negligible.

Remember: this is more about readability and communicating what your code does than about performance. If you ever hit a performance wall because of this kind of code lambdas and streams just aren't the way to go as they are a pretty elaborate abstraction with many indirections.

Body:
While developing I always have to rewrite the same lambda expression over and over again which is quite redundant and most of the cases the code formatting policy imposed by my company does not help. So I moved these common lambdas to a utility class as static methods and use them as method references. The best example I have is the Throwing merger used in conjunction with java.util.stream.Collectors.toMap(Function, Function, BinaryOperator, Supplier).
Always having to write (a,b) -> {throw new IllegalArgumentException("Some message");}; just because I want to use a custom map implementation is a lot of hassle.

//First Form

public static <E> E throwingMerger(E k1, E k2) {
    throw new IllegalArgumentException("Duplicate key " + k1 + " not allowed!");
  }

//Given a list of Car objects with proper getters
Map<String,Car> numberPlateToCar=cars.stream()//
   .collect(toMap(Car::getNumberPlate,identity(),StreamUtils::throwingMerger,LinkedHasMap::new))

//Second Form

  public static <E> BinaryOperator<E> throwingMerger() {
    return (k1, k2) -> {
      throw new IllegalArgumentException("Duplicate key " + k1 + " not allowed!");
    };
  }
Map<String,Car> numberPlateToCar=cars.stream()//
   .collect(toMap(Car::getNumberPlate,identity(),StreamUtils.throwingMerger(),LinkedHasMap::new))

My questions are the following:

Which of the above is the correct approach and why?

Does either one of them offer a performance advantage or compromises performance?


问:
Style "splitting" at breakpoint, mediaqueries
I'm working on developing a style for a site and I'm using media queries as breakpoints. At the breakpoint, the page suddenly decides to listen to some style from the first interval, and some from the second. Please help.

I've tried changing the values of the viewports but this doesn't work. I hope this problem is obvious to someone with more experience than I, because I really don't know what to do.

```<code>@media (min-width: 500px) and (max-width: 768px) {

     (ex.) #randomDiv {
     background-color: blue;
     width: 100px;
     }
}

@media (min-width: 768px) and (max-width: 1023px) {

     (ex.) #randomDiv {
     background-color: red;
     width: 300px;
     }

}
</code>```

When the viewport hits 768px it decides to mix styles, p.e. the background color changes to red, but the width doesn't change. Does anyone know what I'm doing wrong? After 768px (769px <) everything works just fine, as well as before 768px. Please help.

答:
When using media queries to make your frontend code responsive, it is quite useful to think about the base or starting styles then use the queries to alter those styles in one direction only. What I mean is instead of using max-width and min-width in your queries, start with the non-query styling then override those rules with either min-width OR max-width but not both. This way the changes are seamless and you only need to think about the exact breakpoint location and which styles are being overridden.

In using this approach the order of the media queries in your stylesheet matter too. Notice the widest query goes first here, if I were using min-width instead it would go the other way around.

Try looking at this in "Full page" mode and change the size of your screen down from full width.

#randomDiv {
  color: white;
  margin: 0 auto;
  padding: 20px;

  /* only background-color & width will change */
  background-color: purple;
  width: 90%;
}
@media (max-width: 1023px) {
  #randomDiv {
     background-color: red;
     width: 300px;
  }
}
@media (max-width: 768px) {
  #randomDiv {
     background-color: blue;
     width: 100px;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="randomDiv">I am so random.</div></code>```

Body:
I'm working on developing a style for a site and I'm using media queries as breakpoints. At the breakpoint, the page suddenly decides to listen to some style from the first interval, and some from the second. Please help.

I've tried changing the values of the viewports but this doesn't work. I hope this problem is obvious to someone with more experience than I, because I really don't know what to do.

@media (min-width: 500px) and (max-width: 768px) {

     (ex.) #randomDiv {
     background-color: blue;
     width: 100px;
     }
}

@media (min-width: 768px) and (max-width: 1023px) {

     (ex.) #randomDiv {
     background-color: red;
     width: 300px;
     }

}

When the viewport hits 768px it decides to mix styles, p.e. the background color changes to red, but the width doesn't change. Does anyone know what I'm doing wrong? After 768px (769px <) everything works just fine, as well as before 768px. Please help.

Body:
When using media queries to make your frontend code responsive, it is quite useful to think about the base or starting styles then use the queries to alter those styles in one direction only. What I mean is instead of using max-width and min-width in your queries, start with the non-query styling then override those rules with either min-width OR max-width but not both. This way the changes are seamless and you only need to think about the exact breakpoint location and which styles are being overridden.

In using this approach the order of the media queries in your stylesheet matter too. Notice the widest query goes first here, if I were using min-width instead it would go the other way around.

Try looking at this in "Full page" mode and change the size of your screen down from full width.

#randomDiv {
  color: white;
  margin: 0 auto;
  padding: 20px;

  /* only background-color & width will change */
  background-color: purple;
  width: 90%;
}
@media (max-width: 1023px) {
  #randomDiv {
     background-color: red;
     width: 300px;
  }
}
@media (max-width: 768px) {
  #randomDiv {
     background-color: blue;
     width: 100px;
  }
}

<div id="randomDiv">I am so random.</div>


问:
Add Text file to assets folder after export apk file with C#
Just assume some persons's information exist in Asp.net developed application.
and also another application have been written to display the data of mentioned persons for android(by Eclipse).
How could make change in "APK" file after adding data for new Person by Asp to get the data of mentioned person from website.
How mentioned person ID could be placed as text file in assets folder while APK SIGN dont interfere it.

I want have personal apk for each person and personal apk created(or modified) by Asp website(This APK contain a text file with MyPersonId and it added to ASSETS folder with C#).

答:
I was trying to do the same, and i'm almost there.

Basically i used MIT AppInventor to create an APK for Android. On it, i created a TXT file in the assets folder. The MIT AppInventor compiled the code to create the APK file for distribution.

I than placed the APK in a folder, owned by an ASP.net page. The goal would be to open the APK file (as a Zip, currently using the ZipSharpLib), locate the "info.txt" on the assets folder, and replace it for another.

My problem so far is on the "re-pack" ou "re-compress" the copy of the file; android is not recognizing it as a valid APK.

So, up to the "decompress" the APK, run every entry, locating the one that is the asset to replace i'm good (just use ZipSharpLib, classes ZipFile and ZipEntry - they show you how on their site). But on the "compress" a new changed file, i'm failing.


答:
There is no way you can do that without any external modules, such as numpy or pickle. Using pickle, you can do this: (I am assuming you want to save the myBook variable)

import pickle
pickle.dump(myBook, open("foo.bar", "wb")) #where foo is name of file and bar is extension
#also wb is saving type, you can find documentation online
```

<p>To load:</p>

<pre class="lang-py prettyprint-override"><code>pickle.load(myBook, open("foo.bar", "rb"))
</code>```

EDIT:

I was wrong in my first statement. There is a way to save without importing a module. Here is how:

myBook.save(foo.bar) #foo is file name and bar is extention
```

<p>To load:</p>

<pre class="lang-py prettyprint-override"><code>myBook=open(foo.bar)
</code>```

Title: Saving list data in python

Body:
There is no way you can do that without any external modules, such as numpy or pickle. Using pickle, you can do this: (I am assuming you want to save the myBook variable)

import pickle
pickle.dump(myBook, open("foo.bar", "wb")) #where foo is name of file and bar is extension
#also wb is saving type, you can find documentation online

To load:

pickle.load(myBook, open("foo.bar", "rb"))

EDIT:

I was wrong in my first statement. There is a way to save without importing a module. Here is how:

myBook.save(foo.bar) #foo is file name and bar is extention

To load:

myBook=open(foo.bar)


问:
Parse xml and apply formating to text
I am storing some text in a XML file and want to display it in my application by applying the formating to the text in a RichTextBox or something similar (maybe it would be better to have it as a listbox too?)

it would be something like this

```<code><Text>
  <Normal> This is some <Bold> text </Bold> which i like to put somewhere </Normal>
  <Bold><Italic> But there is a problem </Italic></Bold>
  <Normal> I don't know how </Normal>
</Text>
</code>```

this text would look like this

This is some text which i like to put somewhere
But there is a problem
I don't know how

I have searched the net but didnt find any solution...

Edit: I forgot to say that I am developing a silverlight navigation application so i cant user flowdocuments:/

答:
You'd have to manually go through the XML nodes and define what should happen for each node.  There's many different ways to implement something like that, but I'd start by keeping it simple.

For example: (pseudocode)

```<code>Foreach XMLnode node in xmlnodes
{
    if (node.attribute == "bold")
    {
        // apply bold to node text
    }
}
</code>```

You can do it like this, which is fairly simple.  I'm sure there is many ways to improve upon it and it can get fairly complicated I'm sure.

Title: Parse xml and apply formating to text

Body:
I am storing some text in a XML file and want to display it in my application by applying the formating to the text in a RichTextBox or something similar (maybe it would be better to have it as a listbox too?)

it would be something like this

<Text>
  <Normal> This is some <Bold> text </Bold> which i like to put somewhere </Normal>
  <Bold><Italic> But there is a problem </Italic></Bold>
  <Normal> I don't know how </Normal>
</Text>

this text would look like this

This is some text which i like to put somewhere
But there is a problem
I don't know how

I have searched the net but didnt find any solution...

Edit: I forgot to say that I am developing a silverlight navigation application so i cant user flowdocuments:/

Body:
You'd have to manually go through the XML nodes and define what should happen for each node.  There's many different ways to implement something like that, but I'd start by keeping it simple.

For example: (pseudocode)

Foreach XMLnode node in xmlnodes
{
    if (node.attribute == "bold")
    {
        // apply bold to node text
    }
}

You can do it like this, which is fairly simple.  I'm sure there is many ways to improve upon it and it can get fairly complicated I'm sure.


问:
Send surveyjs result to API
I am trying to send surveyjs results to my API.

In mounted(), I make a GET request with vue-resource, get questions from my dB and then set surveyjs. To send the results, I tried to use this.$http.post, in the surveyJS onComplete function, but I got Cannot read property 'post' of undefined. Also, I tried to put a watch on the result variable, but it did not work.

```<code>mounted() {
    this.$http
      .get("myAPI")
      .then(res => res.json())
      .then(questions => {
        this.questions = questions;
        this.survey = new SurveyVue.Model(this.questions.pesquisa);
        this.survey.locale = "pt";

        this.survey.onComplete.add(function(survey) {
          this.result = survey.data;
          this.$http
          .post(
            `myAPI`,
            this.result,
            { headers: { "Content-Type": "application/json" } }
          )
          .then(response => {
            console.log(response);
            UIkit.notification({
              message: "Success",
              pos: "top-center",
              status: "success"
            });
          })
          .catch(error => {
            console.log(error);
            UIkit.notification({
              message: "Erro",
              pos: "top-center",
              status: "danger"
            });
          });
        });
      })
      .catch(error => {
        console.log(error);
        UIkit.notification({
          message: "Error",
          pos: "top-center",
          status: "danger"
        });
      });
}
</code>```

答:
To get access to this inside the onComplete.add()'s parameter, you could replace your regular function with an arrow function:

this.survey.onComplete.add(survey => {
  this.result = survey.data;
  /* rest of your code... */
})
```

<p>An alternative is to place <code>this</code> into a variable, which can be used to access the outer <code>this</code>:</p>

<pre class="lang-js prettyprint-override"><code>const that = this;
this.survey.onComplete.add(function(survey) {
  that.result = survey.data;
  /* rest of your code... */
})
</code>```

Read more about this.

The gist of it is that inside the the function, the function's this overrides the component's this, unless it's an arrow function, which purposefully doesn't have a this so the outside one is available.

Title: Send surveyjs result to API

Body:
I am trying to send surveyjs results to my API.

In mounted(), I make a GET request with vue-resource, get questions from my dB and then set surveyjs. To send the results, I tried to use this.$http.post, in the surveyJS onComplete function, but I got Cannot read property 'post' of undefined. Also, I tried to put a watch on the result variable, but it did not work.

mounted() {
    this.$http
      .get("myAPI")
      .then(res => res.json())
      .then(questions => {
        this.questions = questions;
        this.survey = new SurveyVue.Model(this.questions.pesquisa);
        this.survey.locale = "pt";

        this.survey.onComplete.add(function(survey) {
          this.result = survey.data;
          this.$http
          .post(
            `myAPI`,
            this.result,
            { headers: { "Content-Type": "application/json" } }
          )
          .then(response => {
            console.log(response);
            UIkit.notification({
              message: "Success",
              pos: "top-center",
              status: "success"
            });
          })
          .catch(error => {
            console.log(error);
            UIkit.notification({
              message: "Erro",
              pos: "top-center",
              status: "danger"
            });
          });
        });
      })
      .catch(error => {
        console.log(error);
        UIkit.notification({
          message: "Error",
          pos: "top-center",
          status: "danger"
        });
      });
}

Body:
To get access to this inside the onComplete.add()'s parameter, you could replace your regular function with an arrow function:

this.survey.onComplete.add(survey => {
  this.result = survey.data;
  /* rest of your code... */
})

An alternative is to place this into a variable, which can be used to access the outer this:

const that = this;
this.survey.onComplete.add(function(survey) {
  that.result = survey.data;
  /* rest of your code... */
})

Read more about this.

The gist of it is that inside the the function, the function's this overrides the component's this, unless it's an arrow function, which purposefully doesn't have a this so the outside one is available.


问:
Not getting entered data from input element
This is js app in electron framework. I am trying to get the updated text entered inside text box as shown in image but I am not able to retrieve any data. I have ensured that data is submitted. I have predefined data in a file ,initally, I have this values but onform submit, I modify those values.

```<code>function setData()
{
  let server = mapServers[i];

  var htmlForThisHostID = '<tr>';

  htmlForThisHostID += '<td class="hostid-td-padding">';
  htmlForThisHostID += "<input id=\"first\" type=\"text\" size=\"40\"
 value=\""+server.name+"\"></input>";

  htmlForThisHostID += "</td>\n";
  htmlForThisHostID += '<td class="hostid-td-padding">';
  htmlForThisHostID += "<input type=\"text\" size=\"6\" value=\"
  "+server.pin+" \"></input>";

  htmlForThisHostID += "</td>";
  htmlForThisHostID += '<td class="hostid-td-padding">';
  htmlForThisHostID += "<input style=\"width:50px;\" type=\"submit\"
 value=\"Save\" onclick='Activate(\"" + server.name + "\"," + server.pin + ")'></input>\n";
  htmlForThisHostID += "</td>";

  htmlForThisHostID += "</tr>\n";

  return htmlForThisHostID;
}

</code>```

答:
If you are letting the form submit itself with the inputs from your function, then the problem is that you have not set a name attribute for those inputs. Just give them a name.

Unnamed inputs do not get processed see this answer for further details https://stackoverflow.com/a/12543907/6127393

Body:
This is js app in electron framework. I am trying to get the updated text entered inside text box as shown in image but I am not able to retrieve any data. I have ensured that data is submitted. I have predefined data in a file ,initally, I have this values but onform submit, I modify those values.

function setData()
{
  let server = mapServers[i];

  var htmlForThisHostID = '
';

  htmlForThisHostID += '';
  htmlForThisHostID += "<input id=\"first\" type=\"text\" size=\"40\"
 value=\""+server.name+"\"></input>";

  htmlForThisHostID += "	\n";
  htmlForThisHostID += '';
  htmlForThisHostID += "<input type=\"text\" size=\"6\" value=\"
  "+server.pin+" \"></input>";

  htmlForThisHostID += "	";
  htmlForThisHostID += '';
  htmlForThisHostID += "<input style=\"width:50px;\" type=\"submit\"
 value=\"Save\" onclick='Activate(\"" + server.name + "\"," + server.pin + ")'></input>\n";
  htmlForThisHostID += "	";

  htmlForThisHostID += "
\n";

  return htmlForThisHostID;
}


问:
Only clicked item visible and hide the pervious items in RecyclerView
I have ImageView inside of an item in a RecyclerView. Every time I click on an item, I want the image to become visible and the previous clicked item's image becomes invisible.

```<code>public static class MyHolder extends RecyclerView.ViewHolder {

    private ImageView image_view;
    private TextView text_view_name;
    private TextView text_view_abilities;
    private ImageView heart_image_view;

    public MyHolder(@NonNull final View itemView, final OnItemClickListener listener) {
        super(itemView);

        image_view = itemView.findViewById(R.id.image_view);
        text_view_name = itemView.findViewById(R.id.text_view_name);
        text_view_abilities = itemView.findViewById(R.id.text_view_abilities);
        heart_image_view = itemView.findViewById(R.id.heart_image_view);
        heart_image_view.setImageResource(R.drawable.heart);
        heart_image_view.setVisibility(View.GONE);

        itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (listener != null) {
                int position = getAdapterPosition();
                if (position != RecyclerView.NO_POSITION) {
                    listener.onItemClick(position);
                    heart_image_view.setVisibility(View.VISIBLE);
                }
            }
        });
    }
}

@NonNull
@Override
public MyHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.single_item_layout, viewGroup, false);
    MyHolder holder = new MyHolder(v, mlistener);
    return holder;
}

@Override
public void onBindViewHolder(@NonNull MyHolder myHolder, int position) {

    Item item = myList.get(position);
    myHolder.text_view_name.setText(item.getTitle());

    stringArray = item.getAbilitiesObj();
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < stringArray.size(); i++) {
        try {
            builder.append(stringArray.get(i));
            builder.append(", ");

        } catch (NumberFormatException ex) {
            ex.printStackTrace();
        }
        myHolder.text_view_abilities.setText(builder);
    }
    if (myHolder.image_view != null) {
        String photoUrl = item.getImageUrl();
        Picasso.with(mContext).load(photoUrl).into(myHolder.image_view);
    }
}
</code>```

In MyHolder class where item.setOnClick, I set the clicked item image visible but then every time I click on another item, the image of the new item becomes visible and the image of the previous item does not get invisible.

答:
You need to have another array of integers in your adapter to keep track of the items which is clicked. At first, initialize the array of integers with all ones.

```<code>// Define an array like the following in your adapter
private int[] selectedItems = new int[yourDataList.size()]; // Initialize the array to have the same size as your data list.
</code>```

Then initialize the array with all ones. Try having a function like this in your adapter.

```<code>private void initializeSeledtedItems() {
    for(int item : selectedItems) item = 1;
}
</code>```

Now in your onBindViewHolder, set the visibility of the ImageView in your RecyclerView items based on the value found in the selectedItems array.

```<code>if(selectedItems[position] == 1) heart_image_view.setVisibility(View.VISIBLE);
else heart_image_view.setVisibility(View.GONE);
</code>```

In the onClickListener modify the selectedItems array as such that, only the item selected has the value one and all the others have zeros. Then call notifyDataSetChanged to take your changes into effect.

```<code>private void setSelectedItem(int position) {
    for(int i = 0; i < selectedItems.length(); i++) {
        if(i == position) selectedItems[i] = 1;
        else selectedItems[i] = 0;
    }
}

itemView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        if (listener != null) {
            int position = getAdapterPosition();
            if (position != RecyclerView.NO_POSITION) {
                setSelectedItem(position);
                notifyDataSetChanged();
            }
        }
    }
});
</code>```

Hope that helps!

Body:
I have ImageView inside of an item in a RecyclerView. Every time I click on an item, I want the image to become visible and the previous clicked item's image becomes invisible.

public static class MyHolder extends RecyclerView.ViewHolder {

    private ImageView image_view;
    private TextView text_view_name;
    private TextView text_view_abilities;
    private ImageView heart_image_view;

    public MyHolder(@NonNull final View itemView, final OnItemClickListener listener) {
        super(itemView);

        image_view = itemView.findViewById(R.id.image_view);
        text_view_name = itemView.findViewById(R.id.text_view_name);
        text_view_abilities = itemView.findViewById(R.id.text_view_abilities);
        heart_image_view = itemView.findViewById(R.id.heart_image_view);
        heart_image_view.setImageResource(R.drawable.heart);
        heart_image_view.setVisibility(View.GONE);

        itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (listener != null) {
                int position = getAdapterPosition();
                if (position != RecyclerView.NO_POSITION) {
                    listener.onItemClick(position);
                    heart_image_view.setVisibility(View.VISIBLE);
                }
            }
        });
    }
}

@NonNull
@Override
public MyHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.single_item_layout, viewGroup, false);
    MyHolder holder = new MyHolder(v, mlistener);
    return holder;
}

@Override
public void onBindViewHolder(@NonNull MyHolder myHolder, int position) {

    Item item = myList.get(position);
    myHolder.text_view_name.setText(item.getTitle());

    stringArray = item.getAbilitiesObj();
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < stringArray.size(); i++) {
        try {
            builder.append(stringArray.get(i));
            builder.append(", ");

        } catch (NumberFormatException ex) {
            ex.printStackTrace();
        }
        myHolder.text_view_abilities.setText(builder);
    }
    if (myHolder.image_view != null) {
        String photoUrl = item.getImageUrl();
        Picasso.with(mContext).load(photoUrl).into(myHolder.image_view);
    }
}

In MyHolder class where item.setOnClick, I set the clicked item image visible but then every time I click on another item, the image of the new item becomes visible and the image of the previous item does not get invisible.

Body:
You need to have another array of integers in your adapter to keep track of the items which is clicked. At first, initialize the array of integers with all ones.

// Define an array like the following in your adapter
private int[] selectedItems = new int[yourDataList.size()]; // Initialize the array to have the same size as your data list.

Then initialize the array with all ones. Try having a function like this in your adapter.

private void initializeSeledtedItems() {
    for(int item : selectedItems) item = 1;
}

Now in your onBindViewHolder, set the visibility of the ImageView in your RecyclerView items based on the value found in the selectedItems array.

if(selectedItems[position] == 1) heart_image_view.setVisibility(View.VISIBLE);
else heart_image_view.setVisibility(View.GONE);

In the onClickListener modify the selectedItems array as such that, only the item selected has the value one and all the others have zeros. Then call notifyDataSetChanged to take your changes into effect.

private void setSelectedItem(int position) {
    for(int i = 0; i < selectedItems.length(); i++) {
        if(i == position) selectedItems[i] = 1;
        else selectedItems[i] = 0;
    }
}

itemView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        if (listener != null) {
            int position = getAdapterPosition();
            if (position != RecyclerView.NO_POSITION) {
                setSelectedItem(position);
                notifyDataSetChanged();
            }
        }
    }
});

Hope that helps!


问:
How to save any file with PyQt5?
In PyQt5, let's say I have a path to a given file or folder, would it be possible to save it in a location inputted by the user? I suppose it could also be a copy paste operation, where it copies the file or folder from one directory and pastes it to another.

I currently have the current:

```<code>def browseGeoFile(self):
    self.geoPath, _ = QFileDialog.getOpenFileName(self, "Browse Geometry File", "C:/", "*.scdoc")
    self.textBoxGeo.setText(self.geoPath)
</code>```

Now would it be possible to save this file at a location specified by the user?

答:
Saving a file in Python is completely independent from PyQt.
You could save a file with contents in contents at location path using this code:

```<code>with open(path, "w") as f: # use "wb" if writing binary data
    f.write(contents)
</code>```

Title: How to save any file with PyQt5?

Body:
In PyQt5, let's say I have a path to a given file or folder, would it be possible to save it in a location inputted by the user? I suppose it could also be a copy paste operation, where it copies the file or folder from one directory and pastes it to another.

I currently have the current:

def browseGeoFile(self):
    self.geoPath, _ = QFileDialog.getOpenFileName(self, "Browse Geometry File", "C:/", "*.scdoc")
    self.textBoxGeo.setText(self.geoPath)

Now would it be possible to save this file at a location specified by the user?

Body:
Saving a file in Python is completely independent from PyQt.
You could save a file with contents in contents at location path using this code:

with open(path, "w") as f: # use "wb" if writing binary data
    f.write(contents)


答:
You need to first hide all the other elements, so that then you can show the one you want to see. You could change all of them to have the class="test" and then prepend to your script something like this:

```<code>var tests = document.getElementsByClassName("test");
for (i = 0; i < tests.length; i++) {
  tests[i].style.display = "none";
}
</code>```

UPDATE
The full script would be something like this:

```<code><script>
  function toggle_visibility(el) {
    var tests = document.getElementsByClassName("test");
    for (i = 0; i < tests.length; i++) {
      tests[i].style.display = "none";
    }
    el.style.display = "block";
  }
</script>
</code>```

And the html:

```<code><div>
  <area class="test" onclick="toggle_visibility(this)">A</div>
  <area class="test" onclick="toggle_visibility(this)">B</div>
  <area class="test" onclick="toggle_visibility(this)">C</div>
  <area class="test" onclick="toggle_visibility(this)">D</div>
</div>
</code>```

Body:
I am making a software were i need to hide all other div's when i click on another div. what happens now is that the div's just stack on top of each other. and the div only dissapears when i click the same div again.

i already tried some of the JavaScript and jQuery code on this platform but can't quite figure it out myself.

--- THIS IS THE SCRIPT IM USING TO SHOW AND HIDE THE DIV'S ---

--- THESE ARE MY CLICKABLE AREA'S WHERE THE USER CAN CLICK ON TO SHOW AND HIDE A DIV ---

        <map name="Map" id="Map">

     <area onclick="toggle_visibility('vooglid');" alt="" title="" href="#" shape="poly" coords=170,251,159,253,140,251,134,249,126,244,121,241,118,237,114,226,113,221,118,214,128,204,141,195,160,187,176,178,194,171,208,165,230,157,249,155,268,153,284,151,300,151,326,154,341,158,358,168,371,178,380,190,394,209,402,221,408,235,412,244,403,247,392,242,378,231,366,219,347,207,334,203,316,199,286,199,263,203,246,208,221,218" />
        <area onclick="toggle_visibility('vwimpers');" alt="" title="" href="#" shape="poly" coords="170,251,159,253,140,251,134,249,126,244,121,241,118,237,114,226,113,221,118,214,128,204,141,195,160,187,176,178,194,171,208,165,230,157,249,155,268,153,284,151,300,151,326,154,341,158,358,168,371,178,380,190,394,209,402,221,408,235,412,244,403,247,392,242,378,231,366,219,347,207,334,203,316,199,286,199,263,203,246,208,221,218" />
        <area onclick="toggle_visibility('vwenkbrauw');" alt="" title="" href="#" shape="poly" coords="43,157,62,120,84,103,114,85,132,75,151,65,191,47,204,38,232,31,268,31,298,31,317,31,339,33,365,42,390,47,408,51,429,59,445,61,467,69,484,74,501,85,504,127,498,141,494,146,471,136,446,123,432,119,412,113,396,108,376,100,362,96,354,93,334,90,321,90,308,89,295,87,271,83,260,81,232,75,218,74,207,73,192,73,181,76,150,95,122,109,102,118,78,138,62,149,54,158,49,163,47,167" />
        <area onclick="toggle_visibility('vooghoek');" alt="" title="" href="#" shape="poly" coords="388,275,396,270,401,270,407,266,408,263,411,258,420,263,425,269,428,273,432,278,435,280,434,282,434,285,422,284,414,279" />

    </map>

--- AND THESE ARE MY DIV'S CONTAINING THE INFORMATION IT HAS TO SHOW AND HIDE ---

 Symptoom ooglid

 Symptoom wimper

 Symptoom wenkbrauw

 Symptoom ooghoek

I want the result to be that when I click one of the areas above, the corresponding div shows and all other divs hide.

Body:
You need to first hide all the other elements, so that then you can show the one you want to see. You could change all of them to have the class="test" and then prepend to your script something like this:

var tests = document.getElementsByClassName("test");
for (i = 0; i < tests.length; i++) {
  tests[i].style.display = "none";
}

UPDATE
The full script would be something like this:

<script>
  function toggle_visibility(el) {
    var tests = document.getElementsByClassName("test");
    for (i = 0; i < tests.length; i++) {
      tests[i].style.display = "none";
    }
    el.style.display = "block";
  }
</script>

And the html:

<div>
  <area class="test" onclick="toggle_visibility(this)">A</div>
  <area class="test" onclick="toggle_visibility(this)">B</div>
  <area class="test" onclick="toggle_visibility(this)">C</div>
  <area class="test" onclick="toggle_visibility(this)">D</div>
</div>


问:
How to send long SMS in Android?
I'm using RSA Encryption with a key of 1024bit , the ciphered text's length will be more than 160 bytes , and on sending an SMS of more than 160bytes it gives exception and after using sendmultisms() and divide the message , at the receiver side gets unprintable characters and also I will have a problem of how to concatandenate the SMSs.</p>

答:
You can also encode the ciphered text using Base64 encoding, break it up the into an ArrayList of Strings and use  sendMultipartTextMessage. It then sends as many SMS as needed.</p>

```<code>SmsManager sms = SmsManager.getDefault();
ArrayList<String> parts = sms.divideMessage(base64EncodedMessage);
sms.sendMultipartTextMessage(phoneNumber, null, parts, null, null);
</code>```

Title: How to send long SMS in Android?

Body:
You can also encode the ciphered text using Base64 encoding, break it up the into an ArrayList of Strings and use  sendMultipartTextMessage. It then sends as many SMS as needed.

SmsManager sms = SmsManager.getDefault();
ArrayList<String> parts = sms.divideMessage(base64EncodedMessage);
sms.sendMultipartTextMessage(phoneNumber, null, parts, null, null);


问:
How to fix a React search filter that doesn't update on backspace
The issue:

I'm trying to create a search filter in React, based on first and last name. The search is working when I initially type a matching name, but the results don't update whenever I backspace. Component and additional details included below:

```<code>class People extends Component {
    state = {
        people: [],
        searchValue: ''
    };

    componentDidMount() {
        axios.get('/metadata.json').then(response => {
            const updatedPeople = response.data.map(person => {
                return {
                    ...person
                };
            });
            this.setState({ people: updatedPeople });
        }).catch(error => { console.log(error); });
    }

    searchHandler = (event) => {
        let searchResults = this.state.people;
        searchResults = searchResults.filter(result => {
            return result.name.toLowerCase().search(
                event.target.value.toLowerCase()) !== -1;
        });

        this.setState({
            people: searchResults,
            searchValue: event.target.value.toLowerCase()
        }, () => console.log('state', this.state))
    };

    render() {
        let people = this.state.people.map((person, index) => {
            return (
                <Person
                    key={index}
                    name={person.name} />
            );
        });

        return (
            <React.Fragment>
                <input
                    type="search"
                    value={this.state.searchValue}
                    onChange={this.searchHandler} />
                <div className={classes.People}>
                    {people}
                </div>
            </React.Fragment>
        );
    }
}
</code>```

What I've tried:

creating a search handler that filters names matching event.target.value and updating state based on the results.

adding a second property to state, filteredPeople, to store the filtered list of names while keeping the original list in state.people. However, I ran into issues reconciling these two

writing a function to check the search query and return a value based on whether there's a match, but I questioned if this was needed given the check I'm already doing in searchHandler.

What do I need to do to get my search filter fully functional?

答:
You need two arrays one for original data and one for filtered data

```<code>state = {
    people: [],
    searchValue: '',
    filteredPeople: [],
};

handleSearch = event => {
  const search = event.target.value.toLowerCase();

  this.setState({
    searchValue: search,
    filteredPeople: this.state.people.filter(
     item =>
      (item.lastname && item.lastname.toLowerCase().includes(search)) ||
      (item.name && item.name.toLowerCase().includes(search))
    )
   });
};
</code>```

Then render your filtred array

```<code>let people = this.state.filteredPeople.map((person, index) => {
  return (
    <Person
      key={index}
      name={person.name} />
    );
});
</code>```

```

Body:
The issue:

I'm trying to create a search filter in React, based on first and last name. The search is working when I initially type a matching name, but the results don't update whenever I backspace. Component and additional details included below:

class People extends Component {
    state = {
        people: [],
        searchValue: ''
    };

    componentDidMount() {
        axios.get('/metadata.json').then(response => {
            const updatedPeople = response.data.map(person => {
                return {
                    ...person
                };
            });
            this.setState({ people: updatedPeople });
        }).catch(error => { console.log(error); });
    }

    searchHandler = (event) => {
        let searchResults = this.state.people;
        searchResults = searchResults.filter(result => {
            return result.name.toLowerCase().search(
                event.target.value.toLowerCase()) !== -1;
        });

        this.setState({
            people: searchResults,
            searchValue: event.target.value.toLowerCase()
        }, () => console.log('state', this.state))
    };

    render() {
        let people = this.state.people.map((person, index) => {
            return (
                <Person
                    key={index}
                    name={person.name} />
            );
        });

        return (
            <React.Fragment>
                <input
                    type="search"
                    value={this.state.searchValue}
                    onChange={this.searchHandler} />

                    {people}

            </React.Fragment>
        );
    }
}

What I've tried:

creating a search handler that filters names matching event.target.value and updating state based on the results.

adding a second property to state, filteredPeople, to store the filtered list of names while keeping the original list in state.people. However, I ran into issues reconciling these two

writing a function to check the search query and return a value based on whether there's a match, but I questioned if this was needed given the check I'm already doing in searchHandler.

What do I need to do to get my search filter fully functional?

Body:
You need two arrays one for original data and one for filtered data

state = {
    people: [],
    searchValue: '',
    filteredPeople: [],
};

handleSearch = event => {
  const search = event.target.value.toLowerCase();

  this.setState({
    searchValue: search,
    filteredPeople: this.state.people.filter(
     item =>
      (item.lastname && item.lastname.toLowerCase().includes(search)) ||
      (item.name && item.name.toLowerCase().includes(search))
    )
   });
};

Then render your filtred array

let people = this.state.filteredPeople.map((person, index) => {
  return (
    <Person
      key={index}
      name={person.name} />
    );
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<div id="root"></div>

<script type="text/babel">

const people = [{
  name: 'Isaac', lastname: 'Jacobs'
},
{
  name: 'Peter', lastname: 'Micheal'
},
{
  name: 'John', lastname: 'Snow'
}
]

class Person extends React.Component {
  render() {
    return (
      <div>
        <p>{`${this.props.name} - ${this.props.last}`}</p>
      </div>
    )
  }
}

class App extends React.Component {

  state = {
    people: people,
    searchValue: '',
    filteredPeople: people,
  };

  searchHandler = event => {
    const search = event.target.value.toLowerCase();

    this.setState({
      searchValue: search,
      filteredPeople: this.state.people.filter(
        item =>
          (item.lastname && item.lastname.toLowerCase().includes(search)) ||
          (item.name && item.name.toLowerCase().includes(search))
      )
    });
  };

  render() {

    let people = this.state.filteredPeople.map((person, index) => {
      return (
        <Person
          key={index}
          last={person.lastname}
          name={person.name} />
      );
    });
    return (
      <div>
        <input
          type="search"
          value={this.state.searchValue}
          onChange={this.searchHandler} />
        {people}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
</script>


问:
Version info for App localisation displayed on App Store
In App Store Connect, which is the default version information displayed on the App Store for the text fields "What's new in this version" & "Promotional Text" in the localized alternatives?

Is the following assumption correct?

The version information is provided in English in the App's main language "English US" and in Spanish "Spanish (Spain)":

Spanish (Spain) as well as all other Spanish variants will use the
Spanish text that is provided manually.

All other App Stores using English or another language will display the English text that has been provided manually.

Or are both text fields being left empty actually don't display anything in the App Store?

I feel like having to copy&paste the English version manually for all localised versions (using only localised keywords) shouldn't be necessary.

If you have tested this or seen the actual behaviour, I'd very much appreciate your answer.

答:
Answer from Anand is not correct.

1) For all required fields (like description, keywords, what's new etc.) you must insert something for all active languages/localizations over at App Store Connect.

Example: If you start version 1.0 with English (en-US) as your primary locale and add Spanish (es-ES) to your version 1.1 you must insert something in the "What's new" section for Spanish. (As for all other required fields) Otherwise App Store Connect won't let you submit the app for review.

App Store Connect won't validate or check your translations, so you could translate your general metadata once and "keep" the "What's new" section English, but you must copy & paste the information.

2) Optional fields (promotional text, marketing URL etc.) can be left blank or only filled in for one language, but the App Store will not mix and match locales.

Example: If you insert a promotional text for English (en-US), which is your primary locale, and none for Spanish (es-ES), the Spanish localization will not display any promotional text.

With regards to when which language is used, check out this paragraph from the App Store Connect Help:

For example, if the primary language you select for your app in App Store Connect is English and it’s the only language you provide, your app metadata in all App Store territories appears in English. If you localize your app metadata in French, users whose language setting is French will see the French localization. Users in territories where the App Store supports French but not English also see the French localization. Users can search for your app using localized keywords in all territories where the App Store supports French. If there’s no localization available that matches the language setting, the next most relevant localization is used. In other App Store territories, users see your metadata in the primary language (English in this example).


问:
INSTALL_BASE=~/perl5 -- NOT OK - While installing Perl Module
I am trying to install one of the Perl module in my local system (Windows 7). But its failing to install the module

Here is what its displaying

```<code>C:\Windows\system32>perl -MCPAN -e "install Net::SFTP"
Reading 'C:\Users\AppData\Local\.cpan\Metadata'
  Database was generated on Sun, 26 May 2019 05:17:03 GMT
Running install for module 'Net::SFTP'
Checksum for C:\Users\AppData\Local\.cpan\sources\authors\id\L\LK\LKINLE
Y\Net-SFTP-0.12.tar.gz ok
Configuring L/LK/LKINLEY/Net-SFTP-0.12.tar.gz with Makefile.PL
Checking if your kit is complete...
Looks good
Warning: prerequisite Math::Int64 0.54 not found.
Warning: prerequisite Net::SSH::Perl 2.12 not found.
The getpwuid function is unimplemented at C:/Perl64/lib/ExtUtils/MakeMaker.pm li
ne 1064.
Warning: No success on command[C:\Perl64\bin\perl.exe Makefile.PL INSTALL_BASE=~
/perl5]
  LKINLEY/Net-SFTP-0.12.tar.gz
  C:\Perl64\bin\perl.exe Makefile.PL INSTALL_BASE=~/perl5 -- NOT OK
</code>```

It was working fine before and I have installed couple of modules, don't know what happens suddenly.

Please help me to resolve this. Do I need to make any modifications in config?

答:
You're telling Perl to into ~/perl5. That's not a Windows path, and ExtUtils::MakeMaker is using a unix-specific function (getpwuid) to expand it. Your problem should go away if you use a Windows path.

That said, if you have access to write to C:\Perl64\..., I suggest that you install modules to the default directory by removing INSTALL_BASE=~/perl5.

If you don't have access to write to C:\Perl64\..., I suggest that you install Perl itself in a directly to which you do have access to write, and then I'd install modules to the default directory by removing INSTALL_BASE=~/perl5.

Since you didn't actually specify INSTALL_BASE=~/perl5 on the command line, you are specifying it through the environment (PERL_MM_OPT and PERL_MB_OPT),  or in cpan's configuration (o conf from within cpan).

Body:
I am trying to install one of the Perl module in my local system (Windows 7). But its failing to install the module

Here is what its displaying

C:\Windows\system32>perl -MCPAN -e "install Net::SFTP"
Reading 'C:\Users\AppData\Local\.cpan\Metadata'
  Database was generated on Sun, 26 May 2019 05:17:03 GMT
Running install for module 'Net::SFTP'
Checksum for C:\Users\AppData\Local\.cpan\sources\authors\id\L\LK\LKINLE
Y\Net-SFTP-0.12.tar.gz ok
Configuring L/LK/LKINLEY/Net-SFTP-0.12.tar.gz with Makefile.PL
Checking if your kit is complete...
Looks good
Warning: prerequisite Math::Int64 0.54 not found.
Warning: prerequisite Net::SSH::Perl 2.12 not found.
The getpwuid function is unimplemented at C:/Perl64/lib/ExtUtils/MakeMaker.pm li
ne 1064.
Warning: No success on command[C:\Perl64\bin\perl.exe Makefile.PL INSTALL_BASE=~
/perl5]
  LKINLEY/Net-SFTP-0.12.tar.gz
  C:\Perl64\bin\perl.exe Makefile.PL INSTALL_BASE=~/perl5 -- NOT OK

It was working fine before and I have installed couple of modules, don't know what happens suddenly.

Please help me to resolve this. Do I need to make any modifications in config?


问:
Turtle start and end screen ideas
I am kind of stuck on how to incorporate a start screen with the game information and an end screen with the game results and an option to restart the game?

I tried to write the text and then restart the screen but the text does not show up. I do not know if I can create multiple screen instances or am I missing something?

答:
Use turtle.write(text) then you can use tkinter to put buttons on the turtle screen. Alternatively, there is a really easy GUI for Python called EasyGUI.

Install using:

```<code>pip install easygui
</code>```

Usage:

```<code>import easygui
yn = easygui.ynbox('Game over', 'Continue?', ('Yes', 'No'))
if yn == 'Yes':
    Startover()
</code>```

Title: Turtle start and end screen ideas

Body:
Use turtle.write(text) then you can use tkinter to put buttons on the turtle screen. Alternatively, there is a really easy GUI for Python called EasyGUI.

Install using:

pip install easygui

Usage:

import easygui
yn = easygui.ynbox('Game over', 'Continue?', ('Yes', 'No'))
if yn == 'Yes':
    Startover()


问:
Can't set default value for column
I can't set default value for for column in my table. I see lot of many example, but i can't resolve my issue. I have table with two columns: id, name. I'm need, if id == null, then set default value.

```<code>ALTER TABLE my_table ALTER id SET DEFAULT nextval('val_seq')
INSERT INTO my_table (id, name) VALUES (null, 'test_name')
</code>```

I receive error: null value in column "id" violates not-null constant. How fixed this?

答:
Just try not to include the column that you want to use the default value for in your insert statement.

```<code>INSERT INTO my_table (name) VALUES ('test_name')
</code>```

The default constraint will provide a default value for a column IF no other value is specified.

Title: Can't set default value for column

Body:
I can't set default value for for column in my table. I see lot of many example, but i can't resolve my issue. I have table with two columns: id, name. I'm need, if id == null, then set default value.

ALTER TABLE my_table ALTER id SET DEFAULT nextval('val_seq')
INSERT INTO my_table (id, name) VALUES (null, 'test_name')

I receive error: null value in column "id" violates not-null constant. How fixed this?

Body:
Just try not to include the column that you want to use the default value for in your insert statement.

INSERT INTO my_table (name) VALUES ('test_name')

The default constraint will provide a default value for a column IF no other value is specified.


问:
How to Convert Tuple to Dictionary?
i'm using Python 2.5 and Win XP. i have a tuple as below:

```<code>>>> a
(None, '{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}')
>>> a[1]
'{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}'
>>>
</code>```

i want to convert tuple a[1] to dictionary because i want to use the key and value. pls help to advise. tq

答:
The dict() constructor builds
  dictionaries directly from lists of
  key-value pairs stored as tuples. When
  the pairs form a pattern, list
  comprehensions can compactly specify
  the key-value list.

dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
          {'sape': 4139, 'jack': 4098, 'guido': 4127}
      dict([(x, x**2) for x in (2, 4, 6)])     # use a list comprehension
          {2: 4, 4: 16, 6: 36}

Copy & Paste from: http://docs.python.org/tutorial/datastructures.html

Title: How to Convert Tuple to Dictionary?

Body:
i'm using Python 2.5 and Win XP. i have a tuple as below:

>>> a
(None, '{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}')
>>> a[1]
'{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}'
>>>

i want to convert tuple a[1] to dictionary because i want to use the key and value. pls help to advise. tq


问:
How to select right template for class
As an input, I'm given a number, which is a bit-width of a variable. For ex. if it's 5, I need to use char(which is 8), if I'm given 14, i need to use 16-bit int.
I'm free to use STD lib and all of standards up to C++17.

I've created class, but I can't find how can I create instance without enclosing brackets. I don't know how can I create such object without specifying class template, not even as a pointer.

template<typename T>
class Kompresor{
...
};

int main(int agrc, char* argv[]){

    size_t max_value = argv[1];
    size_t copy = max_value + 1;
    int byte_width = 0;
    while(copy > 0){
        copy = copy >> 1;
        ++byte_width;
    }
    // This works
    // Problem is brackets, can't use kompresor outside scope
    if(byte_width < 9){
        Kompresor<char> Kompresor();
    }else if(byte_width < 17){
        Kompresor<int16_t> Kompresor();
    }
    // This dosen't
    Kompresor<>* k;
    k = new Kompresor<char>();

    return 0;
}
```

I need to use object throughout program, and writing same code in all of enclosing brackets is just code redundancy.

答:
As I don't know size at compile time, I resorted to using
std::vector<uint8_t>, and keeping track of vector size, thanks @skeller, and rest of you.

Title: How to select right template for class

Body:
As an input, I'm given a number, which is a bit-width of a variable. For ex. if it's 5, I need to use char(which is 8), if I'm given 14, i need to use 16-bit int.
I'm free to use STD lib and all of standards up to C++17.

I've created class, but I can't find how can I create instance without enclosing brackets. I don't know how can I create such object without specifying class template, not even as a pointer.

template<typename T>
class Kompresor{
...
};

int main(int agrc, char* argv[]){

    size_t max_value = argv[1];
    size_t copy = max_value + 1;
    int byte_width = 0;
    while(copy > 0){
        copy = copy >> 1;
        ++byte_width;
    }
    // This works
    // Problem is brackets, can't use kompresor outside scope
    if(byte_width < 9){
        Kompresor<char> Kompresor();
    }else if(byte_width < 17){
        Kompresor<int16_t> Kompresor();
    }
    // This dosen't
    Kompresor<>* k;
    k = new Kompresor<char>();

    return 0;
}

I need to use object throughout program, and writing same code in all of enclosing brackets is just code redundancy.


问:
Vertically aligning a checkbox
I have looked at the different questions regarding this issue, but couldn't find anything that works due to limitations in my markup.

My markup looks like so (unfortunately as this is generated by some backend, I am unable to change the markup).

```<code><ul>
    <li>
        <input type="checkbox" value="1" name="test[]" id="myid1">
        <label for="myid1">label1</label>
    </li>
    <li>
        <input type="checkbox" value="2" name="test[]" id="myid2">
        <label for="myid2">label1</label>
    </li>
</ul>
</code>```

I need the checkbox to be on the right and centered vertically in the

Currently, this is styled as:

```<code>li input{
   display: inline-block;
   float: right;
   margin-right: 10px;
}
</code>```

I have tried using various values for vertical-align, but that doesn't seem to help. Also, in some cases the label can be very long and span multiple lines. The checkbox would still need to be able to vertically center itself when the height of the li is arbitrary.

How can I go about achieving this?

答:
The most effective solution that I found is to define the parent element with display:flex and align-items:center

LIVE DEMO

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <style>
      .myclass{
        display:flex;
        align-items:center;
        background-color:grey;
        color:#fff;
        height:50px;
      }
    </style>
  </head>
  <body>
    <div class="myclass">
      <input type="checkbox">
      <label>do you love Ananas?
      </label>
    </div>
  </body>
</html>
</code>```

OUTPUT:

Title: Vertically aligning a checkbox

Body:
I have looked at the different questions regarding this issue, but couldn't find anything that works due to limitations in my markup.

My markup looks like so (unfortunately as this is generated by some backend, I am unable to change the markup).

        <input type="checkbox" value="1" name="test[]" id="myid1">
        label1

        <input type="checkbox" value="2" name="test[]" id="myid2">
        label1

I need the checkbox to be on the right and centered vertically in the

Currently, this is styled as:

li input{
   display: inline-block;
   float: right;
   margin-right: 10px;
}

I have tried using various values for vertical-align, but that doesn't seem to help. Also, in some cases the label can be very long and span multiple lines. The checkbox would still need to be able to vertically center itself when the height of the li is arbitrary.

How can I go about achieving this?

Body:
The most effective solution that I found is to define the parent element with display:flex and align-items:center

LIVE DEMO

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <style>
      .myclass{
        display:flex;
        align-items:center;
        background-color:grey;
        color:#fff;
        height:50px;
      }
    </style>
  </head>
  <body>
    <div class="myclass">
      <input type="checkbox">
      <label>do you love Ananas?
      </label>
    </div>
  </body>
</html>

OUTPUT:


问:
required country combobox
In my project I hava one field that is country name.Till now I am inserting the country name on textfield. I want the combobox which already contain all the country name. Is there any combobox like that in java? </p>

答:
If you're using Swing, there's the JComboBox class. You can use it like this:

```<code>JComboBox comboBox = new JComboBox();
comboBox.addItem("First item");
comboBox.addItem("Second item");
comboBox.addItemListener(new ItemListener()
{
    @Override
    public void itemStateChanged(ItemEvent e)
    {
        if (e.getStateChange() == ItemEvent.SELECTED)
            System.out.println("Item " + e.getItem() + " selected");
        else
            System.out.println("Item " + e.getItem() + " deselected");
    }
});
System.out.println("Selected item: " + comboBox.getSelectedItem());
</code>```

Title: required country combobox

Body:
If you're using Swing, there's the JComboBox class. You can use it like this:

JComboBox comboBox = new JComboBox();
comboBox.addItem("First item");
comboBox.addItem("Second item");
comboBox.addItemListener(new ItemListener()
{
    @Override
    public void itemStateChanged(ItemEvent e)
    {
        if (e.getStateChange() == ItemEvent.SELECTED)
            System.out.println("Item " + e.getItem() + " selected");
        else
            System.out.println("Item " + e.getItem() + " deselected");
    }
});
System.out.println("Selected item: " + comboBox.getSelectedItem());