问:
Can't load "glyp" properly for opengl using freetype2
It seems as if freetype library isn't loading the font properly and doesn't convert it to bytes for later use as opengl texture.

Here is the result I'm getting with freetype:

I've already tried using another texture so it's unlikely that it's my texture manager's problem.

```<code>Font(const std::string font) //constructor
        :name(font)
    {
        std::string _font = "fonts/" + font + ".ttf";

        FT_Library ft;
        FT_Init_FreeType(&ft);

        FT_Face face;
        if (FT_New_Face(ft, _font.c_str(), 0, &face))
            EXIT_ERROR(-11);

        FT_Set_Pixel_Sizes(face, 0, 48);

        for (unsigned int a = 1; a < 128; a++)
        {
            char c = a;

            if (FT_Load_Char(face, c, FT_LOAD_RENDER))
            {
                EXIT_ERROR(-12);
            }

//This just creates the FontTexture type, as I said before it works
//fine,FontTexture is abstracted from BaseTexture which stores char* with
//data. I also made sure that the stuff is loaded
//there properly from inside FontTexture.

            FontTexture* _char = new FontTexture(
//here is buffer passing
face->glyph->bitmap.buffer,
                0,
                { static_cast<float>(face->glyph->bitmap.width),
                static_cast<float>(face->glyph->bitmap.rows) });

            _char->SetAdvance(face->glyph->advance.x);
            _char->SetBearing({ static_cast<float>(face->glyph->bitmap_left),
                static_cast<float>(face->glyph->bitmap_top )});

//This just caches texture, so instead of loading it multiple times I can
//just call "getTexture(name) store that pointer in the entitie's memory
//and bind when Draw() is being called.
            TextureManager::getTextureManager().PrecacheTexture(std::to_string(a) + font, _char);

            Characters.insert(std::pair<char, FontTexture*>(c, _char));
        }

        FT_Done_Face(face);
        FT_Done_FreeType(ft);
    }
</code>```

答: The problem was that glPixelStorei( GL_UNPACK_ALIGNMENT, 1) flag wasn't enabled. I probably enabled it before opengl had valid context.</p>

Body:
It seems as if freetype library isn't loading the font properly and doesn't convert it to bytes for later use as opengl texture.

Here is the result I'm getting with freetype:

I've already tried using another texture so it's unlikely that it's my texture manager's problem.

Font(const std::string font) //constructor
        :name(font)
    {
        std::string _font = "fonts/" + font + ".ttf";

        FT_Library ft;
        FT_Init_FreeType(&ft);

        FT_Face face;
        if (FT_New_Face(ft, _font.c_str(), 0, &face))
            EXIT_ERROR(-11);

        FT_Set_Pixel_Sizes(face, 0, 48);

        for (unsigned int a = 1; a < 128; a++)
        {
            char c = a;

            if (FT_Load_Char(face, c, FT_LOAD_RENDER))
            {
                EXIT_ERROR(-12);
            }

//This just creates the FontTexture type, as I said before it works
//fine,FontTexture is abstracted from BaseTexture which stores char* with
//data. I also made sure that the stuff is loaded
//there properly from inside FontTexture.

            FontTexture* _char = new FontTexture(
//here is buffer passing
face->glyph->bitmap.buffer,
                0,
                { static_cast<float>(face->glyph->bitmap.width),
                static_cast<float>(face->glyph->bitmap.rows) });

            _char->SetAdvance(face->glyph->advance.x);
            _char->SetBearing({ static_cast<float>(face->glyph->bitmap_left),
                static_cast<float>(face->glyph->bitmap_top )});

//This just caches texture, so instead of loading it multiple times I can
//just call "getTexture(name) store that pointer in the entitie's memory
//and bind when Draw() is being called.
            TextureManager::getTextureManager().PrecacheTexture(std::to_string(a) + font, _char);

            Characters.insert(std::pair<char, FontTexture*>(c, _char));
        }

        FT_Done_Face(face);
        FT_Done_FreeType(ft);
    }


来源: stackexchange

问:
PIL: Image.fromarray(img.astype('uint8'), mode='RGB') returns grayscale image
I have converted a pytorch tensor of size torch.Size([3, 28, 28]) to a numpy array of size (28, 28, 3), and there doesn't seem to be any problems with that. I then try to convert this to a PIL image using img = Image.fromarray(img.astype('uint8'), mode='RGB'), but the dimensions of the returned img are (28, 28), when I expect it to be (28, 28, 3) (or (3, 28, 28)). I cannot understand why this is the case. I made sure to convert to uint8 and use RGB mode, as other posters have suggested online, however neither of those (nor using np.ascontiguousarray) helped.

PIL version 1.1.7

```<code># This code implements the __getitem__ function for a child class of datasets.MNIST in pytorch
# https://pytorch.org/docs/stable/_modules/torchvision/datasets/mnist.html#MNIST

img, label = self.data[index], self.targets[index]
assert img.shape == (3, 28, 28), \
       (f'[Before PIL] Incorrect image shape: expecting (3, 28, 28),'
        f'received {img.shape}')

print('Before reshape:', img.shape)    # torch.Size([3, 28, 28])
img = img.numpy().reshape(3, 28, 28)
img = np.stack([img[0,:,:], img[1,:,:], img[2,:,:]], axis=2)
print('After reshape:', img.shape)     # (28, 28, 3)

# doing this so that it is consistent with all other datasets
# to return a PIL Image
img = Image.fromarray(img.astype('uint8'), mode='RGB') # Returns 28 x 28 image

assert img.size == (3, 28, 28), \
       (f'[Before Transform] Incorrect image shape: expecting (3, 28, 28), '
        f'received {img.size}')
</code>```

EDIT: Here is a minimal example. I'll leave the above for context in case it is of any help at all.

```<code>from PIL import Image
import numpy as np

img = np.random.randn(28, 28, 3)
img = Image.fromarray(img.astype('uint8'), mode='RGB') # Returns 28 x 28 image

assert img.size == (28, 28, 3), \
       (f'[Before Transform] Incorrect image shape: expecting (3, 28, 28), '
        f'received {img.size}')
</code>```

AssertionError: [Before Transform] Incorrect image shape: expecting (3, 28, 28), received (28, 28)

答:
I think you want this, where the ranges of the RGB vales are integers in range 0..255:

```<code>import numpy as np
from PIL import Image

# Make random 28x28 RGB image
img =np.random.randint(0,256,(28,28,3), dtype=np.uint8)

# Convert to PIL Image
pImg=Image.fromarray(img, mode='RGB')
</code>```

Now check what we have:

```<code>In [19]: pImg
Out[19]: <PIL.Image.Image image mode=RGB size=28x28 at 0x120CE9CF8>
</code>```

And save:

```<code>pImg.save('result.png')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have converted a pytorch tensor of size torch.Size([3, 28, 28]) to a numpy array of size (28, 28, 3), and there doesn't seem to be any problems with that. I then try to convert this to a PIL image using img = Image.fromarray(img.astype('uint8'), mode='RGB'), but the dimensions of the returned img are (28, 28), when I expect it to be (28, 28, 3) (or (3, 28, 28)). I cannot understand why this is the case. I made sure to convert to uint8 and use RGB mode, as other posters have suggested online, however neither of those (nor using np.ascontiguousarray) helped.

PIL version 1.1.7

# This code implements the __getitem__ function for a child class of datasets.MNIST in pytorch
# https://pytorch.org/docs/stable/_modules/torchvision/datasets/mnist.html#MNIST

img, label = self.data[index], self.targets[index]
assert img.shape == (3, 28, 28), \
       (f'[Before PIL] Incorrect image shape: expecting (3, 28, 28),'
        f'received {img.shape}')

print('Before reshape:', img.shape)    # torch.Size([3, 28, 28])
img = img.numpy().reshape(3, 28, 28)
img = np.stack([img[0,:,:], img[1,:,:], img[2,:,:]], axis=2)
print('After reshape:', img.shape)     # (28, 28, 3)

# doing this so that it is consistent with all other datasets
# to return a PIL Image
img = Image.fromarray(img.astype('uint8'), mode='RGB') # Returns 28 x 28 image

assert img.size == (3, 28, 28), \
       (f'[Before Transform] Incorrect image shape: expecting (3, 28, 28), '
        f'received {img.size}')

EDIT: Here is a minimal example. I'll leave the above for context in case it is of any help at all.

from PIL import Image
import numpy as np

img = np.random.randn(28, 28, 3)
img = Image.fromarray(img.astype('uint8'), mode='RGB') # Returns 28 x 28 image

assert img.size == (28, 28, 3), \
       (f'[Before Transform] Incorrect image shape: expecting (3, 28, 28), '
        f'received {img.size}')

AssertionError: [Before Transform] Incorrect image shape: expecting (3, 28, 28), received (28, 28)

Body:
I think you want this, where the ranges of the RGB vales are integers in range 0..255:

import numpy as np
from PIL import Image

# Make random 28x28 RGB image
img =np.random.randint(0,256,(28,28,3), dtype=np.uint8)

# Convert to PIL Image
pImg=Image.fromarray(img, mode='RGB')

Now check what we have:

In [19]: pImg
Out[19]: <PIL.Image.Image image mode=RGB size=28x28 at 0x120CE9CF8>

And save:

pImg.save('result.png')


问:
Using for loop and charAt to check if each letter appears exactly twice in a word
i'm writing a program in java that checks if a letter appers exactly twice, i was able to write it but my problem is that for some words the code doesn't check if the letter appear exactly twice.
here is my code:</p>

```<code>public class Test {

public static void main(String[] args) {
  isDoubloon("abba");
  isDoubloon("Shanghaiingss");/*it still prints out true though 's' does appear exactly twice*/}

//checks if every letter appears twice in a word
public static void isDoubloon(String s){
    String l=s.toLowerCase();
    int count=0;

    for(int i= 0; i<l.length()-1;i++){
        for(int j=i+1;j<l.length();j++){

            if(l.charAt(i)==l.charAt(j)) count++;
        }

    }
    if(count%2==0){
        System.out.println("True, This is a doubloon");
    }else
        System.err.println("False, This is not a doubloon");

}}
</code>```

答:
```<code>public static boolean isDoubloon(String s) {
    if (s.length() %2 != 0)
        return false;

    String str = s.toLowerCase();

    while (str.length() > 0) {
        int index2 = str.indexOf(str.charAt(0), 1);
        if (index2 == -1) {
            return false;
        }
        int index3 = str.indexOf(str.charAt(0), index2 + 1);
        if (index3 != -1) {
            return false;
        }

        str = str.substring(1, index2) + str.substring(index2 + 1);
    }
    return true;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i'm writing a program in java that checks if a letter appers exactly twice, i was able to write it but my problem is that for some words the code doesn't check if the letter appear exactly twice.
here is my code:

public class Test {

public static void main(String[] args) {
  isDoubloon("abba");
  isDoubloon("Shanghaiingss");/*it still prints out true though 's' does appear exactly twice*/}

//checks if every letter appears twice in a word
public static void isDoubloon(String s){
    String l=s.toLowerCase();
    int count=0;

    for(int i= 0; i<l.length()-1;i++){
        for(int j=i+1;j<l.length();j++){

            if(l.charAt(i)==l.charAt(j)) count++;
        }

    }
    if(count%2==0){
        System.out.println("True, This is a doubloon");
    }else
        System.err.println("False, This is not a doubloon");

}}


问:
Where can I find a good NHibernate and ASP.NET MVC Reference Application
Where can I find a good NHibernate and ASP.NET MVC Reference Application? I downloaded S#arp and this seemed to be a lot more than I needed (IOC and CodeGen via T4). I might work my way up to this later, but I need something smaller at first.

Any simple examples? I just want to pick up how NHibernate Session handling works in ASP.NET MVC.  And maybe how some simple query scenarios work. Still trying to grasp how a SELECT DISTINCT would be done in NHibernate and through to the View via the ViewData.

答:
I would try to tackle them independently.

Before Billy McCafferty wrote sharp-architecture he wrote, what I think is, a must read on codeproject about best practices with NHibernate. Also, I have just discovered  some DimeCasts(by Kyle Baley) under the MVC tag that are very good.

Rob Conery created the ASP.NET MVC Storefront video series which he goes over a lot of patterns and practices. The backend written is using Linq to SQL but can be adapted with LinQ to NHibernate. More recently he has also done a video series on TekPub  - NHibernate with Ayende Rahien. Lastly (for NHibernate) there is the Summer of NHibernate

The S# arch source itself now comes with a sample projects as well.

Finally, there is Code Camp Server that is built with MVC.Net and NHibernate and uses pretty much every open source tool you can think of...

sidenote

If your interested in getting rid of those annoying XML files when using NHibernate you might also want to look at fluent.

OwnerDisplayName: Bruno Tyndall

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Fabian Steeg

OwnerDisplayName: bthb

LastEditorDisplayName: BtBh


问:
How to make two buttons inline if each of them is in different form?
How can I make the submit buttons in two different forms inline ? The first form must be a block level element but the second one can be inline-block.</p>

```<code><form action="#">
     <div class="form-group">
        <label for="title">Title</label>
        <input type="text" name="title" class="form-control" id="title" placeholder="Enter title">
    </div>

    <div class="form-group">
        <label for="body">Body</label>
        <textarea class="form-control" name="body" id="body" rows="10"></textarea>
    </div>

    <button type="submit" class="btn btn-primary">Update</button>

</form>

<form action="#">
    <button type="submit" class="btn btn-danger">DELETE</button>
</form>
</code>```

答:
Simply move the delete button into the other form tag. This should work.

<form action="#">

        Title
        <input type="text" name="title" class="form-control" id="title" placeholder="Enter title">

        Body
        <textarea class="form-control" name="body" id="body" rows="10"></textarea>

    <button type="submit" class="btn btn-primary">Update</button>

    <form action="#">
    <button type="submit" class="btn btn-danger">DELETE</button>
    </form>

</form>
```

Body:
How can I make the submit buttons in two different forms inline ? The first form must be a block level element but the second one can be inline-block.

<form action="#">

        Title
        <input type="text" name="title" class="form-control" id="title" placeholder="Enter title">

        Body
        <textarea class="form-control" name="body" id="body" rows="10"></textarea>

    <button type="submit" class="btn btn-primary">Update</button>

</form>

<form action="#">
    <button type="submit" class="btn btn-danger">DELETE</button>
</form>

Body:
Simply move the delete button into the other form tag. This should work.

<form action="#">
     <div class="form-group">
        <label for="title">Title</label>
        <input type="text" name="title" class="form-control" id="title" placeholder="Enter title">
    </div>

    <div class="form-group">
        <label for="body">Body</label>
        <textarea class="form-control" name="body" id="body" rows="10"></textarea>
    </div>

    <button type="submit" class="btn btn-primary">Update</button>

    <form action="#">
    <button type="submit" class="btn btn-danger">DELETE</button>
    </form>

</form>


问:
Mule 4 secure property placeholder not working
This is my config  where i have defined my properties file ie dev.properties which has some encrypted values. I have defined my secure property placeholder but its not working

```<code><global-property doc:name="Global Property" doc:id="7080a89f-d39c-485d-99c4-b35337ab62c4" name="env" value="dev" />
    <global-property doc:name="Global Property" doc:id="5d1fb026-a34f-490f-9b50-7a9bcb5cdf83" name="enc.key" value="password" />
    <configuration-properties doc:name="Configuration properties"
        doc:id="7448fcf9-e3ef-41b4-879e-9551ab99aa29" file="properties/${env}.properties" />
        <secure-properties:config name="Secure_Properties_Config" doc:name="Secure Properties Config" doc:id="0bbad3ed-42bb-4e13-bc88-e9c1fc6d21f4" file="properties/${env}.properties" key="${enc.key}"  >
    </secure-properties:config>
</code>```

I have encrypted using the value password with AES algorithm. However its not able to decrypt those values with the config provided.

答:
First you are loading the same properties file using configuration-properties and then again using secure-properties. Only load the file once using secure-properties if it contains secure-properties.

Second, you need to use ${secure:myProp.someProp} syntax to read secure properties, rather than just ${myProp.someProp}

If you are using the same file for secure and non-secure properties, you still have to use ${secure:myProp.someProp} for the non-secure properties.

Therefore it is best practice to split your property files into ${env}.properties for non-secure and ${env}-secure.properties for secure properties. Then you can use configuration-properties ${env}.properties and secure-properties for ${env}-secure.properties.

If you are getting a specific error, please update the question with details.

Body:
This is my config  where i have defined my properties file ie dev.properties which has some encrypted values. I have defined my secure property placeholder but its not working

<global-property doc:name="Global Property" doc:id="7080a89f-d39c-485d-99c4-b35337ab62c4" name="env" value="dev" />
    <global-property doc:name="Global Property" doc:id="5d1fb026-a34f-490f-9b50-7a9bcb5cdf83" name="enc.key" value="password" />
    <configuration-properties doc:name="Configuration properties"
        doc:id="7448fcf9-e3ef-41b4-879e-9551ab99aa29" file="properties/${env}.properties" />
        <secure-properties:config name="Secure_Properties_Config" doc:name="Secure Properties Config" doc:id="0bbad3ed-42bb-4e13-bc88-e9c1fc6d21f4" file="properties/${env}.properties" key="${enc.key}"  >
    </secure-properties:config>

I have encrypted using the value password with AES algorithm. However its not able to decrypt those values with the config provided.


问:
Grouping elements close together
I'm trying to figure out a solid way of grouping elements together that a value is next in the list.

The data I have is this

let values = [
    ChartDataEntry(x: 0.0, y: -13.0),
    ChartDataEntry(x: 1.0, y: -13.0),
    ChartDataEntry(x: 2.0, y: 0.68),
    ChartDataEntry(x: 3.0, y: -13.0),
    ChartDataEntry(x: 4.0, y: 1.7),
    ChartDataEntry(x: 5.0, y: 0.5),
    ChartDataEntry(x: 6.0, y: 10.0)
]
```

<p>I'm trying to group it so it's more like this</p>

<pre class="lang-swift prettyprint-override"><code>let values = [
    [
        ChartDataEntry(x: 0.0, y: -13.0),
        ChartDataEntry(x: 1.0, y: -13.0),
        ChartDataEntry(x: 3.0, y: -13.0)
    ],
    [
        ChartDataEntry(x: 2.0, y: 0.68)
    ],
    [
        ChartDataEntry(x: 4.0, y: 1.7),
        ChartDataEntry(x: 5.0, y: 0.5),
        ChartDataEntry(x: 6.0, y: -10.0)
    ]
]
</code>```

Essentially the grouping I am trying to achieve is elements that x elements that have a value above -13.0 go together and elements below -13 go together. The tricky part is grouping by the x value.

The goal is to group values by the x value that are next to each other.

x: 2.0 is next to 3.0, but it's -13, so it doesnt belong in the same group, but if you look at 4.0, 5.0, & 6.0, they would all get grouped together as they have a value greater than -13 consecutively

I hope this makes sense.

答:
I simple solution I found to achieve this is with with reduce function. If anyone has any other cleaner more concise approaches, I'm all ears.

let grouped = values.filter({ $0.y != -13 }).reduce([[ChartDataEntry]]()) { result, item in
    var result = result
    if let lastX = result.last?.last?.x, item.x - 1.0 == lastX {
        let lastIndex = result.count - 1
         result[lastIndex].append(item)
    } else {
        result.append([item])
    }
    return result
}
```

Title: Grouping elements close together

Body:
I'm trying to figure out a solid way of grouping elements together that a value is next in the list.

The data I have is this

let values = [
    ChartDataEntry(x: 0.0, y: -13.0),
    ChartDataEntry(x: 1.0, y: -13.0),
    ChartDataEntry(x: 2.0, y: 0.68),
    ChartDataEntry(x: 3.0, y: -13.0),
    ChartDataEntry(x: 4.0, y: 1.7),
    ChartDataEntry(x: 5.0, y: 0.5),
    ChartDataEntry(x: 6.0, y: 10.0)
]

I'm trying to group it so it's more like this

let values = [
    [
        ChartDataEntry(x: 0.0, y: -13.0),
        ChartDataEntry(x: 1.0, y: -13.0),
        ChartDataEntry(x: 3.0, y: -13.0)
    ],
    [
        ChartDataEntry(x: 2.0, y: 0.68)
    ],
    [
        ChartDataEntry(x: 4.0, y: 1.7),
        ChartDataEntry(x: 5.0, y: 0.5),
        ChartDataEntry(x: 6.0, y: -10.0)
    ]
]

Essentially the grouping I am trying to achieve is elements that x elements that have a value above -13.0 go together and elements below -13 go together. The tricky part is grouping by the x value.

The goal is to group values by the x value that are next to each other.

x: 2.0 is next to 3.0, but it's -13, so it doesnt belong in the same group, but if you look at 4.0, 5.0, & 6.0, they would all get grouped together as they have a value greater than -13 consecutively

I hope this makes sense.


问:
What kind of contention that flink LeaderElectionService needs to handle?
Flink has the following comment in LeaderElectionService.java

https://github.com/apache/flink/blob/master/flink-runtime/src/main/java/org/apache/flink/runtime/leaderelection/LeaderElectionService.java#L26

What kind of contention does this class intent to handle?

```<code> * Interface for a service which allows to elect a leader among
   a group of contenders.
 * Prior to using this service, it has to be started calling
   the start method. The start method
 * takes the contender as a parameter. If there are multiple
   contenders, then each contender has
 * to instantiate its own leader election service.
</code>```

答:
As of Flink 1.8, there are two classes that implement LeaderContender interface.
JobManagerRunner and WebMonitorEndpoint need high availability, and need a LeaderElectionService.

```<code>public class JobManagerRunner implements LeaderContender,
                     OnCompletionActions, AutoCloseableAsync {...

public class WebMonitorEndpoint<T extends RestfulGateway>
    extends RestServerEndpoint implements LeaderContender, JsonArchivist {...
</code>```

Body:
Flink has the following comment in LeaderElectionService.java

https://github.com/apache/flink/blob/master/flink-runtime/src/main/java/org/apache/flink/runtime/leaderelection/LeaderElectionService.java#L26

What kind of contention does this class intent to handle?

 * Interface for a service which allows to elect a leader among
   a group of contenders.
 * Prior to using this service, it has to be started calling
   the start method. The start method
 * takes the contender as a parameter. If there are multiple
   contenders, then each contender has
 * to instantiate its own leader election service.

Body:
As of Flink 1.8, there are two classes that implement LeaderContender interface.
JobManagerRunner and WebMonitorEndpoint need high availability, and need a LeaderElectionService.

public class JobManagerRunner implements LeaderContender,
                     OnCompletionActions, AutoCloseableAsync {...

public class WebMonitorEndpoint<T extends RestfulGateway>
    extends RestServerEndpoint implements LeaderContender, JsonArchivist {...


问:
Finding keyword +1 and making new column
Goals:

1) locate word next to keyword (e.g brca)

2) create a new column with this word

Background:

1) I have a list l in which I make into a dataframe df and extract the word brca from it using the following code:

```<code>l = ['carcinoma brca positive completion mastectomy',
     'clinical brca gene mutation',
     'carcinoma brca positive chemotherapy']
df = pd.DataFrame(l, columns=['Text'])
df['Gene'] = df['Text'].str.extract(r"(brca)")
</code>```

Output:

```<code>                                                Text    Gene
0   breast invasive lobular carcinoma brca positiv...   brca
1   clinical history brca gene mutation . gross de...   brca
2   left breast invasive ductal carcinoma brca pos...   brca
</code>```

Problem:

However, I am now trying to find the word next to the word brca for each row and create a new column.

Desired Output:

```<code>                                                Text    Gene  NextWord
0   breast invasive lobular carcinoma brca positiv...   brca  positive
1   clinical history brca gene mutation . gross de...   brca  gene
2   left breast invasive ductal carcinoma brca pos...   brca  positive
</code>```

I have looked python pandas dataframe words in context: get 3 words before and after and PANDAS Finding the exact word and before word in a column of string and append that new column in python (pandas) column but they do not quite work for me.

Question:

How do I accomplish my goals?

答:
Use:

```<code>import pandas as pd

l = ['carcinoma brca positive completion mastectomy',
     'clinical brca gene mutation',
     'carcinoma brca positive chemotherapy']
df = pd.DataFrame(l, columns=['Text'])

df['NextWord'] = df['Text'].str.extract(r"(?<=brca)(.+?) ")
print(df)
</code>```

Output:

```<code>                                            Text   NextWord
0  carcinoma brca positive completion mastectomy   positive
1                    clinical brca gene mutation       gene
2           carcinoma brca positive chemotherapy   positive
</code>```

Body:
Goals:

1) locate word next to keyword (e.g brca)

2) create a new column with this word

Background:

1) I have a list l in which I make into a dataframe df and extract the word brca from it using the following code:

l = ['carcinoma brca positive completion mastectomy',
     'clinical brca gene mutation',
     'carcinoma brca positive chemotherapy']
df = pd.DataFrame(l, columns=['Text'])
df['Gene'] = df['Text'].str.extract(r"(brca)")

Output:

                                                Text    Gene
0   breast invasive lobular carcinoma brca positiv...   brca
1   clinical history brca gene mutation . gross de...   brca
2   left breast invasive ductal carcinoma brca pos...   brca

Problem:

However, I am now trying to find the word next to the word brca for each row and create a new column.

Desired Output:

                                                Text    Gene  NextWord
0   breast invasive lobular carcinoma brca positiv...   brca  positive
1   clinical history brca gene mutation . gross de...   brca  gene
2   left breast invasive ductal carcinoma brca pos...   brca  positive

I have looked python pandas dataframe words in context: get 3 words before and after and PANDAS Finding the exact word and before word in a column of string and append that new column in python (pandas) column but they do not quite work for me.

Question:

How do I accomplish my goals?

Body:
Use:

import pandas as pd

l = ['carcinoma brca positive completion mastectomy',
     'clinical brca gene mutation',
     'carcinoma brca positive chemotherapy']
df = pd.DataFrame(l, columns=['Text'])

df['NextWord'] = df['Text'].str.extract(r"(?<=brca)(.+?) ")
print(df)

Output:

                                            Text   NextWord
0  carcinoma brca positive completion mastectomy   positive
1                    clinical brca gene mutation       gene
2           carcinoma brca positive chemotherapy   positive


问:
How to refer slot element from its slotted element in lit-element?
I have a component named 'stack-item' which have a slot , its html will look like this

```<code><div>
<div>1<div>
<div class='slot-style'><slot></slot></div>
</div>
</code>```

I have used this component like this

```<code><stack-item>
   <another-component></another-component>
</stack-item>
</code>```

From 'another-component' how do i get the element reference for class ='slot-style' for calculating the slot width and other properties ?

I wrote a workaround

```<code>let slotElement =this.shadowRoot.host.parentElement.shadowRoot.querySelector('slot').parentElement;
</code>```

but is there a clean way of achieving this?

答:
I don't know if this can be considered dramatically simpler, but the scenario you give indicates that you already know the host component is stack-item and that component has a slot wrapper with the class name 'slot-style'. Given that you can obtain a reference like this (this works from within the component as well as the host document):</p>

```<code>let slotElement = document.querySelector("stack-item").shadowRoot.querySelector(".slot-style");
//display width
console.log(slotElement.clientWidth);
</code>```

Body:
I have a component named 'stack-item' which have a slot , its html will look like this

1

<slot></slot>

I have used this component like this

<stack-item>
   <another-component></another-component>
</stack-item>

From 'another-component' how do i get the element reference for class ='slot-style' for calculating the slot width and other properties ?

I wrote a workaround

let slotElement =this.shadowRoot.host.parentElement.shadowRoot.querySelector('slot').parentElement;

but is there a clean way of achieving this?

Body:
I don't know if this can be considered dramatically simpler, but the scenario you give indicates that you already know the host component is stack-item and that component has a slot wrapper with the class name 'slot-style'. Given that you can obtain a reference like this (this works from within the component as well as the host document):

let slotElement = document.querySelector("stack-item").shadowRoot.querySelector(".slot-style");
//display width
console.log(slotElement.clientWidth);


问:
Partial Keyword Search and Ranking
Using Django and Postgres, I have an investment holding model like so:

```<code>class Holding(BaseModel):
    name = models.CharField(max_length=255, db_index=True)
    symbol = models.CharField(max_length=16, db_index=True)
    fund_codes = ArrayField(models.CharField(max_length=16), blank=True, default=list)
    ...
</code>```

That contains a list of approximately 70k US/CAN equity, mutual funds.  I want to build an autocomplete search function that prioritizes 1) ranking of exact match of the symbol or fund_codes, followed by 2) Near matches on the symbol, then 3) Full text search of holding name.

If I have a search vector that adds more weight to the symbol and fund_codes:

```<code>from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank
from django.db.models import F, Func, Value

vector = SearchVector('name', weight='D') + \
         SearchVector('symbol', weight='A') + \
         SearchVector(Func(F('fund_codes'), Value(' '), function='array_to_string'), weight='A')
</code>```

Then, searching 'MA'

```<code>Investment.objects \
    .annotate(document=vector, rank=SearchRank(vector, query)) \
    .filter(document__icontains='MA') \
    .order_by('-rank') \
    .values_list('name', 'fund_codes', 'symbol', 'rank',)
</code>```

Doesn't give the results I need.  I need MA (Mastercard) as top listing, Then MAS (Masco Corp), etc... Then listings containing 'MA' in the name field.

I've also looked at overriding SearchQuery with:

```<code>class MySearchQuery(SearchQuery):
    def as_sql(self, compiler, connection):
        params = [self.value]
        if self.config:
            config_sql, config_params = compiler.compile(self.config)
            template = 'to_tsquery({}::regconfig, %s)'.format(config_sql)
            params = config_params + [self.value]
        else:
            template = 'to_tsquery(%s)'
        if self.invert:
            template = '!!({})'.format(template)
        return template, params
</code>```

But still not getting results I need. Any suggestions on how I should approach search functionality in this use case?  Perhaps concatenate an exact search query  and a full-text search query?

答:
What you need is to pass in normalization parameter. This will give higher ranking to names that are exact match. Raw query looks like following:

```<code>SELECT id, name, symbol, func_codes,
ts_rank_cd(to_tsvector(func_codes), to_tsquery('MA'), 2 ) as rank
FROM Holding
ORDER BY rank DESC
LIMIT 100;
</code>```

Notice that I passed in a normalization parameter https://www.postgresql.org/docs/current/textsearch-controls.html#TEXTSEARCH-RANKING

How to do it in Django?

I believe that django doesn't yet support passing normalization yet. I see a open ticket for it, but its 2 years old. Maybe no one has worked on it yet.

https://code.djangoproject.com/ticket/28194

You can use raw query for now. See official documentation on how:
https://docs.djangoproject.com/en/2.2/topics/db/sql/

Title: Partial Keyword Search and Ranking

Body:
Using Django and Postgres, I have an investment holding model like so:

class Holding(BaseModel):
    name = models.CharField(max_length=255, db_index=True)
    symbol = models.CharField(max_length=16, db_index=True)
    fund_codes = ArrayField(models.CharField(max_length=16), blank=True, default=list)
    ...

That contains a list of approximately 70k US/CAN equity, mutual funds.  I want to build an autocomplete search function that prioritizes 1) ranking of exact match of the symbol or fund_codes, followed by 2) Near matches on the symbol, then 3) Full text search of holding name.

If I have a search vector that adds more weight to the symbol and fund_codes:

from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank
from django.db.models import F, Func, Value

vector = SearchVector('name', weight='D') + \
         SearchVector('symbol', weight='A') + \
         SearchVector(Func(F('fund_codes'), Value(' '), function='array_to_string'), weight='A')

Then, searching 'MA'

Investment.objects \
    .annotate(document=vector, rank=SearchRank(vector, query)) \
    .filter(document__icontains='MA') \
    .order_by('-rank') \
    .values_list('name', 'fund_codes', 'symbol', 'rank',)

Doesn't give the results I need.  I need MA (Mastercard) as top listing, Then MAS (Masco Corp), etc... Then listings containing 'MA' in the name field.

I've also looked at overriding SearchQuery with:

class MySearchQuery(SearchQuery):
    def as_sql(self, compiler, connection):
        params = [self.value]
        if self.config:
            config_sql, config_params = compiler.compile(self.config)
            template = 'to_tsquery({}::regconfig, %s)'.format(config_sql)
            params = config_params + [self.value]
        else:
            template = 'to_tsquery(%s)'
        if self.invert:
            template = '!!({})'.format(template)
        return template, params

But still not getting results I need. Any suggestions on how I should approach search functionality in this use case?  Perhaps concatenate an exact search query  and a full-text search query?

Body:
What you need is to pass in normalization parameter. This will give higher ranking to names that are exact match. Raw query looks like following:

SELECT id, name, symbol, func_codes,
ts_rank_cd(to_tsvector(func_codes), to_tsquery('MA'), 2 ) as rank
FROM Holding
ORDER BY rank DESC
LIMIT 100;

Notice that I passed in a normalization parameter https://www.postgresql.org/docs/current/textsearch-controls.html#TEXTSEARCH-RANKING

How to do it in Django?

I believe that django doesn't yet support passing normalization yet. I see a open ticket for it, but its 2 years old. Maybe no one has worked on it yet.

https://code.djangoproject.com/ticket/28194

You can use raw query for now. See official documentation on how:
https://docs.djangoproject.com/en/2.2/topics/db/sql/


问:
How to get an correspondent id through a model on rails console
I've trying to get the simple situation:

I have a Model called Company, inside Company I have companies and I have the following object: "state_id". I want to find the related companies that contain some id.

This is the only path that I can get the state_id. So, I am doing:

```<code>Company.all.each do |comp|
     comp.address.city.state_id
end
</code>```

It works! But when I do:

```<code>Company.all.each do |comp|
     comp.address.city.state_id = 27
     #or comp.address.city.state_id(27)
end
</code>```

it doesn't return the right data

I know that it simple, but unfortunately, I didn't getting the right output.

Thanks a lot!

答:
Try</p>

```<code>Company.joins(address: :city).where(cities: {state_id: 27})
</code>```

Body:
I've trying to get the simple situation:

I have a Model called Company, inside Company I have companies and I have the following object: "state_id". I want to find the related companies that contain some id.

This is the only path that I can get the state_id. So, I am doing:

Company.all.each do |comp|
     comp.address.city.state_id
end

It works! But when I do:

Company.all.each do |comp|
     comp.address.city.state_id = 27
     #or comp.address.city.state_id(27)
end

it doesn't return the right data

I know that it simple, but unfortunately, I didn't getting the right output.

Thanks a lot!

Body:
Try

Company.joins(address: :city).where(cities: {state_id: 27})


问:
Slow v-model for buefy input, v-model.lazy not working either
I have an a couple of input boxes that connect to data via v-model when a GO button is fired in my buefy form that is connected to my buefy data table.

the rows in my table can be 2000 to 3000, and my pagination cannot be less than 250 per page.

I tried using v-model.lazy but it seems like that doesn't work on b-input(buefy input field).

Now the problem is that the initial fill of the inputs isn't slow at all, but when the table is full and the user tries to edit the input fields there is a lag on the fields.

When I set the pagination to 50 results per page there is no lag, but my problem is that i can't have 50 results I must have 250 per page.

Can anyone think of a solution for this in Vue?

答:
So figured out that v-model.lazy wont work for custom components (seems like Vue limits it for custom components), that being said you would need to have :value + @change.native

and an example is below:

```<code>:value="data"
@change.native="data = $event.target.value"
</code>```

Body:
So figured out that v-model.lazy wont work for custom components (seems like Vue limits it for custom components), that being said you would need to have :value + @change.native

and an example is below:

:value="data"
@change.native="data = $event.target.value"


问:
The "chunk" argument must be one of type string or Buffer. Received type object
I am trying to run the command to run my ionic 3 Command prompt. I used cordova fcm plugin.

ionic cordova run android

ERROR:

The "chunk" argument must be one of type string or Buffer. Received type object

Ionic:

ionic (Ionic CLI)  : 4.10.1 (/usr/local/lib/node_modules/ionic)

  Ionic Framework    : ionic-angular 3.6.0    @ionic/app-scripts : 2.1.4

Cordova:

cordova (Cordova CLI) : 8.1.2 (cordova-lib@8.1.1)    Cordova
  Platforms     : android 7.1.4    Cordova Plugins       : no
  whitelisted plugins (25 plugins total)

System:

NodeJS : v10.15.1
  (/Users/sivakumarv/.nvm/versions/node/v10.15.1/bin/node)    npm    :
  6.4.1    OS     : macOS High Sierra    Xcode  : Xcode 10.1 Build version 10B61

Environment Variables:

ANDROID_HOME : C:\Users\pkhon\AppData\Local\Android\Sdk

答:
There is a bug in the plugin, to solve this: go to:

plugins/cordova-plugin-fcm/scripts/fcm_config_files_process.js

Now change the file like this:

```<code>// change
var strings = fs.readFileSync("platforms/android/res/values/strings.xml").toString();
// to
var strings = fs.readFileSync("platforms/android/app/src/main/res/values/strings.xml").toString();

// AND

//change
fs.writeFileSync("platforms/android/res/values/strings.xml", strings);

//to
fs.writeFileSync("platforms/android/app/src/main/res/values/strings.xml", strings);
</code>```

After that, copy the google-services.json file to the following directories:

platforms/android/google-services.json

platforms/android/app/google-services.json

For more information, you can check this bug here

Body:
There is a bug in the plugin, to solve this: go to:

plugins/cordova-plugin-fcm/scripts/fcm_config_files_process.js

Now change the file like this:

// change
var strings = fs.readFileSync("platforms/android/res/values/strings.xml").toString();
// to
var strings = fs.readFileSync("platforms/android/app/src/main/res/values/strings.xml").toString();

// AND

//change
fs.writeFileSync("platforms/android/res/values/strings.xml", strings);

//to
fs.writeFileSync("platforms/android/app/src/main/res/values/strings.xml", strings);

After that, copy the google-services.json file to the following directories:

platforms/android/google-services.json

platforms/android/app/google-services.json

For more information, you can check this bug here


问:
R ggplot custom label axis ticks with other variable
When labelling axis ticks I'd like to add other information from the dataframe in parentheses. For example, using code snippet below I'd like to automatically include the information on Area in parentheses next to the label X. In other words, the label might say 'Chicago (45)' instead of just 'Chicago'. I know I can do this manually by setting labels in scale_x_discrete. However, can I do this automatically? My dataset has a large number of entries so I would like to avoid doing this manually.

```<code>dataset <- data.frame(Area = sample(c(NA, 1:100), 3, rep = TRUE),
                      Y = rnorm(3), X = c("Chicago","New York", "Orlando"))
ggplot(dataset, aes(X, Y)) + geom_point()
</code>```

答:
You can build a new column with your desired ticks labels:

```<code>library(dyplr)
library(stringr)
library(ggplot2)
dataset = dataset %>% mutate(label = str_c(X, " (", Area, ")"))
</code>```

Then use the column label in the aesthetics

```<code>ggplot(dataset, aes(label, Y)) + geom_point()
</code>```

Body:
When labelling axis ticks I'd like to add other information from the dataframe in parentheses. For example, using code snippet below I'd like to automatically include the information on Area in parentheses next to the label X. In other words, the label might say 'Chicago (45)' instead of just 'Chicago'. I know I can do this manually by setting labels in scale_x_discrete. However, can I do this automatically? My dataset has a large number of entries so I would like to avoid doing this manually.

dataset <- data.frame(Area = sample(c(NA, 1:100), 3, rep = TRUE),
                      Y = rnorm(3), X = c("Chicago","New York", "Orlando"))
ggplot(dataset, aes(X, Y)) + geom_point()

Body:
You can build a new column with your desired ticks labels:

library(dyplr)
library(stringr)
library(ggplot2)
dataset = dataset %>% mutate(label = str_c(X, " (", Area, ")"))

Then use the column label in the aesthetics

ggplot(dataset, aes(label, Y)) + geom_point()


问:
How to make a while loop throughout entire code. (Python)
I'm currently making a text-based game about walking through an abandoned house, and finding items to ward of monsters and all of that. I want a while loop system where if your health reaches below 0 (health=20), then the code ends by saying "You died to (insert event here)". I'm new to coding with python, so I'm not entirely sure how to code that.

I've tried setting up a while loop with an if statement that checks if the health is below 0. This is near the top of the code below the variables and above the functions

```<code>health = 20 #variable

while ( health < 0):
    print("You died to [insert event here]\n")
    break
</code>```

Instead of it doing anything, it completely ignores it. I'm not sure how I would place the code into the function because I still need to use "global" to import variables into them. If you know the answer to this problem, or you know an alternative code to solve this problem, please tell me. Again I'm new to python so please explain in a way I can understand.

答:
I don't think this is a good place to explain in detail why that code doesn't work. Instead, consider the following game as an example:

def adventure_around(pit_limit = 5, initial_position = 0):
    position = initial_position
    lived = False
    print("Try not to die, noob!")
    while position < pit_limit:
        direction = input("Which way would you like to go? [n,s,e,w, or q]:")
        if direction not in ['n', 's', 'e', 'w', 'q']:
            print("Please choose a direction.")
            continue
        if direction == "n":
            position += 1
        if direction == 's':
            position -= 1
        if direction == "q":
            print("Coward! (You lived, though.)")
            lived = True
            break
    if not lived:
        print("You fell into a pit and died while bravely wandering about! RIP")

adventure_around()
```

Feed that to your python interpreter and play around with it. (Minutes of fun!) Then study the code. (Googling isn't cheating, either!) What does the while keyword do? How is information from the outside code conveyed to the function? Why are there two ways to exit the while loop? Was that a good idea? Is there a better way to update the position? Did lived need to be initialized? Why or why not? Go ahead and modify it to suit your purpose, if you can. While I don't think a global health variable is the best way to go, try to change the code so that it uses the global keyword to reference a global health variable. What error messages did you get while getting that to work? How would you manage that in a much larger game with tens, hundreds, or thousands of files?

Good hunting!

Body:
I'm currently making a text-based game about walking through an abandoned house, and finding items to ward of monsters and all of that. I want a while loop system where if your health reaches below 0 (health=20), then the code ends by saying "You died to (insert event here)". I'm new to coding with python, so I'm not entirely sure how to code that.

I've tried setting up a while loop with an if statement that checks if the health is below 0. This is near the top of the code below the variables and above the functions

health = 20 #variable

while ( health < 0):
    print("You died to [insert event here]\n")
    break

Instead of it doing anything, it completely ignores it. I'm not sure how I would place the code into the function because I still need to use "global" to import variables into them. If you know the answer to this problem, or you know an alternative code to solve this problem, please tell me. Again I'm new to python so please explain in a way I can understand.

Body:
I don't think this is a good place to explain in detail why that code doesn't work. Instead, consider the following game as an example:

def adventure_around(pit_limit = 5, initial_position = 0):
    position = initial_position
    lived = False
    print("Try not to die, noob!")
    while position < pit_limit:
        direction = input("Which way would you like to go? [n,s,e,w, or q]:")
        if direction not in ['n', 's', 'e', 'w', 'q']:
            print("Please choose a direction.")
            continue
        if direction == "n":
            position += 1
        if direction == 's':
            position -= 1
        if direction == "q":
            print("Coward! (You lived, though.)")
            lived = True
            break
    if not lived:
        print("You fell into a pit and died while bravely wandering about! RIP")

adventure_around()

Feed that to your python interpreter and play around with it. (Minutes of fun!) Then study the code. (Googling isn't cheating, either!) What does the while keyword do? How is information from the outside code conveyed to the function? Why are there two ways to exit the while loop? Was that a good idea? Is there a better way to update the position? Did lived need to be initialized? Why or why not? Go ahead and modify it to suit your purpose, if you can. While I don't think a global health variable is the best way to go, try to change the code so that it uses the global keyword to reference a global health variable. What error messages did you get while getting that to work? How would you manage that in a much larger game with tens, hundreds, or thousands of files?

Good hunting!


问:
Trying to turn multiple spaces into one space
I am trying to print back the user's input with the modification that anytime there are more than one spaces in a row in the user input, the output will only show one space.  For instance, if I wrote

```<code>Hey,     I love Stack Overflow
</code>```

I would want my output to be

```<code>Hey, I love Stack Overflow
</code>```

I saw some answers on this but they weren't in C and weren't following my logic which I feel like could work.

```<code>int c, count;
c = 0;
count = 0;
printf("Enter a string of characters, please: ");
while ((c = getchar()) != EOF)
{
    if (c == ' ')
        ++count;
    if ((count == 1) && c == ' ')
        continue;
    else
        count--;
    putchar(c);
}
</code>```

The output when I run this code, though, does not remove excess spaces, it just outputs the exact same message.

答:
This is untested but shows the approach I'd take.</p>

```<code>int inSpace = 0;

printf("Enter a string of characters, please: ");
while ((c = getchar()) != EOF)
{
    if (c == ' ')
    {
        if (!inSpace)
        {
            putchar(c);
            inSpace = 1;
        }
    }
    else
    {
        putchar(c);
        inSpace = 0;
    }
}
</code>```

Body:
I am trying to print back the user's input with the modification that anytime there are more than one spaces in a row in the user input, the output will only show one space.  For instance, if I wrote

Hey,     I love Stack Overflow

I would want my output to be

Hey, I love Stack Overflow

I saw some answers on this but they weren't in C and weren't following my logic which I feel like could work.

int c, count;
c = 0;
count = 0;
printf("Enter a string of characters, please: ");
while ((c = getchar()) != EOF)
{
    if (c == ' ')
        ++count;
    if ((count == 1) && c == ' ')
        continue;
    else
        count--;
    putchar(c);
}

The output when I run this code, though, does not remove excess spaces, it just outputs the exact same message.

Body:
This is untested but shows the approach I'd take.

int inSpace = 0;

printf("Enter a string of characters, please: ");
while ((c = getchar()) != EOF)
{
    if (c == ' ')
    {
        if (!inSpace)
        {
            putchar(c);
            inSpace = 1;
        }
    }
    else
    {
        putchar(c);
        inSpace = 0;
    }
}


问:
Parsing using decodable when value of a dictionary is an array of strings
I want to parse the json file below, but I keep getting the following error:

typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array but found a dictionary instead.", underlyingError: nil))

I have looked on stackoverflow, but they didn't seem to help as I don't see other json files that returns a dictionary value that is an array of strings. Any ideas?

```<code>//JSON file
{
 pugs: [
   "http://27.media.tumblr.com/tumblr_lqfwfyZuyS1qiyqyfo1_500.jpg",
   "http://30.media.tumblr.com/tumblr_liic7bdmRF1qcipjro1_500.jpg",
   "http://29.media.tumblr.com/tumblr_ll3xdp73DQ1qb08qmo1_500.jpg",
   "http://29.media.tumblr.com/tumblr_lht5uy6khS1qed3e3o1_500.jpg",
   "http://26.media.tumblr.com/tumblr_lrqnevtBvM1qb08qmo1_400.jpg",
   "http://26.media.tumblr.com/tumblr_ll90kwmMJw1qzj3syo1_500.jpg",
   "http://26.media.tumblr.com/tumblr_ll7aoxHGfW1qb08qmo1_500.jpg",
   "http://24.media.tumblr.com/tumblr_lk27smb4sR1qzj3syo1_500.jpg",
   "http://26.media.tumblr.com/tumblr_lil8a1m1YM1qzj3syo1_500.jpg",
   "http://27.media.tumblr.com/tumblr_liy1xfY9G71qftdfxo1_500.jpg"
  ]
}
</code>```

```<code>//Data Model
class PugList: Codable {
    var pugs: [Pug]
    var likes: Int
}

class Pug: Codable {
    var images: [String]
}
</code>```

答:
You don't need the Pug class. Change pugs to [String].

BTW - use struct instead of class unless you have a good reason to use a class.

Body:
I want to parse the json file below, but I keep getting the following error:

typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array but found a dictionary instead.", underlyingError: nil))

I have looked on stackoverflow, but they didn't seem to help as I don't see other json files that returns a dictionary value that is an array of strings. Any ideas?

//JSON file
{
 pugs: [
   "http://27.media.tumblr.com/tumblr_lqfwfyZuyS1qiyqyfo1_500.jpg",
   "http://30.media.tumblr.com/tumblr_liic7bdmRF1qcipjro1_500.jpg",
   "http://29.media.tumblr.com/tumblr_ll3xdp73DQ1qb08qmo1_500.jpg",
   "http://29.media.tumblr.com/tumblr_lht5uy6khS1qed3e3o1_500.jpg",
   "http://26.media.tumblr.com/tumblr_lrqnevtBvM1qb08qmo1_400.jpg",
   "http://26.media.tumblr.com/tumblr_ll90kwmMJw1qzj3syo1_500.jpg",
   "http://26.media.tumblr.com/tumblr_ll7aoxHGfW1qb08qmo1_500.jpg",
   "http://24.media.tumblr.com/tumblr_lk27smb4sR1qzj3syo1_500.jpg",
   "http://26.media.tumblr.com/tumblr_lil8a1m1YM1qzj3syo1_500.jpg",
   "http://27.media.tumblr.com/tumblr_liy1xfY9G71qftdfxo1_500.jpg"
  ]
}

//Data Model
class PugList: Codable {
    var pugs: [Pug]
    var likes: Int
}

class Pug: Codable {
    var images: [String]
}


问:
Invalid hook call. Hooks can only be called inside of the body of a function component when apply style to class base component with material-ui
I am just started to learn reactjs using material-ui but getting this error when apply style to my component. My code:

```<code>const useStyles = makeStyles(theme => ({
    root: {
        flexGrow: 1,
    },
    menuButton: {
        marginRight: theme.spacing(2),
    },
    title: {
        flexGrow: 1,
    },
}));

class NavMenu extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            isOpen: false
        };
    }
    render() {
        const classes = useStyles();
        return (
            <div className={classes.root}>
                <AppBar position="static">
                    <Toolbar>
                        <IconButton
                            edge="start"
                            className={classes.menuButton}
                            color="inherit"
                            aria-label="Menu"
                        >
                            <MenuIcon />
                        </IconButton>
                        <Typography
                            variant="h6"
                            className={classes.title}
                        >
                            News
                        </Typography>
                        <Button color="inherit">Login</Button>
                    </Toolbar>
                </AppBar>
            </div>
        );
    }
}
export default NavMenu;
</code>```

and this is Error:

答:
material-ui makeStyles function only works inside function components, as it uses the new React Hooks APIs inside.

You have two options:

Convert your class component to a functional component.

Use a Higher Order Component as in material-ui docs

I personally recommend the first approach, as this is becoming the new standard in React development.
This tutorial may help you get started with functional components
and check the docs for React Hooks

Body:
I am just started to learn reactjs using material-ui but getting this error when apply style to my component. My code:

const useStyles = makeStyles(theme => ({
    root: {
        flexGrow: 1,
    },
    menuButton: {
        marginRight: theme.spacing(2),
    },
    title: {
        flexGrow: 1,
    },
}));

class NavMenu extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            isOpen: false
        };
    }
    render() {
        const classes = useStyles();
        return (

                <AppBar position="static">
                    <Toolbar>
                        <IconButton
                            edge="start"
                            className={classes.menuButton}
                            color="inherit"
                            aria-label="Menu"
                        >
                            <MenuIcon />
                        </IconButton>
                        <Typography
                            variant="h6"
                            className={classes.title}
                        >
                            News
                        </Typography>
                        <Button color="inherit">Login</Button>
                    </Toolbar>
                </AppBar>

        );
    }
}
export default NavMenu;

and this is Error:


问:
Using Bitwise Operators in C
I am a beginner to C language.I have a code for towers of hanoi but can someone explain me what are these bitwise operators doing ie if value of i is 1 what will be the source and target output value ?</p>

```<code>source = (i & i-1) % 3;
target = ((i | i-1) + 1) % 3;
</code>```

答:
Good answer above, here is a high-level approach:

i == 1:
source: (1 & 0). Are both of these values true or >= 1? No they are not. So the overall result is 0, 0 % 3 = 0.

target: ((1 | 0) + 1) % 3.
(1 | 0) evaluates to 1(true) since one of the two values on the sides of the | operator are 1, so now we have (1 + 1). so then it follows we have 2 % 3 = 2.

Source: 0, target: 2

Title: Using Bitwise Operators in C

Body:
I am a beginner to C language.I have a code for towers of hanoi but can someone explain me what are these bitwise operators doing ie if value of i is 1 what will be the source and target output value ?

source = (i & i-1) % 3;
target = ((i | i-1) + 1) % 3;


问:
Javascript: how can I access a class property to a function inside nested object
I'm working with javascript classes and there's something I want to do but I don't know how. First of all, this is my class:

```<code>class Company {
  constructor (options) {
    this.employee = options.employee;
    this.algorithm = "AZ1";
  }
}
</code>```

Now, employee is an object which has another object nested inside of it and that final object contains a series of functions:

```<code>employee {
  code {
    generate [Function: generate]
    alter [Function: alter]
  }
}
</code>```

Now, my problem is that I want to access the algorithm from any of these functions?

Btw; I'm trying to do so from an object created with that class:

```<code>const myCompany = new Company({ employee });
</code>```

So I want to access the algorithm property from the generate function within myCompany.

答:
You should be able to access the algorithm like this: myCompany.employee.code.generate(myCompany.algorithm)

EDIT: It wasn't clear from your original question that you're trying to keep the algorithm private to the class. Something like this might work:

class Company {
  constructor (options) {
    this.employee = options.employee;
    this.algorithm = "AZ1";
  }

  generateEmployee = () => {
    this.employee.code.generate(this.algorithm);
  }
}
```

<p>This would give you a <code>myCompany.generateEmployee</code> method that the caller could use without passing in the algorithm.</p>

<p>Note that this syntax will only work if you're using a transpiler like Babel. If not, you can use this syntax (so your method has the right <code>this</code> context):</p>

<pre class="lang-js prettyprint-override"><code>class Company {
  constructor (options) {
    this.employee = options.employee;
    this.algorithm = "AZ1";
    this.generateEmployee = this.generateEmployee.bind(this);
  }

  generateEmployee() {
    this.employee.code.generate(this.algorithm);
  }
}
</code>```

Body:
I'm working with javascript classes and there's something I want to do but I don't know how. First of all, this is my class:

class Company {
  constructor (options) {
    this.employee = options.employee;
    this.algorithm = "AZ1";
  }
}

Now, employee is an object which has another object nested inside of it and that final object contains a series of functions:

employee {
  code {
    generate [Function: generate]
    alter [Function: alter]
  }
}

Now, my problem is that I want to access the algorithm from any of these functions?

Btw; I'm trying to do so from an object created with that class:

const myCompany = new Company({ employee });

So I want to access the algorithm property from the generate function within myCompany.

Body:
You should be able to access the algorithm like this: myCompany.employee.code.generate(myCompany.algorithm)

EDIT: It wasn't clear from your original question that you're trying to keep the algorithm private to the class. Something like this might work:

class Company {
  constructor (options) {
    this.employee = options.employee;
    this.algorithm = "AZ1";
  }

  generateEmployee = () => {
    this.employee.code.generate(this.algorithm);
  }
}

This would give you a myCompany.generateEmployee method that the caller could use without passing in the algorithm.

Note that this syntax will only work if you're using a transpiler like Babel. If not, you can use this syntax (so your method has the right this context):

class Company {
  constructor (options) {
    this.employee = options.employee;
    this.algorithm = "AZ1";
    this.generateEmployee = this.generateEmployee.bind(this);
  }

  generateEmployee() {
    this.employee.code.generate(this.algorithm);
  }
}


问:
EF core Access list through Include
I have a Model named as Blog:

```<code>public class Blog
    {
        [Key]
        public int blogId { get; set; }
        [Required]
        public string blogTitle { get; set; }
        public string imagePath { get; set; }
        [Required, DataType(DataType.Html)]
        public string blogDescription { get; set; }
        [DataType(DataType.DateTime)]
        public DateTime blogDateTime { get; set; }
        [Required]
        public bool isPublished { get; set; }

        [Required]
        public BlogCategory blogCategory { get; set; }
        public List<Comments> blogComments { get; set; }
    }
</code>```

And another model Comment:

```<code>public class Comments
    {
        [Key]
        public int authorId { get; set; }
        [Required]
        public string commentAuthor { get; set; }
        [DataType(DataType.Date)]
        public DateTime commentDate { get; set; }
        public bool isHidden { get; set; }
        [Required, DataType(DataType.EmailAddress)]
        public string commentAuthorEmail { get; set; }
        [Required]
        public string commentDescription { get; set; }
        public Blog Blog { get; set; }
    }
</code>```

In the blogs controller I want to access all the comments where isHidden = false

What I have tried is:

```<code>var blog = await _context.Blog
           .Include(cat => cat.blogCategory)
           .Include(comments => comments.blogComments.Any(c => !c.isHidden))
           .FirstOrDefaultAsync(m => m.blogId == id);
</code>```

But all I am getting exception is

```<code>An unhandled exception occurred while processing the request.
InvalidOperationException: The Include property lambda expression 'comments => comments.blogComments.Find(c => Not(c.isHidden))' is invalid. The expression should represent a property access: 't => t.MyProperty'. To target navigations declared on derived types, specify an explicitly typed lambda parameter of the target type, E.g. '(Derived d) => d.MyProperty'.
</code>```

How can I solve this problem?

答:
```<code>var blog = await _context.Blog
       .Include(cat => cat.blogCategory)
       .Include(comments => comments.blogComments)
       .Select(x=> {
            x.blogCategory = x.blogCategory;
            x.blogComments = x.blogComments.Where(y=>!y.IsHidden)
       })
       .FirstOrDefaultAsync(m => m.blogId == id);
</code>```

Since it's a IQueryable this will  have the same result. It will only return the comments where the blog comments are hidden. This is considering that you want to return all the blogs and not just the blogs whose comments are hidden.

Title: EF core Access list through Include

Body:
I have a Model named as Blog:

public class Blog
    {
        [Key]
        public int blogId { get; set; }
        [Required]
        public string blogTitle { get; set; }
        public string imagePath { get; set; }
        [Required, DataType(DataType.Html)]
        public string blogDescription { get; set; }
        [DataType(DataType.DateTime)]
        public DateTime blogDateTime { get; set; }
        [Required]
        public bool isPublished { get; set; }

        [Required]
        public BlogCategory blogCategory { get; set; }
        public List<Comments> blogComments { get; set; }
    }

And another model Comment:

public class Comments
    {
        [Key]
        public int authorId { get; set; }
        [Required]
        public string commentAuthor { get; set; }
        [DataType(DataType.Date)]
        public DateTime commentDate { get; set; }
        public bool isHidden { get; set; }
        [Required, DataType(DataType.EmailAddress)]
        public string commentAuthorEmail { get; set; }
        [Required]
        public string commentDescription { get; set; }
        public Blog Blog { get; set; }
    }

In the blogs controller I want to access all the comments where isHidden = false

What I have tried is:

var blog = await _context.Blog
           .Include(cat => cat.blogCategory)
           .Include(comments => comments.blogComments.Any(c => !c.isHidden))
           .FirstOrDefaultAsync(m => m.blogId == id);

But all I am getting exception is

An unhandled exception occurred while processing the request.
InvalidOperationException: The Include property lambda expression 'comments => comments.blogComments.Find(c => Not(c.isHidden))' is invalid. The expression should represent a property access: 't => t.MyProperty'. To target navigations declared on derived types, specify an explicitly typed lambda parameter of the target type, E.g. '(Derived d) => d.MyProperty'.

How can I solve this problem?

Body:
var blog = await _context.Blog
       .Include(cat => cat.blogCategory)
       .Include(comments => comments.blogComments)
       .Select(x=> {
            x.blogCategory = x.blogCategory;
            x.blogComments = x.blogComments.Where(y=>!y.IsHidden)
       })
       .FirstOrDefaultAsync(m => m.blogId == id);

Since it's a IQueryable this will  have the same result. It will only return the comments where the blog comments are hidden. This is considering that you want to return all the blogs and not just the blogs whose comments are hidden.


问:
Difficulty installing RSpec on Windows
I'm trying to get started with RSpec. I already had Ruby 1.8.7 installed on my Windows 7 machine.

So I typed gem install rspec and that seemed to work. But if I type spec in the command line, the command is not found. My path currently includes the bin folder in my RUBY_HOME.

If I look into the C:\Users\Eric\.gem\specs\rubygems.org%80\quick\Marshal.4.8 directory, I do see four RSpec files such as rspec-core-2.5.0.gemspec. Nevertheless, the spec command fails even in this directory.

What needs to be done to install RSpec correctly? It would seem like a path issue, but I have been unable to find a directory where the spec command works, so I can't figure what to add to my path.

答: On Windows, try this bundle exec rspec spec

Title: Difficulty installing RSpec on Windows


问:
kafka rest api - connection refused
I'm using kafka_2.11.-0.9.0.1.

First, I started the zookeeper & kafka (as explained here) with:

```<code>bin/zookeeper-server-start.sh config/zookeeper.properties
</code>```

and then:

```<code>bin/kafka-server-start.sh config/server.properties
</code>```

Now I'm trying to GET some info from the REST API (as explained here) with:

```<code>[itay@localhost general]$ wget http://127.0.0.1:8083/connectors
--2016-04-27 10:44:26--  http://127.0.0.1:8083/connectors
Connecting to 127.0.0.1:8083... failed: Connection refused.
</code>```

Kafka & zookeeper are up & running, My application is connected with them and sending/receiving messages.

what did I miss? any suggestions? (I didn't find instruction of firing up web-server/port.. )

Thanks

答:
Yes, alone Zookeeper and Kafka doesn't work. Need to run Kafka connect too.

Run Kafka Connect in Distributed Mode :

```<code>bin/connect-distributed.sh config/connect-distributed.properties
</code>```

and hit http://localhost:8083/connectors/

It worked for me.

Title: kafka rest api - connection refused

Body:
I'm using kafka_2.11.-0.9.0.1.

First, I started the zookeeper & kafka (as explained here) with:

bin/zookeeper-server-start.sh config/zookeeper.properties

and then:

bin/kafka-server-start.sh config/server.properties

Now I'm trying to GET some info from the REST API (as explained here) with:

[itay@localhost general]$ wget http://127.0.0.1:8083/connectors
--2016-04-27 10:44:26--  http://127.0.0.1:8083/connectors
Connecting to 127.0.0.1:8083... failed: Connection refused.

Kafka & zookeeper are up & running, My application is connected with them and sending/receiving messages.

what did I miss? any suggestions? (I didn't find instruction of firing up web-server/port.. )

Thanks

Body:
Yes, alone Zookeeper and Kafka doesn't work. Need to run Kafka connect too.

Run Kafka Connect in Distributed Mode :

bin/connect-distributed.sh config/connect-distributed.properties

and hit http://localhost:8083/connectors/

It worked for me.


问:
How to start / stop Java process in the Command Prompt?
I have Java 1.8.0 running in Windows. How can i start/stop this process in the Command Prompt?</p>

答:
not mine, check if it helps</p>

```<code>taskkill /f /im jqs.exe
taskkill /f /im javaw.exe
taskkill /f /im java.exe
</code>```

Body:
not mine, check if it helps

taskkill /f /im jqs.exe
taskkill /f /im javaw.exe
taskkill /f /im java.exe


问:
Predict Value Not In Data Set
Given that I have training and testing data, that may be missing a logical sequential number. Is it possible to infer a value that wasn't present?

For example:
Training / Testing Data have values 1,2,3,4,5...7,8,9,10 specified for the label.

Is it possible that based on the data model, that it could predict a result of 6 even though there has been no instance of such an occurrence within the training or testing data?

I am new to Machine Learning and have read about Supervised / Non-supervised learning. It's been difficult to pinpoint an explicit answer, as it's quite hard to get the correct terminology to an area I am unfamiliar with.

Would be be best to create a arbitrary row in the data set that contains a label value that is not present?

Using ML.net.

Apologies if this is a simple question.

Thanks

答:
The way I solved, or in fact mitigated, the lack of a value was to do the following. For each input data type that requires to be sequential - no gaps, I only used data / rows from my data set where there was an unbroken sequence, across all entries.

Given the following: 0,1,2,3,4,5,6,7,9

I only used data that conformed to the largest available sequence across all entries. 0 - 7. This could lead to some lost data for the training models, but as the data is fairly consistent, there are few omissions.

Title: Predict Value Not In Data Set


问:
building Python from source with zlib support
When building Python 3.2.3 from source on Ubuntu 12.04, the zlib module is not available.

I downloaded the official source distribution from python.org, and attempted to build and install it with the following commands.

```<code>tar xfa Python3.2.3.tar.bz2
cd Python-3.2.3
./configure --prefix=/opt/python3.2
make
sudo make install
</code>```

The make command output includes the following.

```<code>Python build finished, but the necessary bits to build these modules were not found:
_curses            _curses_panel      _dbm
_gdbm              _sqlite3           _ssl
_tkinter           bz2                readline
zlib
</code>```

After running make install and starting the interpreter, the zlib module cannot be imported.

I confirmed that the zlib1g-dev package is installed on my system.

I also found this similar question, which suggests adding the --with-zlib flag to the ./configure command.  However, that returns an error that it is an unrecognized option and has no effect.

答:
For anyone having the same error on macOS Mojave, this is the easiest solution for installing/linking the header files:

```<code>open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg
</code>```

Then just build Python again as usual (also works with pyenv builds).

Body:
When building Python 3.2.3 from source on Ubuntu 12.04, the zlib module is not available.

I downloaded the official source distribution from python.org, and attempted to build and install it with the following commands.

tar xfa Python3.2.3.tar.bz2
cd Python-3.2.3
./configure --prefix=/opt/python3.2
make
sudo make install

The make command output includes the following.

Python build finished, but the necessary bits to build these modules were not found:
_curses            _curses_panel      _dbm
_gdbm              _sqlite3           _ssl
_tkinter           bz2                readline
zlib

After running make install and starting the interpreter, the zlib module cannot be imported.

I confirmed that the zlib1g-dev package is installed on my system.

I also found this similar question, which suggests adding the --with-zlib flag to the ./configure command.  However, that returns an error that it is an unrecognized option and has no effect.

Body:
For anyone having the same error on macOS Mojave, this is the easiest solution for installing/linking the header files:

open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg

Then just build Python again as usual (also works with pyenv builds).


问:
fetching data and adding title to Json object
I would like to add title to my JSON object, the structure I wish to achieve is:

```<code>{
"posts": [
    {
        "title": "put title here",
        "upvotes": 1234,
        "score": 1000,
        "num_comments": 100,
        "created": "16.05.2019 12:12",
    },
]
}
</code>```

I was able to fetch data and put it into array of 26 elements, everything is fine but I wish to somehow add this "posts:" to be above whole rest, here is my code:

```<code>fetch("https://www.reddit.com/r/funny.json")
.then(resp => resp.json()
.then(async res => {
   let posts = await res.data.children.map(el => {
    let title = el.data.title;
    let upvote = el.data.ups;
    let score = el.data.score;
    let comments = el.data.num_comments;
    let created = el.data.created;
    const allPosts = {title, upvote, score, comments, created}
    postList.push(allPosts)
    return postList
})
console.log(posts);

    return posts
})
</code>```

答:
```<code>  fetch("https://www.reddit.com/r/funny.json")
  .then(resp => resp.json())
  .then(async res => {
    console.log(res);
    let posts = await res.data.children.map(el => {
      let title = el.data.title;
      let upvote = el.data.ups;
      let score = el.data.score;
      let comments = el.data.num_comments;
      let created = el.data.created;
      const allPosts = { title, upvote, score, comments, created };
      let postList = [];
      postList.push(allPosts);
      return postList;
    });
    console.log({"posts": posts});

    return {"posts": posts};
  });
</code>```

Body:
I would like to add title to my JSON object, the structure I wish to achieve is:

{
"posts": [
    {
        "title": "put title here",
        "upvotes": 1234,
        "score": 1000,
        "num_comments": 100,
        "created": "16.05.2019 12:12",
    },
]
}

I was able to fetch data and put it into array of 26 elements, everything is fine but I wish to somehow add this "posts:" to be above whole rest, here is my code:

fetch("https://www.reddit.com/r/funny.json")
.then(resp => resp.json()
.then(async res => {
   let posts = await res.data.children.map(el => {
    let title = el.data.title;
    let upvote = el.data.ups;
    let score = el.data.score;
    let comments = el.data.num_comments;
    let created = el.data.created;
    const allPosts = {title, upvote, score, comments, created}
    postList.push(allPosts)
    return postList
})
console.log(posts);

    return posts
})


问:
Testing rx throws error on scheduler init
Unit test terminates if I write var scheduler = TestScheduler(initialClock: 0)

my imports

```<code>import XCTest
import RxTest
</code>```

with error message

failed to demangle superclass of TestScheduler from mangled name '7RxSwift20VirtualTimeSchedulerCy0A4Test0fecD9ConverterVG'

pod versions

```<code>pod 'RxBlocking', '~> 5'
pod 'RxTest', '~> 5'
</code>```

答:
This is a bug of the Cocoapods + XCode 10.2 platform.

Statement from XCode 10.2 RC notes about known issues:

```<code>Linking against a static Swift library might create a binary with missing
type metadata because the object files that define the metadata inside the
static archive are mistakenly considered unused. (47598583)

This can manifest as a Swift runtime error with a message such as:
“failed to demangle superclass of MyClass from mangled name ‘<mangled name>’”.

Workaround: If you can rebuild the static library, try building it with whole module
optimization enabled.
Otherwise, add -all_load to the linker flags in the client binary to
ensure all object files are linked into it.
</code>```

This thread and this solution should help you get rid of it.

Body:
Unit test terminates if I write var scheduler = TestScheduler(initialClock: 0)

my imports

import XCTest
import RxTest

with error message

failed to demangle superclass of TestScheduler from mangled name '7RxSwift20VirtualTimeSchedulerCy0A4Test0fecD9ConverterVG'

pod versions

pod 'RxBlocking', '~> 5'
pod 'RxTest', '~> 5'

Body:
This is a bug of the Cocoapods + XCode 10.2 platform.

Statement from XCode 10.2 RC notes about known issues:

Linking against a static Swift library might create a binary with missing
type metadata because the object files that define the metadata inside the
static archive are mistakenly considered unused. (47598583)

This can manifest as a Swift runtime error with a message such as:
“failed to demangle superclass of MyClass from mangled name ‘<mangled name>’”.

Workaround: If you can rebuild the static library, try building it with whole module
optimization enabled.
Otherwise, add -all_load to the linker flags in the client binary to
ensure all object files are linked into it.

This thread and this solution should help you get rid of it.


答:
Ctrl + C in the command.

If you need exit elegantly, you need program for it. You can refer to apache's library for more.

Title: How to start / stop Java process in the Command Prompt?

Body: I have Java 1.8.0 running in Windows. How can i start/stop this process in the Command Prompt?


问:
How to het Source port no. in decimal form
I got the source port No. in hexa decimal no from the for loop as show in the  code.. The Source port is 01 bb in this case.. I want to show it as 443 i.e. decimal how to show that...

```<code>printf("\nSource Port Number: ");
a = packet[34];
b = packet[35];
char num[20];
int num3;

strcpy (num, a);
strcat (num, b);
printf("Hexadecimal string %s\n", num);
sscanf(num,"%x", &num3);
printf("Decimal number %d\n", num3);
</code>```

34 and 35 no. packet show the source port no. I have seen it from wireshark...I am getting 01 bb as the answer but i want to get it in decimal...

答:
You try to convert the port number which consists of data bytes '0x01 0xbb' captured by libpcap to integer value using sscanf. This won't work because sscanf expects the port number as character string "01bb". If you check the return value of sscanf i would expect it is '0' which means nothing happened because of expected data to format mismatch.
I think you could setup the port number just by combining the data bytes '0x01' and '0xbb' using bitwise or and shift (Important: byte order).</p>

Body:
I got the source port No. in hexa decimal no from the for loop as show in the  code.. The Source port is 01 bb in this case.. I want to show it as 443 i.e. decimal how to show that...

printf("\nSource Port Number: ");
a = packet[34];
b = packet[35];
char num[20];
int num3;

strcpy (num, a);
strcat (num, b);
printf("Hexadecimal string %s\n", num);
sscanf(num,"%x", &num3);
printf("Decimal number %d\n", num3);

34 and 35 no. packet show the source port no. I have seen it from wireshark...I am getting 01 bb as the answer but i want to get it in decimal...


问:
is there a way to prevent a form to show multiple times in #c?
so I have this program, and I want to prevent it from opening multiple times but can seem to get the hang of it =/

```<code>    private void button1_Click(object sender, EventArgs e)
    {

        if (forge.Checked)
        {
            successfully_injected openForm = new successfully_injected();
            openForm.Show();
            this.Close();
        }
        else if (!forge.Checked)
        {
            select_option openForm = new select_option();
            openForm.Show();
        }

    }
</code>```

I only want to be able to click the button once and then it stops showing more windows, but the result I get right now is that I can click it and it will just keep opening windows every time I click so yeh =/

答:
give the owner to the new window

```<code>    successfully_injected openForm = new successfully_injected();
        Owner = openForm;
        Hide();
        openForm.Show();
</code>```

Now the new window has the owner and you can simply close it and it works

Body:
so I have this program, and I want to prevent it from opening multiple times but can seem to get the hang of it =/

    private void button1_Click(object sender, EventArgs e)
    {

        if (forge.Checked)
        {
            successfully_injected openForm = new successfully_injected();
            openForm.Show();
            this.Close();
        }
        else if (!forge.Checked)
        {
            select_option openForm = new select_option();
            openForm.Show();
        }

    }

I only want to be able to click the button once and then it stops showing more windows, but the result I get right now is that I can click it and it will just keep opening windows every time I click so yeh =/

Body:
give the owner to the new window

    successfully_injected openForm = new successfully_injected();
        Owner = openForm;
        Hide();
        openForm.Show();

Now the new window has the owner and you can simply close it and it works


问:
Encrypt and Decrypt password on different computers
Currently I am writing a little script which stores an encrypted password in a config file and decrypt it when it needs to use the password. I know that this is not the safest way and it should only make it "unreadable" for people. I have encrypted my password with:

```<code>echo PasswordToEncrypt | openssl enc -aes-256-cbc -a -salt -pass pass:PasswordForEncryptAndDecrypt
</code>```

Now I got my encrypted password and tried to decrypt it and it works fine. But after I tried to decrypt the password on a different computer, it can't decrypt it anymore. Also if I encrypt the password again it looks different than the encrypted password on the first computer.

My question is: Is there any method to encrypt and decrypt a password with openssl with the same result on different computers? So that I can encrypt a password in Comouter A and decrypt it in Computer B?

答:
If you encrypt a file and decrypt it on another computer, the decrypted data will be the same. Encryption becomes useless otherwise. I think you see different output because you forgot to give the -md option.

To encrypt:

```<code>$ echo TEST | openssl enc -aes-256-cbc -md md5 -salt -pass pass:my_password > enc.bin
</code>```

And decrypt:

```<code>$ cat enc.bin | openssl enc -d -aes-256-cbc  -md md5 -pass pass:my_password
TEST
</code>```

Just to give you the option to use keys:

```<code>$ openssl genrsa -out key.priv 4096
$ openssl rsa -in key.priv -pubout -out key.pub
$ echo TEST | openssl enc -aes-256-cbc -md sha256 -salt -pass file:key.pub > tmp.bin
$ cat tmp.bin | openssl enc -d -aes-256-cbc -md sha256 -pass file:key.pub > tmp.txt
TEST
</code>```

Body:
Currently I am writing a little script which stores an encrypted password in a config file and decrypt it when it needs to use the password. I know that this is not the safest way and it should only make it "unreadable" for people. I have encrypted my password with:

echo PasswordToEncrypt | openssl enc -aes-256-cbc -a -salt -pass pass:PasswordForEncryptAndDecrypt

Now I got my encrypted password and tried to decrypt it and it works fine. But after I tried to decrypt the password on a different computer, it can't decrypt it anymore. Also if I encrypt the password again it looks different than the encrypted password on the first computer.

My question is: Is there any method to encrypt and decrypt a password with openssl with the same result on different computers? So that I can encrypt a password in Comouter A and decrypt it in Computer B?

Body:
If you encrypt a file and decrypt it on another computer, the decrypted data will be the same. Encryption becomes useless otherwise. I think you see different output because you forgot to give the -md option.

To encrypt:

$ echo TEST | openssl enc -aes-256-cbc -md md5 -salt -pass pass:my_password > enc.bin

And decrypt:

$ cat enc.bin | openssl enc -d -aes-256-cbc  -md md5 -pass pass:my_password
TEST

Just to give you the option to use keys:

$ openssl genrsa -out key.priv 4096
$ openssl rsa -in key.priv -pubout -out key.pub
$ echo TEST | openssl enc -aes-256-cbc -md sha256 -salt -pass file:key.pub > tmp.bin
$ cat tmp.bin | openssl enc -d -aes-256-cbc -md sha256 -pass file:key.pub > tmp.txt
TEST


问:
How to Minimize any open application (AHK example of the desired result)
I'm trying to write a piece of code to minimize an application based on the text displaying in the title bar (any application running on the system, not just my own). I've been able to perform the task in an AHK but the desired result isn't ideal and I'd definitely rather it be an active piece of my application then an external one. The AHK is:

```<code>#Persistent
#SingleInstance

SetTimer, NoCashierOrHEM, 300
return

NoCashierOrHEM:
IfWinExist , Cashier
WinClose , Cashier
IfWinExist , Hold’em + Omaha Manager
WinMinimize , Hold’em + Omaha Manager
return
</code>```

Which will minimize any window that has the title bar "Hold'em + Omaha Manager" and close any window that has the title "Cashier". What direction should I be looking in for solving this problem in C#?

答:
You will need to use a combination of Windows API functions, like

GetClassName

GetWindowsText

GetWindow

and write a method that goes through open forms and searches for the text.

An example in vb6 can be found here.
I believe that code should be fairly easy to convert to c#.

Body:
I'm trying to write a piece of code to minimize an application based on the text displaying in the title bar (any application running on the system, not just my own). I've been able to perform the task in an AHK but the desired result isn't ideal and I'd definitely rather it be an active piece of my application then an external one. The AHK is:

#Persistent
#SingleInstance

SetTimer, NoCashierOrHEM, 300
return

NoCashierOrHEM:
IfWinExist , Cashier
WinClose , Cashier
IfWinExist , Hold’em + Omaha Manager
WinMinimize , Hold’em + Omaha Manager
return

Which will minimize any window that has the title bar "Hold'em + Omaha Manager" and close any window that has the title "Cashier". What direction should I be looking in for solving this problem in C#?


问:
Trying to turn multiple spaces into one space
I am trying to print back the user's input with the modification that anytime there are more than one spaces in a row in the user input, the output will only show one space.  For instance, if I wrote

```<code>Hey,     I love Stack Overflow
</code>```

I would want my output to be

```<code>Hey, I love Stack Overflow
</code>```

I saw some answers on this but they weren't in C and weren't following my logic which I feel like could work.

```<code>int c, count;
c = 0;
count = 0;
printf("Enter a string of characters, please: ");
while ((c = getchar()) != EOF)
{
    if (c == ' ')
        ++count;
    if ((count == 1) && c == ' ')
        continue;
    else
        count--;
    putchar(c);
}
</code>```

The output when I run this code, though, does not remove excess spaces, it just outputs the exact same message.

答:
Your code is very close.

Use count as a flag and set to either 1 or 0 instead of using ++ and --.

```<code>#include <stdio.h>

int main ( void) {
    int c = 0, count = 1;//1 to skip leading spaces
    printf ( "Enter a string of characters, please: ");
    while ( ( c = getchar()) != EOF) {
        if ( c == ' ') {//c is a space
            if ( count == 1 && c == ' ') {//skip extra spaces
                continue;
            }
            //if count is 0 execution will fall through and putchar will be called
            count = 1;//flag to skip extra spaces
        }
        else {//c is not a space
            count = 0;//flag to print a space
        }
        putchar ( c);
    }
    return 0;
}
</code>```

Body:
I am trying to print back the user's input with the modification that anytime there are more than one spaces in a row in the user input, the output will only show one space.  For instance, if I wrote

Hey,     I love Stack Overflow

I would want my output to be

Hey, I love Stack Overflow

I saw some answers on this but they weren't in C and weren't following my logic which I feel like could work.

int c, count;
c = 0;
count = 0;
printf("Enter a string of characters, please: ");
while ((c = getchar()) != EOF)
{
    if (c == ' ')
        ++count;
    if ((count == 1) && c == ' ')
        continue;
    else
        count--;
    putchar(c);
}

The output when I run this code, though, does not remove excess spaces, it just outputs the exact same message.

Body:
Your code is very close.

Use count as a flag and set to either 1 or 0 instead of using ++ and --.

#include <stdio.h>

int main ( void) {
    int c = 0, count = 1;//1 to skip leading spaces
    printf ( "Enter a string of characters, please: ");
    while ( ( c = getchar()) != EOF) {
        if ( c == ' ') {//c is a space
            if ( count == 1 && c == ' ') {//skip extra spaces
                continue;
            }
            //if count is 0 execution will fall through and putchar will be called
            count = 1;//flag to skip extra spaces
        }
        else {//c is not a space
            count = 0;//flag to print a space
        }
        putchar ( c);
    }
    return 0;
}


问:
Sending an email with Python from a Protonmail account, SMTP library
I am using apple mail app with protonmail-I have the bridge app. (MacOS and Windows install here; linux here.)

After activating the bridge app, I tried to send an email with python by using smtp library and it does not work. Here is the code which I tried to run and failed me:

```<code>import smtplib

server = smtplib.SMTP("127.0.0.1", portnumber)
server.login("mymail@protonmail.com", "my password")
server.sendmail(
    "mymail@protonmail.com",
    "receiver@protonmail.com",
    "hello")
server.quit()
</code>```

The error message I receive:

smtplib.SMTPDataError: (554, b'Error: transaction failed, blame it on the weather: malformed MIME header line: 00')

答:
This might help..</p>

```<code>import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

port_number =1234
msg = MIMEMultipart()
msg['From'] = 'sender@protonmail.com'
msg['To'] = 'receiver@protonmail.com'
msg['Subject'] = 'My Test Mail '
message = 'This is the body of the mail'
msg.attach(MIMEText(message))
mailserver = smtplib.SMTP('localhost',port_number)
mailserver.login("sender@protonmail.com", "mypassword")
mailserver.sendmail('sender@protonmail.com','receiver@protonmail.com',msg.as_string())
mailserver.quit()
</code>```

Body:
I am using apple mail app with protonmail-I have the bridge app. (MacOS and Windows install here; linux here.)

After activating the bridge app, I tried to send an email with python by using smtp library and it does not work. Here is the code which I tried to run and failed me:

import smtplib

server = smtplib.SMTP("127.0.0.1", portnumber)
server.login("mymail@protonmail.com", "my password")
server.sendmail(
    "mymail@protonmail.com",
    "receiver@protonmail.com",
    "hello")
server.quit()

The error message I receive:

smtplib.SMTPDataError: (554, b'Error: transaction failed, blame it on the weather: malformed MIME header line: 00')

Body:
This might help..

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

port_number =1234
msg = MIMEMultipart()
msg['From'] = 'sender@protonmail.com'
msg['To'] = 'receiver@protonmail.com'
msg['Subject'] = 'My Test Mail '
message = 'This is the body of the mail'
msg.attach(MIMEText(message))
mailserver = smtplib.SMTP('localhost',port_number)
mailserver.login("sender@protonmail.com", "mypassword")
mailserver.sendmail('sender@protonmail.com','receiver@protonmail.com',msg.as_string())
mailserver.quit()


问:
How to get the base url in jsp?
Im creating a simple project by using jsp and servlet. I want to link the css in my jsp file. So any one can tell me the way to do this??</p>

答:
You just need to do:

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

provided that you have style.css file in folder "css" near your .jsp file. You don't need to know the base URL for that, this will work with any base URL that leads to your .jsp file.

Title: How to get the base url in jsp?

Body:
You just need to do:

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

provided that you have style.css file in folder "css" near your .jsp file. You don't need to know the base URL for that, this will work with any base URL that leads to your .jsp file.


问:
React Native - Focus a TextInput (Inside custom Component) that is inside of a Flat List element
I'm a React Native beginner and I'm working with a Flat List and custom Rows. Inside of each custom row, I have elements like Text, TextInput, and Button. The problem is that I need to press one of these buttons that enables and triggers a focus to the TextInput.

I tried implementing that with refs but everything freezes so I don't know how to do that correctly.

My constructor

```<code>class EditProfileScreen extends React.Component {
  constructor(props) {
    super(props);
    this._rowRefs = {}
  }
</code>```

My FlatList and MyCustomRow

```<code>_renderItem = ({item, index}) => {
    return (
      <MyCustomRow
                       fieldname={item.fieldname}
                       value={item.value}
                       isEditable={item.isEditable}
                       editFieldHandler={ this.editFieldHandler }
                       allowsEdition={item.allowsEdition}
                       ref={ref => { this._rowRefs[index] = ref}}
                      />
    )
  }

  _keyExtractor = (item, index) => index.toString();

  render() {
    return (
      <View style={styles.mainContainer}>
        <FlatList
          ref={this.flatListRef}
          style={styles.flatList}
          data={this.state.fields}
          renderItem={this._renderItem}
          keyExtractor= {this._keyExtractor}
          extraData={this.state.refresh}
        />
      </View>
    );
  }
</code>```

Trying to print the refs:

```<code>enableField(name) {
    console.log('Printing refs...')
    console.log(this._rowRefs) // the Button pressed freezes here
  }
</code>```

I expect to see what's inside of _rowRefs, but instead of that, the button just gets frozen and I never see that result in the console

答:
Try to give the key for each ref (not index)

```<code>ref={ref => { this._rowRefs['key1'] = ref}}
</code>```

and invoke focus action like this:

```<code>this._rowRefs['key1'].focus()
</code>```

Body:
I'm a React Native beginner and I'm working with a Flat List and custom Rows. Inside of each custom row, I have elements like Text, TextInput, and Button. The problem is that I need to press one of these buttons that enables and triggers a focus to the TextInput.

I tried implementing that with refs but everything freezes so I don't know how to do that correctly.

My constructor

class EditProfileScreen extends React.Component {
  constructor(props) {
    super(props);
    this._rowRefs = {}
  }

My FlatList and MyCustomRow

_renderItem = ({item, index}) => {
    return (
      <MyCustomRow
                       fieldname={item.fieldname}
                       value={item.value}
                       isEditable={item.isEditable}
                       editFieldHandler={ this.editFieldHandler }
                       allowsEdition={item.allowsEdition}
                       ref={ref => { this._rowRefs[index] = ref}}
                      />
    )
  }

  _keyExtractor = (item, index) => index.toString();

  render() {
    return (
      <View style={styles.mainContainer}>
        <FlatList
          ref={this.flatListRef}
          style={styles.flatList}
          data={this.state.fields}
          renderItem={this._renderItem}
          keyExtractor= {this._keyExtractor}
          extraData={this.state.refresh}
        />
      </View>
    );
  }

Trying to print the refs:

enableField(name) {
    console.log('Printing refs...')
    console.log(this._rowRefs) // the Button pressed freezes here
  }

I expect to see what's inside of _rowRefs, but instead of that, the button just gets frozen and I never see that result in the console

Body:
Try to give the key for each ref (not index)

ref={ref => { this._rowRefs['key1'] = ref}}

and invoke focus action like this:

this._rowRefs['key1'].focus()