问:
Svg to pdf converter for Qt project
I have multiple svg files and I wish to convert them in the PDF format. The problem is that I need to work with multiple text fonts and a simple QSvgRenderer is not enough.

For example:

My problem is that I need to integrate a library in my project that does not use external dependencies (just a library that can be used as a standalone entity).

The only library that can partially suit my needs is librsvg but I have no experience and I can not find a method to integrate it in a Qt project.

Can someone give me a few tips or can point me in the right direction?

EDIT

With something basic there is not a single font that made it to the right using QSvgRenderer:

```<code>  QSvgRenderer renderer;
  renderer.load((QString)"E:/TEXT4.svg");

  QPrinter printer;
  printer.setOutputFormat(QPrinter::PdfFormat);
  printer.setOutputFileName("E:/TEXT4.pdf");

  QPainter painter(&printer);
  renderer.render(&painter);
  painter.end();
</code>```

答:
Maybe a bit late, but had the same problem and found a solution using Qt only.
The problem in your case is you need to install the fonts manually and need a QApplication.
E.g.:

```<code>int main(int argc, char** argv)
{
    // A QApplication instance is necessary if fonts are used in the SVG
    QApplication app(argc, argv);

    int id = QFontDatabase::addApplicationFont(":/DejaVuSans.ttf");
    if (id != -1)
    {
        QStringList font_families = QFontDatabase::applicationFontFamilies(id);
        // This prints: DejaVu Sans
        for (const auto& item : font_families)
        {
            std::cout << item.toStdString() << std::endl;
        }
    }

    // Load your SVG
    QSvgRenderer renderer(QString("myimage.svg"));

    QPdfWriter pdfWriter(QString("mydoc.pdf"));
    pdfWriter.setPageSize(QPageSize(QPageSize::A4));
    QPainter painter(&pdfWriter);
    renderer.render(&painter);
}
</code>```

Also tested with multiple different font families and it worked.

Note: As far as I know, you cannot change the font name in Qt, so in the SVG font-family must match exactly the added font name. In this example, font-family:DejaVu Sans.

Title: Svg to pdf converter for Qt project

Body:
I have multiple svg files and I wish to convert them in the PDF format. The problem is that I need to work with multiple text fonts and a simple QSvgRenderer is not enough.

For example:

My problem is that I need to integrate a library in my project that does not use external dependencies (just a library that can be used as a standalone entity).

The only library that can partially suit my needs is librsvg but I have no experience and I can not find a method to integrate it in a Qt project.

Can someone give me a few tips or can point me in the right direction?

EDIT

With something basic there is not a single font that made it to the right using QSvgRenderer:

  QSvgRenderer renderer;
  renderer.load((QString)"E:/TEXT4.svg");

  QPrinter printer;
  printer.setOutputFormat(QPrinter::PdfFormat);
  printer.setOutputFileName("E:/TEXT4.pdf");

  QPainter painter(&printer);
  renderer.render(&painter);
  painter.end();

Body:
Maybe a bit late, but had the same problem and found a solution using Qt only.
The problem in your case is you need to install the fonts manually and need a QApplication.
E.g.:

int main(int argc, char** argv)
{
    // A QApplication instance is necessary if fonts are used in the SVG
    QApplication app(argc, argv);

    int id = QFontDatabase::addApplicationFont(":/DejaVuSans.ttf");
    if (id != -1)
    {
        QStringList font_families = QFontDatabase::applicationFontFamilies(id);
        // This prints: DejaVu Sans
        for (const auto& item : font_families)
        {
            std::cout << item.toStdString() << std::endl;
        }
    }

    // Load your SVG
    QSvgRenderer renderer(QString("myimage.svg"));

    QPdfWriter pdfWriter(QString("mydoc.pdf"));
    pdfWriter.setPageSize(QPageSize(QPageSize::A4));
    QPainter painter(&pdfWriter);
    renderer.render(&painter);
}

Also tested with multiple different font families and it worked.

Note: As far as I know, you cannot change the font name in Qt, so in the SVG font-family must match exactly the added font name. In this example, font-family:DejaVu Sans.


来源: stackexchange

问:
BlackBerry Device Date/Time Update Listener?
Is there a listener in RIM API which can detect that the user has changed the Date/Time settings of his Blackberry device ? I need to catch this event how could i do this ?</p>

答:
you can also try RealtimeClockListener</p>

```<code>public class MyApp extends UiApplication implements RealtimeClockListener
{
  public static void main(String[] args)
  {
    ...
  }

  public MyApp()
  {
    addRealtimeClockListener(this);
  }

  public void clockUpdated()
  {
    //it will call every minute
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
you can also try RealtimeClockListener

public class MyApp extends UiApplication implements RealtimeClockListener
{
  public static void main(String[] args)
  {
    ...
  }

  public MyApp()
  {
    addRealtimeClockListener(this);
  }

  public void clockUpdated()
  {
    //it will call every minute
  }
}


问:
HashiCorp Vault Database Secrets display Connection URL
Following:

https://www.vaultproject.io/docs/secrets/databases/mysql-maria/

I want to display connection_url or database host along with userpass when I query Vault via:

vault read database/creds/my-role

答:
if you don't mind me asking, could I ask why you need the connection_url. If it is to provide to an application for config you can potentially use Vault template?

https://www.vaultproject.io/docs/agent/template/

As the user2599522 said it is not possible directly with Vault but a simple bash script or template will do the trick. All depends on the use case for the best solution.

ContentLicense: CC BY-SA 4.0


问:
compare list values withina python dictionary
I think it is very basic, but I struggle to find a way to solve this.
In a python dictionary like below (where values are lists), how can I conveniently compare values of each key-value pair?
For example, how can I retrieve the key-value pairs where:

Elements of values are not repeated in values of other key-value pairs,

If the first element of the value present in other values, select the pair where the second element of the value in larger.

In other words, I need to get

```<code>"a": ["bc", "5", "0"]
"b": ["nc", "8", "5"]
</code>```

```<code>test_dict = {"a": ["bc", "5", "0"], "b": ["nc", "8", "5"], "c": ["bc", "3", "0"]}
</code>```

Any hint is appreciated.

答:
Made it into one-liner. It looks for the third element for the comparison too (not just the second).

It creates a dict twice. First with the first element as a key and then uses its values to generate the result.

```<code>dict({v[0]:(k,v) for v,k in sorted((v,k) for k,v in test_dict.items())}.values())
</code>```

Body:
I think it is very basic, but I struggle to find a way to solve this.
In a python dictionary like below (where values are lists), how can I conveniently compare values of each key-value pair?
For example, how can I retrieve the key-value pairs where:

Elements of values are not repeated in values of other key-value pairs,

If the first element of the value present in other values, select the pair where the second element of the value in larger.

In other words, I need to get

"a": ["bc", "5", "0"]
"b": ["nc", "8", "5"]

test_dict = {"a": ["bc", "5", "0"], "b": ["nc", "8", "5"], "c": ["bc", "3", "0"]}

Any hint is appreciated.

Body:
Made it into one-liner. It looks for the third element for the comparison too (not just the second).

It creates a dict twice. First with the first element as a key and then uses its values to generate the result.

dict({v[0]:(k,v) for v,k in sorted((v,k) for k,v in test_dict.items())}.values())


问:
Is it possible to use Cloud NAT with public GKE Cluster?
I have one public GKE cluster with 2 nodes and with that, 2 public external IPs. I want only one egress IP.

I want to use Cloud NAT for that. It seems it is possible.

An alias IP range assigned to the VM's network interface: Even if the
  network interface has an external IP address assigned to it, you can
  configure a Cloud NAT gateway to provide NAT for packets whose sources
  come from an alias IP range of the interface. An external IP address
  on an interface never performs one-to-one NAT for alias IP addresses.

I created a Cloud NAT but it is not working. I use the following commands to get the IP and it always returns one of the IPs of the nodes.

```<code>kubectl run -i --tty get-ip-address --image=dwdraju/alpine-curl-jq --restart=Never
</code>```

and

```<code>curl checkip.amazonaws.com
</code>```

My cluster has VPC native enabled.

答:
Please use the Private Kubernetes Cluster option. The nodes will only have internal IP addresses.

If you follow this guide, you will be able to achieve your desired configuration using Private clusters.

Body:
I have one public GKE cluster with 2 nodes and with that, 2 public external IPs. I want only one egress IP.

I want to use Cloud NAT for that. It seems it is possible.

An alias IP range assigned to the VM's network interface: Even if the
  network interface has an external IP address assigned to it, you can
  configure a Cloud NAT gateway to provide NAT for packets whose sources
  come from an alias IP range of the interface. An external IP address
  on an interface never performs one-to-one NAT for alias IP addresses.

I created a Cloud NAT but it is not working. I use the following commands to get the IP and it always returns one of the IPs of the nodes.

kubectl run -i --tty get-ip-address --image=dwdraju/alpine-curl-jq --restart=Never

and

curl checkip.amazonaws.com

My cluster has VPC native enabled.


问:
Increase banner width on mobile shopify
I created a page template for a page, using a banner + 2 products.

The issue is on mobile, where I can't make the banner wider. It stays with some margin left and right, making the image unapropriate for the user xp.

I tried using js to make it forcefully wider, but it kept the margin. I even made a function to get the viewport width and set the banner in px to it, with no results. Can anyone give me some light?

The classes below are premade by the theme creator.

Banner section:

```<code><section  class="parallax-banner parallax-slide slide parallax_effect--{{ section.settings.parallax_effect }}" id="slide-{{ section.id }}">
  <div id="bannerImg" class="bcg {% if section.settings.image == nil %}bcg-placeholder{% endif %}"
      {% if section.settings.parallax_effect %}
        style="background-image:url({% if section.settings.image != nil %}{{ section.settings.image | img_url: '1600x' }}{% else %}{{ 'placeholder.svg' | asset_url }}{% endif %})"
        data-bottom-top="background-position: 50% 200px;"
        data-top-bottom="background-position: 50% -200px;"
        data-anchor-target="#slide-{{ section.id }}"
      {% endif %}
      >
      {% if section.settings.link != blank and section.settings.button_label == blank %}
        <a href="{{ section.settings.link }}" class="full-link">
          {{ section.settings.link }}
        </a>
      {% endif %}
      <div class="hsContainer">
        <img src="{% if section.settings.image != nil %}{{ section.settings.image | img_url: '1600x' }}{% else %}{{ 'placeholder.svg' | asset_url }}{% endif %}" alt="{{ section.settings.image.alt | escape }}" class="hsContainer__image">
        <div class="hsContent">
          <div class="container">
            <div class="columns {% if section.settings.text_position == 'left' %} eight offset-by-one {% elsif section.settings.text_position == 'right' %} eight offset-by-eight {% else %} sixteen {% endif %} align_{{ section.settings.text_alignment }}">
              <div class="{{ section.settings.headline_animation }}">
                {% if section.settings.title != blank %}
... (unecessary code not pasted)
</code>```

Page template code:

```<code><div class="container main content main-wrapper">

  <div class="sixteen columns page clearfix">

    <div>
      {% include 'page-multi-column', content: page.content %}
        {% section 'aniversariante-img-overlay' %}
       {% section 'aniversariante-promocoes' %}
    </div>
  </div>
</div>

<script>
  var size = getViewportSize().w;
  console.log(size);

 document.getElementsByClassName("hsContainer")[0].style.width = size+"px !important";
 document.getElementsByClassName("hsContainer")[0].style = "margin: 0";

  function getViewportSize(w) {

    // Use the specified window or the current window if no argument
    w = w || window;

    // This works for all browsers except IE8 and before
    if (w.innerWidth != null) return { w: w.innerWidth, h: w.innerHeight };

    // For IE (or any browser) in Standards mode
    var d = w.document;
    if (document.compatMode == "CSS1Compat")
        return { w: d.documentElement.clientWidth,
           h: d.documentElement.clientHeight };

    // For browsers in Quirks mode
    return { w: d.body.clientWidth, h: d.body.clientHeight };

}
</script>
</code>```

Live page location: https://clubeporcao.com.br/pages/aniversariante

I already tried:

removing the classes, with result, but broking the page

removing the container class padding, with no result

putting width to % and px

setting margin to 0

getting into chrome inspect element and try to find where the padding/margin is being set

答:
Hacky solution:

```<code>#slide-aniversariante-img-overlay {
  width: 100vw;
  position: relative;
  left: 50%;
  transform: translateX(-50%);
}

</code>```

Explanation:

You want to make a child element of your .container (which has a fixed width) wider than this container. You know the width of you .container for a picked  breakpoint but you can't tell how much space is avaible at the left and right.

You can check it with JavaScript like you already tried, but then you are forced to add an event listener after resizing (because those values will change).

Above I've set the child width to 100vw (100% of the viewport width) - so it has a right width but we don't know the value of margin we should use.

We probably could use margin-left: calc( 100vw / 2 - Xpx); where X is the width of .container but instead, I've added position relative and move this slide to the middle width left: 50% - it is 50% of the parent element (if you turn off the transform you will see that the slide starts exactly in the middle of the window). transform: translateX(-50%) will set slide in the right place because it works on the child's width not parent's.

Caution:
For some zoom options, horizontal scroll can appear, you can wrap a banner in a separate section with overflow: hidden; (but if you could do this you probably would remove .container already) or add overflow-x: hidden; to the body.

Title: Increase banner width on mobile shopify

Body:
I created a page template for a page, using a banner + 2 products.

The issue is on mobile, where I can't make the banner wider. It stays with some margin left and right, making the image unapropriate for the user xp.

I tried using js to make it forcefully wider, but it kept the margin. I even made a function to get the viewport width and set the banner in px to it, with no results. Can anyone give me some light?

The classes below are premade by the theme creator.

Banner section:

  <div id="bannerImg" class="bcg {% if section.settings.image == nil %}bcg-placeholder{% endif %}"
      {% if section.settings.parallax_effect %}
        style="background-image:url({% if section.settings.image != nil %}{{ section.settings.image | img_url: '1600x' }}{% else %}{{ 'placeholder.svg' | asset_url }}{% endif %})"
        data-bottom-top="background-position: 50% 200px;"
        data-top-bottom="background-position: 50% -200px;"
        data-anchor-target="#slide-{{ section.id }}"
      {% endif %}
      >
      {% if section.settings.link != blank and section.settings.button_label == blank %}

          {{ section.settings.link }}

      {% endif %}

                {% if section.settings.title != blank %}
... (unecessary code not pasted)

Page template code:

      {% include 'page-multi-column', content: page.content %}
        {% section 'aniversariante-img-overlay' %}
       {% section 'aniversariante-promocoes' %}

Live page location: https://clubeporcao.com.br/pages/aniversariante

I already tried:

removing the classes, with result, but broking the page

removing the container class padding, with no result

putting width to % and px

setting margin to 0

getting into chrome inspect element and try to find where the padding/margin is being set

Body:
Hacky solution:

#slide-aniversariante-img-overlay {
  width: 100vw;
  position: relative;
  left: 50%;
  transform: translateX(-50%);
}

Explanation:

You want to make a child element of your .container (which has a fixed width) wider than this container. You know the width of you .container for a picked  breakpoint but you can't tell how much space is avaible at the left and right.

You can check it with JavaScript like you already tried, but then you are forced to add an event listener after resizing (because those values will change).

Above I've set the child width to 100vw (100% of the viewport width) - so it has a right width but we don't know the value of margin we should use.

We probably could use margin-left: calc( 100vw / 2 - Xpx); where X is the width of .container but instead, I've added position relative and move this slide to the middle width left: 50% - it is 50% of the parent element (if you turn off the transform you will see that the slide starts exactly in the middle of the window). transform: translateX(-50%) will set slide in the right place because it works on the child's width not parent's.

Caution:
For some zoom options, horizontal scroll can appear, you can wrap a banner in a separate section with overflow: hidden; (but if you could do this you probably would remove .container already) or add overflow-x: hidden; to the body.


问:
Get every tail faster with math/logic applied in numpy 1D array - to eliminate infinity
I have a 2D array in which I need each 'column' (axis=1) to be treated independently.  For each column (1D array) I need a function applied to each length tail of the 1D array, to provide an array of length N as follows.  How do I make it faster?  Perhaps by removing the for loop.  I was doing this with map/lambda/hstack until I hit a divide by zero error, which required the if/elif/else conditions to eliminate the march to infinity.

```<code>import numpy as np
x = np.random.rand(20,5)

def get_updown_array(loc_array):
    return np.array([updown(loc_array[x:]) for x in list(range(loc_array.shape[0]))])

def updown(local_array):
    sub_length = ((local_array.shape[0]) + 1) // 2 # to get the middle value when length is uneven
    a = local_array[:sub_length].mean() # first half mean
    b = local_array[-sub_length:].mean() # second half mean
    if not a == 0:
        return ( b - a ) / abs(a)
    elif not b == 0:
        return ( b - a ) / abs(( a + b ) / 2)
    else:
        return 0

result = np.apply_along_axis(get_updown_array, 0, x)
</code>```

It seems the if/else conditional logic eliminates the ability to apply the function across multiple values in one numpy dimension, all at the same time.

I looked at using vectorize, though it seems this would still require the for loop in the first function.

I looked at pandas.apply though it seems slower, and still requires a concatenate or
vstack/hstack afterward?

Cython was considered though this still leaves the inelegant for loop clunking away.

I tried np.where though this still
needs a for loop.

Is there a way to apply the math/logic to each length tail without the for loop?  What is the fastest approach? stackoverflow community.

答:
I would do something like this:

def updown(x):
    result = np.zeros_like(x)
    for i in range(len(x)):
        mid = (len(x)+1)//2
        a = x[:mid].mean(axis=0)
        b = x[-mid:].mean(axis=0)
        mask_a = a != 0
        mask_b = (a == 0) & (b != 0)
        result[i, mask_a] = (b[mask_a] - a[mask_a]) / abs(a[mask_a])
        result[i, mask_b] = (b[mask_b] - a[mask_b]) / abs((a[mask_b] + b[mask_b])/2)
        x = x[1:]
    return result
```

<p>In cases where a loop is fairly unavoidable like here, it is best to pre-allocate the result array (if the dimensions are known beforehand) and fill the values in the loop. This also has the advantage of allowing the default value of zero to be pre-filled.</p>

<p>There is no need for applying anything over the columns of <code>x</code> as the other operations (<code>mean</code> and arithmetic) can be easily applied to the chosen axis.</p>

<p>The conditional logic is achieved with masking.</p>

<p>You could also make use of the <code>out</code> and <code>where</code> keyword arguments of <code>np.divide</code>:</p>

<pre class="lang-py prettyprint-override"><code>def updown(x):
    result = np.zeros_like(x)
    for i in range(len(x)):
        mid = (len(x)+1)//2
        a = x[:mid].mean(axis=0)
        b = x[-mid:].mean(axis=0)
        np.divide(b - a, abs(a), out=result[i], where=(a != 0))
        np.divide(b - a, abs((a + b)/2), out=result[i], where=(a == 0) & (b != 0))
        x = x[1:]
    return result
</code>```

Let's see some performance comparisons (I've wrapped your entire original code in a function called updown_orig)

For dimensions (20, 5), we see only a factor of 2 improvement:

In []: %timeit updown_orig(np.random.rand(20, 5))
1 ms ± 13.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In []: %timeit updown(np.random.rand(20, 5))
508 µs ± 10.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
```

<p>Let's scale both dimensions by 10 (increasing the size of <code>x</code> by a factor of 100):</p>

<pre class="lang-py prettyprint-override"><code>In []: %timeit updown_orig(np.random.rand(200, 50))
96.4 ms ± 1.91 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
In []: %timeit updown(np.random.rand(200, 50))
5.84 ms ± 64 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code>```

Now the difference is a factor of about 16.5.

Body:
I have a 2D array in which I need each 'column' (axis=1) to be treated independently.  For each column (1D array) I need a function applied to each length tail of the 1D array, to provide an array of length N as follows.  How do I make it faster?  Perhaps by removing the for loop.  I was doing this with map/lambda/hstack until I hit a divide by zero error, which required the if/elif/else conditions to eliminate the march to infinity.

import numpy as np
x = np.random.rand(20,5)

def get_updown_array(loc_array):
    return np.array([updown(loc_array[x:]) for x in list(range(loc_array.shape[0]))])

def updown(local_array):
    sub_length = ((local_array.shape[0]) + 1) // 2 # to get the middle value when length is uneven
    a = local_array[:sub_length].mean() # first half mean
    b = local_array[-sub_length:].mean() # second half mean
    if not a == 0:
        return ( b - a ) / abs(a)
    elif not b == 0:
        return ( b - a ) / abs(( a + b ) / 2)
    else:
        return 0

result = np.apply_along_axis(get_updown_array, 0, x)

It seems the if/else conditional logic eliminates the ability to apply the function across multiple values in one numpy dimension, all at the same time.

I looked at using vectorize, though it seems this would still require the for loop in the first function.

I looked at pandas.apply though it seems slower, and still requires a concatenate or
vstack/hstack afterward?

Cython was considered though this still leaves the inelegant for loop clunking away.

I tried np.where though this still
needs a for loop.

Is there a way to apply the math/logic to each length tail without the for loop?  What is the fastest approach? stackoverflow community.

Body:
I would do something like this:

def updown(x):
    result = np.zeros_like(x)
    for i in range(len(x)):
        mid = (len(x)+1)//2
        a = x[:mid].mean(axis=0)
        b = x[-mid:].mean(axis=0)
        mask_a = a != 0
        mask_b = (a == 0) & (b != 0)
        result[i, mask_a] = (b[mask_a] - a[mask_a]) / abs(a[mask_a])
        result[i, mask_b] = (b[mask_b] - a[mask_b]) / abs((a[mask_b] + b[mask_b])/2)
        x = x[1:]
    return result

In cases where a loop is fairly unavoidable like here, it is best to pre-allocate the result array (if the dimensions are known beforehand) and fill the values in the loop. This also has the advantage of allowing the default value of zero to be pre-filled.

There is no need for applying anything over the columns of x as the other operations (mean and arithmetic) can be easily applied to the chosen axis.

The conditional logic is achieved with masking.

You could also make use of the out and where keyword arguments of np.divide:

def updown(x):
    result = np.zeros_like(x)
    for i in range(len(x)):
        mid = (len(x)+1)//2
        a = x[:mid].mean(axis=0)
        b = x[-mid:].mean(axis=0)
        np.divide(b - a, abs(a), out=result[i], where=(a != 0))
        np.divide(b - a, abs((a + b)/2), out=result[i], where=(a == 0) & (b != 0))
        x = x[1:]
    return result

Let's see some performance comparisons (I've wrapped your entire original code in a function called updown_orig)

For dimensions (20, 5), we see only a factor of 2 improvement:

In []: %timeit updown_orig(np.random.rand(20, 5))
1 ms ± 13.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In []: %timeit updown(np.random.rand(20, 5))
508 µs ± 10.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Let's scale both dimensions by 10 (increasing the size of x by a factor of 100):

In []: %timeit updown_orig(np.random.rand(200, 50))
96.4 ms ± 1.91 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
In []: %timeit updown(np.random.rand(200, 50))
5.84 ms ± 64 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Now the difference is a factor of about 16.5.


问:
AngularFireList push error: Argument of type '{ message: string; }' is not assignable to parameter of type 'ChatMessage[]'
Here is my ChatMessage model:

```<code> export class ChatMessage{
            $key?: string;
            email?:string;
            userName?:string;
            message?:string;
            timeSent?: Date = new Date();
        }
</code>```

and this is my code for AngularFireList:

```<code>chatMessages: AngularFireList<ChatMessage[]>;

const timestamp = this.getTimeStamp();
    //const email = this.user.email;
    const email = "example@abc.com";

this.chatMessages.push({
  message: msg,
  timeSent: timestamp,
  email: email,
  //userName: this.userName,
  userName: "user-test",

});

 getTimeStamp(){
    const now = new Date();
    const date = now.getUTCFullYear() + '/' +
                 (now.getUTCMonth() + 1) + '/' +
                 now.getUTCDate();
    const time =  now.getUTCHours() +':'+
                  now.getUTCMinutes() + ':'+
                  now.getUTCSeconds();

    return (date + ' '+ time);
  }
</code>```

I have an error saying:

message: 'Argument of type '{ message: string; timeSent: string; email: string; userName: string; }' is not assignable to parameter of type 'ChatMessage[]'.
    Object literal may only specify known properties, and 'message' does not exist in type 'ChatMessage[]'.

答:
The correction: Please note that AngularFireList requires type of a single element of the array.

Do not put [] brackets after ChatMessage in AngularFireList.

Body:
Here is my ChatMessage model:

 export class ChatMessage{
            $key?: string;
            email?:string;
            userName?:string;
            message?:string;
            timeSent?: Date = new Date();
        }

and this is my code for AngularFireList:

chatMessages: AngularFireList<ChatMessage[]>;

const timestamp = this.getTimeStamp();
    //const email = this.user.email;
    const email = "example@abc.com";

this.chatMessages.push({
  message: msg,
  timeSent: timestamp,
  email: email,
  //userName: this.userName,
  userName: "user-test",

});

 getTimeStamp(){
    const now = new Date();
    const date = now.getUTCFullYear() + '/' +
                 (now.getUTCMonth() + 1) + '/' +
                 now.getUTCDate();
    const time =  now.getUTCHours() +':'+
                  now.getUTCMinutes() + ':'+
                  now.getUTCSeconds();

    return (date + ' '+ time);
  }

I have an error saying:

message: 'Argument of type '{ message: string; timeSent: string; email: string; userName: string; }' is not assignable to parameter of type 'ChatMessage[]'.
    Object literal may only specify known properties, and 'message' does not exist in type 'ChatMessage[]'.


问:
Where is the users password actually updated in Devise::PasswordsController?
I am quite new to rails Device gem. and Trying to understand how it work.

In my project, there is Devise::PasswordsController.

```<code>  def update
    self.resource = resource_class.reset_password_by_token(resource_params)
    yield resource if block_given?

    if resource.errors.empty?
      resource.unlock_access! if unlockable?(resource)
      if Devise.sign_in_after_reset_password
        flash_message = resource.active_for_authentication? ? :updated : :updated_not_active
        set_flash_message!(:notice, flash_message)
        resource.after_database_authentication
        sign_in(resource_name, resource)
      else
        set_flash_message!(:notice, :updated_not_active)
      end
      respond_with resource, location: after_resetting_password_path_for(resource)
    else
      set_minimum_password_length
      respond_with resource
    end
  end
</code>```

This will update new password to database.

In my server log. I can see UPDATE SQL query executed.

```<code>UPDATE `users` SET `reset_password_sent_at` = NULL, `encrypted_password` = 'somevalue......', `reset_password_token` = NULL, `updated_at` = '2020-xx-xx xx:xx:xx' WHERE `users`.`id` = xxx
</code>```

but,

Why Can't I find any ruby code equivalent to this? as in resource.update things like that.

Sorry if my question is doesn't make sense. And if so, please correct my misunderstanding.

Where can I find the function that executes SQL?

答:
The actual update is happening in Devise::Models::Recoverable#reset_password which is called by #reset_password_by_token.</p>

```<code># Update password saving the record and clearing token. Returns true if
# the passwords are valid and the record was saved, false otherwise.
def reset_password(new_password, new_password_confirmation)
  if new_password.present?
    self.password = new_password
    self.password_confirmation = new_password_confirmation
    save
  else
    errors.add(:password, :blank)
    false
  end
end
</code>```

Body:
I am quite new to rails Device gem. and Trying to understand how it work.

In my project, there is Devise::PasswordsController.

  def update
    self.resource = resource_class.reset_password_by_token(resource_params)
    yield resource if block_given?

    if resource.errors.empty?
      resource.unlock_access! if unlockable?(resource)
      if Devise.sign_in_after_reset_password
        flash_message = resource.active_for_authentication? ? :updated : :updated_not_active
        set_flash_message!(:notice, flash_message)
        resource.after_database_authentication
        sign_in(resource_name, resource)
      else
        set_flash_message!(:notice, :updated_not_active)
      end
      respond_with resource, location: after_resetting_password_path_for(resource)
    else
      set_minimum_password_length
      respond_with resource
    end
  end

This will update new password to database.

In my server log. I can see UPDATE SQL query executed.

UPDATE `users` SET `reset_password_sent_at` = NULL, `encrypted_password` = 'somevalue......', `reset_password_token` = NULL, `updated_at` = '2020-xx-xx xx:xx:xx' WHERE `users`.`id` = xxx

but,

Why Can't I find any ruby code equivalent to this? as in resource.update things like that.

Sorry if my question is doesn't make sense. And if so, please correct my misunderstanding.

Where can I find the function that executes SQL?

Body:
The actual update is happening in Devise::Models::Recoverable#reset_password which is called by #reset_password_by_token.

# Update password saving the record and clearing token. Returns true if
# the passwords are valid and the record was saved, false otherwise.
def reset_password(new_password, new_password_confirmation)
  if new_password.present?
    self.password = new_password
    self.password_confirmation = new_password_confirmation
    save
  else
    errors.add(:password, :blank)
    false
  end
end


问:
PHP SHA-512 to Python+C SHA-512
I am working on a website for a game. The accounts are created via the php based website, and the game login server is being prototyped in Python, and will be finalized in C. The problem I am having is that when I hash something in PHP, I am unable to reproduce the same result with the same starting data and salt in Python. I looked through the algorithm in PHP here http://www.akkadia.org/drepper/SHA-crypt.txt and compared it to the way I was doing it and noticed that PHP cuts off the null byte at the end. Although, other than that I havent had much luck.

Python:

```<code>def HashPassword(Salt,Password,Rounds=5000):
    passhash=hashlib.sha512(Password+Salt).digest()[:-1]
    for i in xrange(2,Rounds):
        passhash=hashlib.sha512(passhash+Salt).digest()[:-1]
    return passhash
</code>```

PHP:

```<code>function HashPW($password, $salt = "")
{
    if(strlen($salt) == 0) $salt = RandChar(16);
    return crypt($password, '$6$rounds=5000$' . $salt . '$');
}
</code>```

答:
String in python doesn't include a null byte at the end.

And range(2,5000) will only loop 4998 times.

Title: PHP SHA-512 to Python+C SHA-512

Body:
I am working on a website for a game. The accounts are created via the php based website, and the game login server is being prototyped in Python, and will be finalized in C. The problem I am having is that when I hash something in PHP, I am unable to reproduce the same result with the same starting data and salt in Python. I looked through the algorithm in PHP here http://www.akkadia.org/drepper/SHA-crypt.txt and compared it to the way I was doing it and noticed that PHP cuts off the null byte at the end. Although, other than that I havent had much luck.

Python:

def HashPassword(Salt,Password,Rounds=5000):
    passhash=hashlib.sha512(Password+Salt).digest()[:-1]
    for i in xrange(2,Rounds):
        passhash=hashlib.sha512(passhash+Salt).digest()[:-1]
    return passhash

PHP:

function HashPW($password, $salt = "")
{
    if(strlen($salt) == 0) $salt = RandChar(16);
    return crypt($password, '$6$rounds=5000$' . $salt . '$');
}


问:
What does the ?. syntax mean in JavaScript?
I came across this C# like code in a React project. I couldn't confirm if this syntax correct or not. I didn't find any recent ES version release to support this syntax. In current scenario I'm not authorized to execute and check this code.

I tried testing this syntax in browse console and encountered error:

```<code>{cart?.widgets?.items.map(widget => (
        <div className="billing-details__box" key={widget.id}>
          <p className="m-0">{widget.name}</p>
          <p className="my-0">{widget.value} $</p>
        </div>
 ))}
</code>```

My concern with above code is whether cart?.widgets?.items will raise any error or not.

答:
It is optional chaining which is JS new feature.

Basically it is the same as:

```<code>{cart && cart.widgets && cart.widgets.items.map(widget => (
        <div className="billing-details__box" key={widget.id}>
          <p className="m-0">{widget.name}</p>
          <p className="my-0">{widget.value} $</p>
        </div>
 ))}
</code>```

For more details be sure to visit V8 guide.

Body:
I came across this C# like code in a React project. I couldn't confirm if this syntax correct or not. I didn't find any recent ES version release to support this syntax. In current scenario I'm not authorized to execute and check this code.

I tried testing this syntax in browse console and encountered error:

{cart?.widgets?.items.map(widget => (

{widget.name}

{widget.value} $

 ))}

My concern with above code is whether cart?.widgets?.items will raise any error or not.

Body:
It is optional chaining which is JS new feature.

Basically it is the same as:

{cart && cart.widgets && cart.widgets.items.map(widget => (
        <div className="billing-details__box" key={widget.id}>
          <p className="m-0">{widget.name}</p>
          <p className="my-0">{widget.value} $</p>
        </div>
 ))}

For more details be sure to visit V8 guide.


问:
How to find a pair of hunted values for a given value with lopps?
I am trying to write a function that gets a list of numbers and an integer and returns a tuple that containing pair of numbers from the list whose sum is the must closest to the number the function received.
for example: closest([10,22,28,29,30,40], 54) --> (22,30)
It is important for me to do this in loop and in time complexity of  O(n).
The problem with my code is that the loop does not want to rerun the list end for any value I take from the beginning of the list...
I would appreciate help :)
Thanks for the helpers!</p>

```<code>def closest(lst, x):
    max_num = 0
    cur = lst[0]
    final = 0
    my_tup = ()
    for num in lst[::-1]:
        max_num = cur + num
        if max_num <= x:
            if max_num > final:
                final = max_num
                my_tup = (cur, num)
            else:
                cur = lst[1]

    return my_tup

print(closest([10,22,28,29,30,40], 54))  ---> return: (22,29)
</code>```

答:
If the list that you give is sorted and the elements are unique you can use this.Otherwise I believe that you can implement some conditions to the dictionary and get the values you want.

my_dict = {i+j:(i,j) for i in mylist for j in mylist if i != j and i + j < bound}
my_dict[max(t)]

Body:
I am trying to write a function that gets a list of numbers and an integer and returns a tuple that containing pair of numbers from the list whose sum is the must closest to the number the function received.
for example: closest([10,22,28,29,30,40], 54) --> (22,30)
It is important for me to do this in loop and in time complexity of  O(n).
The problem with my code is that the loop does not want to rerun the list end for any value I take from the beginning of the list...
I would appreciate help :)
Thanks for the helpers!

def closest(lst, x):
    max_num = 0
    cur = lst[0]
    final = 0
    my_tup = ()
    for num in lst[::-1]:
        max_num = cur + num
        if max_num <= x:
            if max_num > final:
                final = max_num
                my_tup = (cur, num)
            else:
                cur = lst[1]

    return my_tup

print(closest([10,22,28,29,30,40], 54))  ---> return: (22,29)


问:
How do I use the inet type with Python and postgresql?
I am writing a python3 program that uses a postgresql database, I am using py-postgresql: http://python.projects.postgresql.org/ as the database driver.
One table stores IP addresses using the inet type.

I have created the following prepared statement:

```<code>aID = db.prepare('SELECT id FROM a_records WHERE ip = $1 LIMIT 1')
</code>```

When calling aID(ip) I get the following error:

(ip is a python string)

```<code> File "/usr/local/lib/python3.1/dist-packages/postgresql/driver/pq3.py", line
1517, in __call__
    c = SingleXactFetch(self, parameters)
  File "/usr/local/lib/python3.1/dist-packages/postgresql/driver/pq3.py", line
837, in __init__
    Output.__init__(self, '')
  File "/usr/local/lib/python3.1/dist-packages/postgresql/driver/pq3.py", line
622, in __init__
    self._init()
  File "/usr/local/lib/python3.1/dist-packages/postgresql/driver/pq3.py", line
854, in _init
    STEP()
  File "/usr/local/lib/python3.1/dist-packages/postgresql/driver/pq3.py", line
2612, in _pq_step
    self.typio.raise_error(x.error_message, cause = getattr(x, 'exception', Non
e))
  File "/usr/local/lib/python3.1/dist-packages/postgresql/driver/pq3.py", line
507, in raise_error
    self.raise_server_error(error_message, **kw)
  File "/usr/local/lib/python3.1/dist-packages/postgresql/driver/pq3.py", line
498, in raise_server_error
    raise server_error
postgresql.exceptions.BinaryRepresentationError: invalid address family in exte
rnal "inet" value
  CODE: 22P03
  LOCATION: File 'network.c', line 218, in network_recv from SERVER
RESULT:
  type: SingleXactFetch
  parameters: ('139.78.113.1',)
STATEMENT: [prepared]
  sql_parameter_types: ['pg_catalog.inet']
  results: (id INTEGER)
  statement_id: py:0x2ff9a50
  string: SELECT id FROM a_records WHERE ip = $1 LIMIT 1
CONNECTION: [idle]
  client_address: 127.0.0.1/32
  client_port: 51563
  version:
    PostgreSQL 8.4.7 on x86_64-pc-linux-gnu, compiled by GCC gcc-4.4.real (Debi
an 4.4.5-8) 4.4.5, 64-bit
CONNECTOR: [IP4] pq://python:***@127.0.0.1:5432/vdz
  category: None
DRIVER: postgresql.driver.pq3.Driver
</code>```

Can anyone help me debug this and figure out why postgresql is not liking the inet data?

Thanks!

答:
You should explicitly cast string to inet data type.</p>

```<code>aID = db.prepare('SELECT id FROM a_records WHERE ip = inet($1) LIMIT 1')
</code>```

Body:
I am writing a python3 program that uses a postgresql database, I am using py-postgresql: http://python.projects.postgresql.org/ as the database driver.
One table stores IP addresses using the inet type.

I have created the following prepared statement:

aID = db.prepare('SELECT id FROM a_records WHERE ip = $1 LIMIT 1')

When calling aID(ip) I get the following error:

(ip is a python string)

 File "/usr/local/lib/python3.1/dist-packages/postgresql/driver/pq3.py", line
1517, in __call__
    c = SingleXactFetch(self, parameters)
  File "/usr/local/lib/python3.1/dist-packages/postgresql/driver/pq3.py", line
837, in __init__
    Output.__init__(self, '')
  File "/usr/local/lib/python3.1/dist-packages/postgresql/driver/pq3.py", line
622, in __init__
    self._init()
  File "/usr/local/lib/python3.1/dist-packages/postgresql/driver/pq3.py", line
854, in _init
    STEP()
  File "/usr/local/lib/python3.1/dist-packages/postgresql/driver/pq3.py", line
2612, in _pq_step
    self.typio.raise_error(x.error_message, cause = getattr(x, 'exception', Non
e))
  File "/usr/local/lib/python3.1/dist-packages/postgresql/driver/pq3.py", line
507, in raise_error
    self.raise_server_error(error_message, **kw)
  File "/usr/local/lib/python3.1/dist-packages/postgresql/driver/pq3.py", line
498, in raise_server_error
    raise server_error
postgresql.exceptions.BinaryRepresentationError: invalid address family in exte
rnal "inet" value
  CODE: 22P03
  LOCATION: File 'network.c', line 218, in network_recv from SERVER
RESULT:
  type: SingleXactFetch
  parameters: ('139.78.113.1',)
STATEMENT: [prepared]
  sql_parameter_types: ['pg_catalog.inet']
  results: (id INTEGER)
  statement_id: py:0x2ff9a50
  string: SELECT id FROM a_records WHERE ip = $1 LIMIT 1
CONNECTION: [idle]
  client_address: 127.0.0.1/32
  client_port: 51563
  version:
    PostgreSQL 8.4.7 on x86_64-pc-linux-gnu, compiled by GCC gcc-4.4.real (Debi
an 4.4.5-8) 4.4.5, 64-bit
CONNECTOR: [IP4] pq://python:***@127.0.0.1:5432/vdz
  category: None
DRIVER: postgresql.driver.pq3.Driver

Can anyone help me debug this and figure out why postgresql is not liking the inet data?

Thanks!

Body:
You should explicitly cast string to inet data type.

aID = db.prepare('SELECT id FROM a_records WHERE ip = inet($1) LIMIT 1')


问:
Problem with neural network in TensorFlow 2.0
```<code>import tensorflow as tf
import pandas as pd
import numpy as np
import matplotlib as plt
from sklearn.model_selection import train_test_split
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from sklearn.preprocessing import StandardScaler
import functools

LABEL_COLUMN = 'Endstage'
LABELS = [1, 2, 3, 4]
x = pd.read_csv('HCVnew.csv', index_col=False)

def get_dataset(file_path, **kwargs):
  dataset = tf.data.experimental.make_csv_dataset(
      file_path,
      batch_size=35, # Artificially small to make examples easier to show.
      label_name=LABEL_COLUMN,
      na_value="?",
      num_epochs=1,
      ignore_errors=True,
      **kwargs)
  return dataset

SELECT_COLUMNS = ["Alter", "Gender", "BMI", "Fever", "Nausea", "Fatigue",
                  "WBC", "RBC", "HGB", "Plat", "AST1", "ALT1", "ALT4", "ALT12", "ALT24", "ALT36", "ALT48", "ALT24w",
                  "RNABase", "RNA4", "Baseline", "Endstage"]

DEFAULTS = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
            0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
temp_dataset = get_dataset("HCVnew.csv",
                           select_columns=SELECT_COLUMNS,
                           column_defaults=DEFAULTS)
def pack(features, label):
  return tf.stack(list(features.values()), axis=-1), label

packed_dataset = temp_dataset.map(pack)

"""
for features, labels in packed_dataset.take(1):
  print(features.numpy())
  print()
  print(labels.numpy())
"""

NUMERIC_FEATURES = ["Alter", "Gender","BMI", "Fever", "Nausea", "Fatigue",
                  "WBC", "RBC", "HGB", "Plat", "AST1", "ALT1", "ALT4", "ALT12", "ALT24", "ALT36", "ALT48", "ALT24w",
                  "RNABase", "RNA4", "Baseline", "Endstage"]

desc = pd.read_csv("HCVnew.csv")[NUMERIC_FEATURES].describe()

MEAN = np.array(desc.T['mean'])
STD = np.array(desc.T['std'])

def normalize_numeric_data(data, mean, std):
  # Center the data
  return (data-mean)/std

# See what you just created.
raw_train_data = get_dataset("HCVnew.csv")
raw_test_data = get_dataset("HCVnew.csv")

class PackNumericFeatures(object):
  def __init__(self, names):
    self.names = names

  def __call__(self, features, labels):
    numeric_freatures = [features.pop(name) for name in self.names]
    numeric_features = [tf.cast(feat, tf.float32) for feat in numeric_freatures]
    numeric_features = tf.stack(numeric_features, axis=-1)
    features['numeric'] = numeric_features

    return features, labels

NUMERIC_FEATURES = ["Alter", "Gender","BMI", "Fever", "Nausea", "Fatigue",
                  "WBC", "RBC", "HGB", "Plat", "AST1", "ALT1", "ALT4", "ALT12", "ALT24", "ALT36", "ALT48", "ALT24w",
                  "RNABase", "RNA4", "Baseline", "Endstage"]

packed_train_data = raw_train_data.map(
    PackNumericFeatures(NUMERIC_FEATURES))

packed_test_data = raw_test_data.map(
    PackNumericFeatures(NUMERIC_FEATURES))

normalizer = functools.partial(normalize_numeric_data, mean=MEAN, std=STD)

numeric_column = tf.feature_column.numeric_column('numeric', normalizer_fn=normalizer, shape=[len(NUMERIC_FEATURES)])
numeric_columns = [numeric_column]

numeric_layer = tf.keras.layers.DenseFeatures(numeric_columns)
preprocessing_layer = tf.keras.layers.DenseFeatures(numeric_columns)

#———————————————————————MODEL———————————————————————————————————————————————————————————————————————————————————————————

model = tf.keras.Sequential([
  preprocessing_layer,
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dense(1, activation='sigmoid'),
])

model.compile(
    loss='binary_crossentropy',
    optimizer='adam',
    metrics=['accuracy'])

data_x = get_dataset("HCVnew.csv")

train_data = data_x.shuffle(500)

model.fit(train_data, epochs=20)

</code>```

Hello, I'm trying to build a neural network that can predict Hepatitis C based on a csv file containing patient information and I can't fix the error...
I'm getting the error: KeyError 'Endstage', whereas Endstage is the csv column that contains the corresponding values (between 1 and 4) and serves as the label column.
If someone has an idea that could fix my problem then please tell me.
Thanks a lot for your help!

答:
That's because Endstage is your label column and the framework does a favour to you by removing (popping) it out of your dataset. Otherwise your training data set would have also the target class, rendering it useless.

Remove it from NUMERIC_FEATURES and any other place that makes it into your training set features.

[EDIT]

The OP asked in the follow-up question (in the comments) why, after fixing the initial problem, he's getting an error:

ValueError: Feature numeric is not in features dictionary

By the looks of it, feature called numeric is produced via call to PackNumericFeatures. The latter is used to create packed_train_data and packed_test_data, but these are never used. Yet this line:

```<code>numeric_column = tf.feature_column.numeric_column('numeric', normalizer_fn=normalizer, shape=[len(NUMERIC_FEATURES)])
</code>```

assumes the data is there - hence the error.

Body:
import tensorflow as tf
import pandas as pd
import numpy as np
import matplotlib as plt
from sklearn.model_selection import train_test_split
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from sklearn.preprocessing import StandardScaler
import functools

LABEL_COLUMN = 'Endstage'
LABELS = [1, 2, 3, 4]
x = pd.read_csv('HCVnew.csv', index_col=False)

def get_dataset(file_path, **kwargs):
  dataset = tf.data.experimental.make_csv_dataset(
      file_path,
      batch_size=35, # Artificially small to make examples easier to show.
      label_name=LABEL_COLUMN,
      na_value="?",
      num_epochs=1,
      ignore_errors=True,
      **kwargs)
  return dataset

SELECT_COLUMNS = ["Alter", "Gender", "BMI", "Fever", "Nausea", "Fatigue",
                  "WBC", "RBC", "HGB", "Plat", "AST1", "ALT1", "ALT4", "ALT12", "ALT24", "ALT36", "ALT48", "ALT24w",
                  "RNABase", "RNA4", "Baseline", "Endstage"]

DEFAULTS = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
            0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
temp_dataset = get_dataset("HCVnew.csv",
                           select_columns=SELECT_COLUMNS,
                           column_defaults=DEFAULTS)
def pack(features, label):
  return tf.stack(list(features.values()), axis=-1), label

packed_dataset = temp_dataset.map(pack)

"""
for features, labels in packed_dataset.take(1):
  print(features.numpy())
  print()
  print(labels.numpy())
"""

NUMERIC_FEATURES = ["Alter", "Gender","BMI", "Fever", "Nausea", "Fatigue",
                  "WBC", "RBC", "HGB", "Plat", "AST1", "ALT1", "ALT4", "ALT12", "ALT24", "ALT36", "ALT48", "ALT24w",
                  "RNABase", "RNA4", "Baseline", "Endstage"]

desc = pd.read_csv("HCVnew.csv")[NUMERIC_FEATURES].describe()

MEAN = np.array(desc.T['mean'])
STD = np.array(desc.T['std'])

def normalize_numeric_data(data, mean, std):
  # Center the data
  return (data-mean)/std

# See what you just created.
raw_train_data = get_dataset("HCVnew.csv")
raw_test_data = get_dataset("HCVnew.csv")

class PackNumericFeatures(object):
  def __init__(self, names):
    self.names = names

  def __call__(self, features, labels):
    numeric_freatures = [features.pop(name) for name in self.names]
    numeric_features = [tf.cast(feat, tf.float32) for feat in numeric_freatures]
    numeric_features = tf.stack(numeric_features, axis=-1)
    features['numeric'] = numeric_features

    return features, labels

NUMERIC_FEATURES = ["Alter", "Gender","BMI", "Fever", "Nausea", "Fatigue",
                  "WBC", "RBC", "HGB", "Plat", "AST1", "ALT1", "ALT4", "ALT12", "ALT24", "ALT36", "ALT48", "ALT24w",
                  "RNABase", "RNA4", "Baseline", "Endstage"]

packed_train_data = raw_train_data.map(
    PackNumericFeatures(NUMERIC_FEATURES))

packed_test_data = raw_test_data.map(
    PackNumericFeatures(NUMERIC_FEATURES))

normalizer = functools.partial(normalize_numeric_data, mean=MEAN, std=STD)

numeric_column = tf.feature_column.numeric_column('numeric', normalizer_fn=normalizer, shape=[len(NUMERIC_FEATURES)])
numeric_columns = [numeric_column]

numeric_layer = tf.keras.layers.DenseFeatures(numeric_columns)
preprocessing_layer = tf.keras.layers.DenseFeatures(numeric_columns)

#———————————————————————MODEL———————————————————————————————————————————————————————————————————————————————————————————

model = tf.keras.Sequential([
  preprocessing_layer,
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dense(1, activation='sigmoid'),
])

model.compile(
    loss='binary_crossentropy',
    optimizer='adam',
    metrics=['accuracy'])

data_x = get_dataset("HCVnew.csv")

train_data = data_x.shuffle(500)

model.fit(train_data, epochs=20)

Hello, I'm trying to build a neural network that can predict Hepatitis C based on a csv file containing patient information and I can't fix the error...
I'm getting the error: KeyError 'Endstage', whereas Endstage is the csv column that contains the corresponding values (between 1 and 4) and serves as the label column.
If someone has an idea that could fix my problem then please tell me.
Thanks a lot for your help!

Body:
That's because Endstage is your label column and the framework does a favour to you by removing (popping) it out of your dataset. Otherwise your training data set would have also the target class, rendering it useless.

Remove it from NUMERIC_FEATURES and any other place that makes it into your training set features.

[EDIT]

The OP asked in the follow-up question (in the comments) why, after fixing the initial problem, he's getting an error:

ValueError: Feature numeric is not in features dictionary

By the looks of it, feature called numeric is produced via call to PackNumericFeatures. The latter is used to create packed_train_data and packed_test_data, but these are never used. Yet this line:

numeric_column = tf.feature_column.numeric_column('numeric', normalizer_fn=normalizer, shape=[len(NUMERIC_FEATURES)])

assumes the data is there - hence the error.


问:
How to keep track of QLabel created in a loop using new operator
I am creating many labels based inside a loop using new operator in Qt, something like this:

```<code>QLabel *p;
for(int i=0; i<10; i++)
    {
    p = new QLabel(this);
    // ...
    }
</code>```

Now what is happening, when I am using p it points to the last label in the sequence but I want to use my first label. How can I keep track of every label?

答:
You could store all Label-pointer using std::vector:

```<code>std::vector<QLabel*> labels;

for (int i=0; i<10; i++)
   labels.push_back(new QLabel(this));
</code>```

Accessing these pointers can be done array-like:

```<code>QLabel *first = labels[0];
</code>```

Or by using iterators:

```<code>std::vector<QLabel*>::iterator itr = labels.begin();
QLabel *first = *itr;
</code>```

Body:
I am creating many labels based inside a loop using new operator in Qt, something like this:

QLabel *p;
for(int i=0; i<10; i++)
    {
    p = new QLabel(this);
    // ...
    }

Now what is happening, when I am using p it points to the last label in the sequence but I want to use my first label. How can I keep track of every label?

Body:
You could store all Label-pointer using std::vector:

std::vector<QLabel*> labels;

for (int i=0; i<10; i++)
   labels.push_back(new QLabel(this));

Accessing these pointers can be done array-like:

QLabel *first = labels[0];

Or by using iterators:

std::vector<QLabel*>::iterator itr = labels.begin();
QLabel *first = *itr;


问:
[Java]Find duplicate characters in a string without hashmap and set
I have written a Java program to find duplicate characters in a string without Hashmap and set.

Below is the program,

```<code>package practice;

public class Duplicate {

    public static void main(String[] args) {

        String src= "abcad";

        char[] srcChar= src.toLowerCase().toCharArray();

        int len=srcChar.length;
        int j=0;
        boolean flag=false;
        char ch;

        //      System.out.println("Length of the String is "+len1);
        //      System.out.println("Length of the character array is "+len);

        int k=0;

        for(int i=0;i<len;i++)
        {
            //          System.out.println("i-----> "+i + " and character is "+srcChar[i]);
            for(j=0;j<len;j++)
            {
                //              System.out.println("j-----> "+j + " and character is "+srcChar[j]);
                if(srcChar[i]==srcChar[j])
                {
                    k++;
                }
            }
            if(k>1)
            {
                if(srcChar[i]>1)
                {
                    System.out.println("This character "+srcChar[i]+" has repeated "+k+ " time");
                }
                else
                {
                    System.out.println("There are no characters repeated in the given string");
                }
            }
            k=0;
        }
    }
}
</code>```

Output here is:

This character a has repeated 2 time

This character a has repeated 2 time

Here, I want the output like
This character a has repeated 2 time

i.e. not repeating the output twice. Since the character "a" is repeated twice, the output is also repeated twice.

kindly help me to get the output once instead of twice.

Thank you,

答:
```<code>private static void duplicateChar(String str){
        char[] arr1 = str.toUpperCase().toCharArray();
        int length = str.length();
        int count = 1;
        String s = "";
        char c1 = '\u0000';

        for(int i=0;i<length;i++){
            count = 1;
            for(int j=i+1;j<length;j++){
                if(arr1[i] == arr1[j]){
                    count++;
                    c1 = arr1[i];
                }
                if(j == (length-1) && c1 != '\u0000' && !s.contains(String.valueOf(c1))){
                    s = s+" "+String.valueOf(c1)+"  No of times:  "+count+"\n";
                }
            }
        }
        System.out.println("\nDuplicate char are:\n"+s);
    }
</code>```

Body:
I have written a Java program to find duplicate characters in a string without Hashmap and set.

Below is the program,

package practice;

public class Duplicate {

    public static void main(String[] args) {

        String src= "abcad";

        char[] srcChar= src.toLowerCase().toCharArray();

        int len=srcChar.length;
        int j=0;
        boolean flag=false;
        char ch;

        //      System.out.println("Length of the String is "+len1);
        //      System.out.println("Length of the character array is "+len);

        int k=0;

        for(int i=0;i<len;i++)
        {
            //          System.out.println("i-----> "+i + " and character is "+srcChar[i]);
            for(j=0;j<len;j++)
            {
                //              System.out.println("j-----> "+j + " and character is "+srcChar[j]);
                if(srcChar[i]==srcChar[j])
                {
                    k++;
                }
            }
            if(k>1)
            {
                if(srcChar[i]>1)
                {
                    System.out.println("This character "+srcChar[i]+" has repeated "+k+ " time");
                }
                else
                {
                    System.out.println("There are no characters repeated in the given string");
                }
            }
            k=0;
        }
    }
}

Output here is:

This character a has repeated 2 time

This character a has repeated 2 time

Here, I want the output like
This character a has repeated 2 time

i.e. not repeating the output twice. Since the character "a" is repeated twice, the output is also repeated twice.

kindly help me to get the output once instead of twice.

Thank you,


问:
check look up values of dynamics 365 entities inside power automate
I want to know how can I compare a field of an entity with a dropdown list or a lookup value in dynamics 365 power automate?

for example, I want to send an email to a case customer when a case is created if the case type is "complain,request" , but I don't want to write those words, it doesn't pick up values like the workflows??

Thanks

答:
Flow/PowerAutomate does have condition to check for type.
I just tried on case Entity. For every Type you will have a value behind it.


问:
Is Kestrel completely in-process?
I have created a C# console application (using the simple console application template) and I am using Kestrel to host an HTTP service using Web API. My question is: is Kestrel in-process? Can I be sure that no other process related to IIS or anything else will be used? There doesn't seem to be any documentation in Microsoft's site to confirm this.

Here is the code I'm using:

```<code>public static void Main(string[] args)
{
    new WebHostBuilder()
        .UseStartup<Startup>()
        .UseKestrel(options =>
        {
            options.ListenLocalhost(6001, listenOptions => { });
        })
        .Build()
        .Run();
}
</code>```

答: Yes, Kestrel is open source and cross-platform, meaning, it does not depend on Windows, nor does it use any kind of Windows service or process.</p>

Title: Is Kestrel completely in-process?

Body:
I have created a C# console application (using the simple console application template) and I am using Kestrel to host an HTTP service using Web API. My question is: is Kestrel in-process? Can I be sure that no other process related to IIS or anything else will be used? There doesn't seem to be any documentation in Microsoft's site to confirm this.

Here is the code I'm using:

public static void Main(string[] args)
{
    new WebHostBuilder()
        .UseStartup<Startup>()
        .UseKestrel(options =>
        {
            options.ListenLocalhost(6001, listenOptions => { });
        })
        .Build()
        .Run();
}


问:
Handle MouseEvent.CLICK, MOUSE_DOWN in subclasses
I'm building a panel of buttons, that are enclosed in Canvas container. For this purpose I created a MyButton class, which is a subclass of UIComponent. MyButton class has 2 other subclasses: MyRadioButton and MyMenuButton, which have another behavior on MouseEvent.MOUSE_DOWN. MyMenuButtoncreates and shows a menu, that I build from XML and it builds ok.

I add listeners in the superclass like this:

```<code>this.addEventListener(MouseEvent.CLICK, handleClick);
this.addEventListener(MouseEvent.MOUSE_DOWN, handleMouse);
this.addEventListener(MouseEvent.MOUSE_UP, handleMouse);
</code>```

It's done at the creation stage.

In my subclasses I override handleMouse handler.

```<code>override protected handleMouse(event:MouseEvent) : void
{
  // subclass specific handling
}
</code>```

These button objects are added to canvas container as following:

in class MyButtonsContainer.as:

```<code>this.rowChildren.addChild(button);
</code>```

These buttons draw perfectly and in place. The problem is the behavior:
The event doesn't come to handleClick handler of superclass. And that's the question actually - why can it be?
Thanks in advance

EDIT: It appears that MOUSE_DOWN & MOUSE_UP interfere with CLICK event. When I remove listeners to them I get to click handler.How to cause them live together?

答:
If I'm understanding you correctly, you just need to make sure that in your overriden handlers you end each one with a call to super -</p>

```<code>override protected handleMouse(event:MouseEvent):void {
// my logic here for the subclass
trace("blah blah blah");

//now redispatch up to the superclass.
super.handleMouse(event);

}
</code>```

Body:
I'm building a panel of buttons, that are enclosed in Canvas container. For this purpose I created a MyButton class, which is a subclass of UIComponent. MyButton class has 2 other subclasses: MyRadioButton and MyMenuButton, which have another behavior on MouseEvent.MOUSE_DOWN. MyMenuButtoncreates and shows a menu, that I build from XML and it builds ok.

I add listeners in the superclass like this:

this.addEventListener(MouseEvent.CLICK, handleClick);
this.addEventListener(MouseEvent.MOUSE_DOWN, handleMouse);
this.addEventListener(MouseEvent.MOUSE_UP, handleMouse);

It's done at the creation stage.

In my subclasses I override handleMouse handler.

override protected handleMouse(event:MouseEvent) : void
{
  // subclass specific handling
}

These button objects are added to canvas container as following:

in class MyButtonsContainer.as:

this.rowChildren.addChild(button);

These buttons draw perfectly and in place. The problem is the behavior:
The event doesn't come to handleClick handler of superclass. And that's the question actually - why can it be?
Thanks in advance

EDIT: It appears that MOUSE_DOWN & MOUSE_UP interfere with CLICK event. When I remove listeners to them I get to click handler.How to cause them live together?

Body:
If I'm understanding you correctly, you just need to make sure that in your overriden handlers you end each one with a call to super -

override protected handleMouse(event:MouseEvent):void {
// my logic here for the subclass
trace("blah blah blah");

//now redispatch up to the superclass.
super.handleMouse(event);

}


问:
How to design a shared weight, multi input/output Auto-Encoder network?
I have two different types of images (camera image and it's corresponding sketch). The goal of the network is to find the similarity between both images.

The network consists of a single encoder and a single decoder. The motivation behind the single encoder-decoder is to share the weights between them.

```<code>input_img = Input(shape=(img_width,img_height, channels))

def encoder(input_img):
    # Photo-Encoder Code
    pe = Conv2D(96, kernel_size=11, strides=(4,4), padding = 'SAME')(left_input) # (?, 64, 64, 96)
    pe = BatchNormalization()(pe)
    pe = Activation('selu')(pe)
    pe = MaxPool2D((3, 3), strides=(2, 2), padding = 'VALID')(pe) # (?, 31, 31, 96)

    pe = Conv2D(256, kernel_size=5, strides=(1,1), padding = 'SAME')(pe) # (?, 31, 31, 256)
    pe = BatchNormalization()(pe)
    pe = Activation('selu')(pe)
    pe = MaxPool2D((3, 3), strides=(2, 2), padding = 'VALID')(pe) #(?, 15, 15, 256)

    pe = Conv2D(384, kernel_size=3, strides=(1,1), padding = 'SAME')(pe) # (?, 15, 15, 384)
    pe = BatchNormalization()(pe)
    pe = Activation('selu')(pe)

    pe = Conv2D(384, kernel_size=3, strides=(1,1), padding = 'SAME')(pe) # (?, 15, 15, 384)
    pe = BatchNormalization()(pe)
    pe = Activation('selu')(pe)

    pe = Conv2D(256, kernel_size=3, strides=(1,1), padding = 'SAME')(pe) # (?, 15, 15, 256)
    pe = BatchNormalization()(pe)
    pe = Activation('selu')(pe)
    encoded = MaxPool2D((3, 3), strides=(2, 2), padding = 'VALID')(pe) # (?, 7, 7, 256)

    return encoded

def decoder(pe):
    pe = Conv2D(1024, kernel_size=7, strides=(1, 1), padding = 'VALID')(pe)
    pe = BatchNormalization()(pe)
    pe = Activation('selu')(pe)

    p_decoder_inp = Reshape((2,2,256))(pe)

    pd = Conv2DTranspose(128, kernel_size=5, strides=(2, 2), padding='SAME')(p_decoder_inp)
    pd = Activation("selu")(pd)

    pd = Conv2DTranspose(64, kernel_size=5, strides=(2, 2), padding='SAME')(pd)
    pd = Activation("selu")(pd)

    pd = Conv2DTranspose(32, kernel_size=5, strides=(2, 2), padding='SAME')(pd)
    pd = Activation("selu")(pd)

    pd = Conv2DTranspose(16, kernel_size=5, strides=(2, 2), padding='SAME')(pd)
    pd = Activation("selu")(pd)

    pd = Conv2DTranspose(8, kernel_size=5, strides=(2, 2), padding='SAME')(pd)
    pd = Activation("selu")(pd)

    pd = Conv2DTranspose(4, kernel_size=5, strides=(2, 2), padding='SAME')(pd)
    pd = Activation("selu")(pd)

    decoded = Conv2DTranspose(3, kernel_size=5, strides=(2, 2), padding='SAME', activation='sigmoid')(pd) # (?, ?, ?, 3)

    return decoded

siamsese_net = Model([camera_img, sketch_img], [decoder(encoder(camera_img)), decoder(encoder(sketch_img))])

siamsese_net.summary()
</code>```

When I visualize the network, it show two-different networks.

But what I want is a network which takes two inputs, for example, a camera image and a sketch image and returns same images by using a single encoder-decoder.

Where I am doing wrong?

答:
Your "functions" are not "models", they are "creators".

Update both your functions like:

```<code>def create_encoder(): #no arguments!!!
    pe = Input(shape=(img_width,img_height, channels))
    ....
    encoded = ...

    encoder = Model(pe, encoded)
    return encoder

def create_decoder():
    pe = Input(shape=(7,7,256))
     ....
    decoded = ....

    decoder = Model(pe, decoded)
    return decoder
</code>```

Now create the models:

```<code>encoder = create_encoder()
decoder = create_decoder()

siamsese_net = Model([camera_img, sketch_img],
                     [decoder(encoder(camera_img)), decoder(encoder(sketch_img))])

#where camera_img and sketch_image are 'Input' objects.
</code>```

Body:
I have two different types of images (camera image and it's corresponding sketch). The goal of the network is to find the similarity between both images.

The network consists of a single encoder and a single decoder. The motivation behind the single encoder-decoder is to share the weights between them.

input_img = Input(shape=(img_width,img_height, channels))

def encoder(input_img):
    # Photo-Encoder Code
    pe = Conv2D(96, kernel_size=11, strides=(4,4), padding = 'SAME')(left_input) # (?, 64, 64, 96)
    pe = BatchNormalization()(pe)
    pe = Activation('selu')(pe)
    pe = MaxPool2D((3, 3), strides=(2, 2), padding = 'VALID')(pe) # (?, 31, 31, 96)

    pe = Conv2D(256, kernel_size=5, strides=(1,1), padding = 'SAME')(pe) # (?, 31, 31, 256)
    pe = BatchNormalization()(pe)
    pe = Activation('selu')(pe)
    pe = MaxPool2D((3, 3), strides=(2, 2), padding = 'VALID')(pe) #(?, 15, 15, 256)

    pe = Conv2D(384, kernel_size=3, strides=(1,1), padding = 'SAME')(pe) # (?, 15, 15, 384)
    pe = BatchNormalization()(pe)
    pe = Activation('selu')(pe)

    pe = Conv2D(384, kernel_size=3, strides=(1,1), padding = 'SAME')(pe) # (?, 15, 15, 384)
    pe = BatchNormalization()(pe)
    pe = Activation('selu')(pe)

    pe = Conv2D(256, kernel_size=3, strides=(1,1), padding = 'SAME')(pe) # (?, 15, 15, 256)
    pe = BatchNormalization()(pe)
    pe = Activation('selu')(pe)
    encoded = MaxPool2D((3, 3), strides=(2, 2), padding = 'VALID')(pe) # (?, 7, 7, 256)

    return encoded

def decoder(pe):
    pe = Conv2D(1024, kernel_size=7, strides=(1, 1), padding = 'VALID')(pe)
    pe = BatchNormalization()(pe)
    pe = Activation('selu')(pe)

    p_decoder_inp = Reshape((2,2,256))(pe)

    pd = Conv2DTranspose(128, kernel_size=5, strides=(2, 2), padding='SAME')(p_decoder_inp)
    pd = Activation("selu")(pd)

    pd = Conv2DTranspose(64, kernel_size=5, strides=(2, 2), padding='SAME')(pd)
    pd = Activation("selu")(pd)

    pd = Conv2DTranspose(32, kernel_size=5, strides=(2, 2), padding='SAME')(pd)
    pd = Activation("selu")(pd)

    pd = Conv2DTranspose(16, kernel_size=5, strides=(2, 2), padding='SAME')(pd)
    pd = Activation("selu")(pd)

    pd = Conv2DTranspose(8, kernel_size=5, strides=(2, 2), padding='SAME')(pd)
    pd = Activation("selu")(pd)

    pd = Conv2DTranspose(4, kernel_size=5, strides=(2, 2), padding='SAME')(pd)
    pd = Activation("selu")(pd)

    decoded = Conv2DTranspose(3, kernel_size=5, strides=(2, 2), padding='SAME', activation='sigmoid')(pd) # (?, ?, ?, 3)

    return decoded

siamsese_net = Model([camera_img, sketch_img], [decoder(encoder(camera_img)), decoder(encoder(sketch_img))])

siamsese_net.summary()

When I visualize the network, it show two-different networks.

But what I want is a network which takes two inputs, for example, a camera image and a sketch image and returns same images by using a single encoder-decoder.

Where I am doing wrong?

Body:
Your "functions" are not "models", they are "creators".

Update both your functions like:

def create_encoder(): #no arguments!!!
    pe = Input(shape=(img_width,img_height, channels))
    ....
    encoded = ...

    encoder = Model(pe, encoded)
    return encoder

def create_decoder():
    pe = Input(shape=(7,7,256))
     ....
    decoded = ....

    decoder = Model(pe, decoded)
    return decoder

Now create the models:

encoder = create_encoder()
decoder = create_decoder()

siamsese_net = Model([camera_img, sketch_img],
                     [decoder(encoder(camera_img)), decoder(encoder(sketch_img))])

#where camera_img and sketch_image are 'Input' objects.


问:
CSS: Make image fit the proper area with the absolutely positioned label on the picture
On my webpage there is an area and I'd like to add a image to it. I don't know the image's size and orientation (portrait or landscape). But I want it to fit the area as it is displayed in the picture:

So, if an image has a landscape orientation it must fill the whole width of the area. See picture 1. If the image's width is bigger that the area's width the image's width must be constrained and if its width is smaller - the image must be widened. However if the image's height is bigger than the area's one the image's height must be constrained. See picture 2.

The similar I want for the portrait image. See picture 2.

In short, what I want can be easily done with object-fit: contain;.

.wrapper {
  width: 30%;
  height: 400px;
  overflow: hidden;
  border: 1px solid black;
  position: relative;
}

.img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.label {
  position: absolute;
  top: 0;
  right: 0;
  padding: 15px;
  background-color: #cccccc;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <img class="img" src="https://images.unsplash.com/photo-1500622944204-b135684e99fd?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80" alt="">
  <span class="label">Label</span>
</div></code>```

Here is the CodePen: see the code

But the problem is that I have a label to each picture and I want it to be on the top-right corner of the picture and not the area.

Is there any way to do this with CSS only?

Any help would appreciated! Thank you in advance!

答:
You can do the following:

Wrap image and .label span with another span with class e.g. .inner-wrapper and add to its css

```<code>  position: relative;
  height: 100%;
</code>```

Remove from .wrapper css position: relative; and add

```<code>display: flex;
justify-content: center;
</code>```

Replace in .img css width: 100%;height: 100%; with max-width: 100%;max-height: 100%;

Look in the snippet in full page mode and resize the window.

.wrapper,
.wrapper200 {
  width: 30%;
  height: 400px;
  overflow: hidden;
  border: 1px solid black;
  /*position: relative;*/

  display: flex;
  justify-content: center;
}

.wrapper200 {
  height: 200px;
}

.inner-wrapper {
  position: relative;
  height: 100%;
}

.img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.label {
  position: absolute;
  top: 0;
  right: 0;
  padding: 15px;
  background-color: #cccccc;
}

/* for visual illustration */
.container {
  display: flex;
  justify-content: space-evenly;
  padding: 10px;
  outline: dashed red 1px;
  margin-bottom: 25px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Heigth: 200px</h1>
<div class="container">
  <div class="wrapper200">
    <span class="inner-wrapper">
      <img class="img" src="https://images.unsplash.com/photo-1500622944204-b135684e99fd?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80" alt="">
      <span class="label">Label</span>
    </span>
  </div>

  <div class="wrapper200">
    <span class="inner-wrapper">
      <img class="img" src="https://images.unsplash.com/photo-1581622634376-ff17d073c4f7?ixlib=rb-1.2.1&auto=format&fit=crop&w=1832&q=80" alt="">
      <span class="label">Label</span>
    </span>
  </div>
</div>

<h1>Heigth: 400px</h1>
<div class="container">
  <div class="wrapper">
    <span class="inner-wrapper">
      <img class="img" src="https://images.unsplash.com/photo-1500622944204-b135684e99fd?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80" alt="">
      <span class="label">Label</span>
    </span>
  </div>

  <div class="wrapper">
    <span class="inner-wrapper">
      <img class="img" src="https://images.unsplash.com/photo-1581622634376-ff17d073c4f7?ixlib=rb-1.2.1&auto=format&fit=crop&w=1832&q=80" alt="">
      <span class="label">Label</span>
    </span>
  </div>
</div></code>```

Body:
On my webpage there is an area and I'd like to add a image to it. I don't know the image's size and orientation (portrait or landscape). But I want it to fit the area as it is displayed in the picture:

So, if an image has a landscape orientation it must fill the whole width of the area. See picture 1. If the image's width is bigger that the area's width the image's width must be constrained and if its width is smaller - the image must be widened. However if the image's height is bigger than the area's one the image's height must be constrained. See picture 2.

The similar I want for the portrait image. See picture 2.

In short, what I want can be easily done with object-fit: contain;.

.wrapper {
  width: 30%;
  height: 400px;
  overflow: hidden;
  border: 1px solid black;
  position: relative;
}

.img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.label {
  position: absolute;
  top: 0;
  right: 0;
  padding: 15px;
  background-color: #cccccc;
}

  Label

Here is the CodePen: see the code

But the problem is that I have a label to each picture and I want it to be on the top-right corner of the picture and not the area.

Is there any way to do this with CSS only?

Any help would appreciated! Thank you in advance!

Body:
You can do the following:

Wrap image and .label span with another span with class e.g. .inner-wrapper and add to its css

  position: relative;
  height: 100%;

Remove from .wrapper css position: relative; and add

display: flex;
justify-content: center;

Replace in .img css width: 100%;height: 100%; with max-width: 100%;max-height: 100%;

Look in the snippet in full page mode and resize the window.

.wrapper,
.wrapper200 {
  width: 30%;
  height: 400px;
  overflow: hidden;
  border: 1px solid black;
  /*position: relative;*/

  display: flex;
  justify-content: center;
}

.wrapper200 {
  height: 200px;
}

.inner-wrapper {
  position: relative;
  height: 100%;
}

.img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.label {
  position: absolute;
  top: 0;
  right: 0;
  padding: 15px;
  background-color: #cccccc;
}

/* for visual illustration */
.container {
  display: flex;
  justify-content: space-evenly;
  padding: 10px;
  outline: dashed red 1px;
  margin-bottom: 25px;
}

<h1>Heigth: 200px</h1>
<div class="container">
  <div class="wrapper200">
    <span class="inner-wrapper">
      <img class="img" src="https://images.unsplash.com/photo-1500622944204-b135684e99fd?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80" alt="">
      <span class="label">Label</span>
    </span>
  </div>

  <div class="wrapper200">
    <span class="inner-wrapper">
      <img class="img" src="https://images.unsplash.com/photo-1581622634376-ff17d073c4f7?ixlib=rb-1.2.1&auto=format&fit=crop&w=1832&q=80" alt="">
      <span class="label">Label</span>
    </span>
  </div>
</div>

<h1>Heigth: 400px</h1>
<div class="container">
  <div class="wrapper">
    <span class="inner-wrapper">
      <img class="img" src="https://images.unsplash.com/photo-1500622944204-b135684e99fd?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80" alt="">
      <span class="label">Label</span>
    </span>
  </div>

  <div class="wrapper">
    <span class="inner-wrapper">
      <img class="img" src="https://images.unsplash.com/photo-1581622634376-ff17d073c4f7?ixlib=rb-1.2.1&auto=format&fit=crop&w=1832&q=80" alt="">
      <span class="label">Label</span>
    </span>
  </div>
</div>


问:
How to Swap a Table from Vertical to horizontal in javascript?
What I want is exactly the same attributes but in horizontal view instead of vertical one.

Here I am just providing few json objects to add inside the table, just to see if it will be possible or not. In actual code, I have over 100 json objects for the table.

I tried the Swap method for this issue but I don't know how to use the swap method for Json objects.

My code for vertical table is given below:

var attributes = [{
    "name": "Asset #",
    "display_name": "Asset #",
    "key": "header2",
    "values": {
      "MSSBL": "4-194169767930##1-2H77NZSQ",
      "SNOW": "4-194169767930##1-2H77NZSQ"
    },
    "type": "header",
    "data_type": "Text",
    "editable": "N"
  },
  {
    "name": "Serial Number",
    "display_name": "Serial Number",
    "key": "header3",
    "values": {
      "MSSBL": "21256112##1-2H77NZSQ",
      "SNOW": "NA##1-2H77NZSQ"
    },
    "type": "header",
    "data_type": "Text",
    "editable": "N"
  },
  {
    "name": "ACCOUNT NUMBER",
    "display_name": "ACCOUNT NUMBER",
    "key": "header6",
    "values": {
      "MSSBL": "532649##1-2H77NZSQ",
      "SNOW": "NA##1-2H77NZSQ"
    },
    "type": "header",
    "data_type": "Text",
    "editable": "N"
  }
]

var key = [];

document.write("

");
for (key in attributes[0]) {
  document.write('' + '' + key + '' + '	');
}
document.write("
");
for (var i = 0; i < attributes.length; i++) {
  document.write('
');
  for (key in attributes[i]) {
    document.write('' + attributes[i][key] + '	');
  }
  document.write('
');
}
document.write("
");```

答:
By small reorder in code.

function demo(attributes) {
  var key = [];

  document.write("
");
  var i = 0;
  for (key in attributes[i]) {
    document.write("
");
    document.write('' + '' + key + '' + '	');
    while (i < attributes.length) {
      if (attributes[i][key].constructor == Object) {
        var levelDown = attributes[i][key];
        document.write('');
        for(var subKey in levelDown) {
          document.write(subKey + ':' + levelDown[subKey] + '
');
        }
        document.write('	');
      } else {
        document.write('' + attributes[i][key] + '	');
      }
      i++;
    }
    i = 0;
    document.write("
");
  }
  document.write("
");
document.write("
");
}

demo([{
    "name": "Asset #",
    "display_name": "Asset #",
    "key": "header2",
    "values": {
      "MSSBL": "4-194169767930##1-2H77NZSQ",
      "SNOW": "4-194169767930##1-2H77NZSQ"
    },
    "type": "header",
    "data_type": "Text",
    "editable": "N"
  },
  {
    "name": "Serial Number",
    "display_name": "Serial Number",
    "key": "header3",
    "values": {
      "MSSBL": "21256112##1-2H77NZSQ",
      "SNOW": "NA##1-2H77NZSQ"
    },
    "type": "header",
    "data_type": "Text",
    "editable": "N"
  },
  {
    "name": "ACCOUNT NUMBER",
    "display_name": "ACCOUNT NUMBER",
    "key": "header6",
    "values": {
      "MSSBL": "532649##1-2H77NZSQ",
      "SNOW": "NA##1-2H77NZSQ"
    },
    "type": "header",
    "data_type": "Text",
    "editable": "N"
  }
]);```
</div>
</div>
</p>

<p>Or using 2 dimensional arrays to reorder data before table generation.
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function demo(attributes) {
  var colsData = [];

  document.write("<table border==\"1\"><tr>");
  for (key in attributes[0]) {
    colsData.push([key]);
  }
  for (var i = 0; i < attributes.length; i++) {
    var j = 0;
    for (key in attributes[i]) {
      var levelDown = attributes[i][key];
      if (attributes[i][key].constructor == Object) {
        var longList = "";
        for(var subKey in levelDown) {
          longList += subKey + ':' + levelDown[subKey] + '<br>';
        }
        levelDown = longList;
      } else longList = levelDown;
      colsData[j].push(levelDown);
      j++;
    }
  }
  for(var i=0;i<colsData.length;i++) {
    document.write("<tr><th>" + colsData[i][0] + "</th><td>" + colsData[i].slice(1).join("</td><td>") + "</td></tr>");
  }
  document.write("</table>");

}

demo([{
    "name": "Asset #",
    "display_name": "Asset #",
    "key": "header2",
    "values": {
      "MSSBL": "4-194169767930##1-2H77NZSQ",
      "SNOW": "4-194169767930##1-2H77NZSQ"
    },
    "type": "header",
    "data_type": "Text",
    "editable": "N"
  },
  {
    "name": "Serial Number",
    "display_name": "Serial Number",
    "key": "header3",
    "values": {
      "MSSBL": "21256112##1-2H77NZSQ",
      "SNOW": "NA##1-2H77NZSQ"
    },
    "type": "header",
    "data_type": "Text",
    "editable": "N"
  },
  {
    "name": "ACCOUNT NUMBER",
    "display_name": "ACCOUNT NUMBER",
    "key": "header6",
    "values": {
      "MSSBL": "532649##1-2H77NZSQ",
      "SNOW": "NA##1-2H77NZSQ"
    },
    "type": "header",
    "data_type": "Text",
    "editable": "N"
  }
]);</code>```

Body:
By small reorder in code.

function demo(attributes) {
  var key = [];

  document.write("<table border==\"1\">");
  var i = 0;
  for (key in attributes[i]) {
    document.write("<tr>");
    document.write('<td>' + '<b>' + key + '</b>' + '</td>');
    while (i < attributes.length) {
      if (attributes[i][key].constructor == Object) {
        var levelDown = attributes[i][key];
        document.write('<td>');
        for(var subKey in levelDown) {
          document.write(subKey + ':' + levelDown[subKey] + '<br>');
        }
        document.write('</td>');
      } else {
        document.write('<td>' + attributes[i][key] + '</td>');
      }
      i++;
    }
    i = 0;
    document.write("</tr>");
  }
  document.write("</tr>");
document.write("</table>");
}

demo([{
    "name": "Asset #",
    "display_name": "Asset #",
    "key": "header2",
    "values": {
      "MSSBL": "4-194169767930##1-2H77NZSQ",
      "SNOW": "4-194169767930##1-2H77NZSQ"
    },
    "type": "header",
    "data_type": "Text",
    "editable": "N"
  },
  {
    "name": "Serial Number",
    "display_name": "Serial Number",
    "key": "header3",
    "values": {
      "MSSBL": "21256112##1-2H77NZSQ",
      "SNOW": "NA##1-2H77NZSQ"
    },
    "type": "header",
    "data_type": "Text",
    "editable": "N"
  },
  {
    "name": "ACCOUNT NUMBER",
    "display_name": "ACCOUNT NUMBER",
    "key": "header6",
    "values": {
      "MSSBL": "532649##1-2H77NZSQ",
      "SNOW": "NA##1-2H77NZSQ"
    },
    "type": "header",
    "data_type": "Text",
    "editable": "N"
  }
]);

Or using 2 dimensional arrays to reorder data before table generation.

function demo(attributes) {
  var colsData = [];

  document.write("<table border==\"1\"><tr>");
  for (key in attributes[0]) {
    colsData.push([key]);
  }
  for (var i = 0; i < attributes.length; i++) {
    var j = 0;
    for (key in attributes[i]) {
      var levelDown = attributes[i][key];
      if (attributes[i][key].constructor == Object) {
        var longList = "";
        for(var subKey in levelDown) {
          longList += subKey + ':' + levelDown[subKey] + '<br>';
        }
        levelDown = longList;
      } else longList = levelDown;
      colsData[j].push(levelDown);
      j++;
    }
  }
  for(var i=0;i<colsData.length;i++) {
    document.write("<tr><th>" + colsData[i][0] + "</th><td>" + colsData[i].slice(1).join("</td><td>") + "</td></tr>");
  }
  document.write("</table>");

}

demo([{
    "name": "Asset #",
    "display_name": "Asset #",
    "key": "header2",
    "values": {
      "MSSBL": "4-194169767930##1-2H77NZSQ",
      "SNOW": "4-194169767930##1-2H77NZSQ"
    },
    "type": "header",
    "data_type": "Text",
    "editable": "N"
  },
  {
    "name": "Serial Number",
    "display_name": "Serial Number",
    "key": "header3",
    "values": {
      "MSSBL": "21256112##1-2H77NZSQ",
      "SNOW": "NA##1-2H77NZSQ"
    },
    "type": "header",
    "data_type": "Text",
    "editable": "N"
  },
  {
    "name": "ACCOUNT NUMBER",
    "display_name": "ACCOUNT NUMBER",
    "key": "header6",
    "values": {
      "MSSBL": "532649##1-2H77NZSQ",
      "SNOW": "NA##1-2H77NZSQ"
    },
    "type": "header",
    "data_type": "Text",
    "editable": "N"
  }
]);


问:
Any idea why I can not assign a unique number to my SavingsAccount?
I have one abstract class Account and one subclass SavingsAccount, but when I create SavingsAccount object it doesn't assign a number like 1001, 1002, 1003 and so on. Any idea why?

```<code>import java.util.ArrayList;

public abstract class Account {
    private String accountType;
    private static double balance = 0;
    private static int accountId;
    private static int accountNumberCounter = 1000;
    private ArrayList<Account> accounts;

    public Account(String acType, int acNumber){
        accountType = acType;
        accountNumberCounter ++;
        accountId = accountNumberCounter;

    }

    public Account() {
        accountNumberCounter++;
        accountId = accountNumberCounter;
    }
    public void addAccounts(Account acc){
        accounts.add(acc);

    }
    public void deposit(double amount){
        balance += amount;
    }
    public abstract boolean withdraw(double value);

    public String getAccountInfo(){
        return "Account type: " + accountType + ", Account number: " + accountId;
    }

    public int getAccountNumber(){
        return accountId;
    }
    public String getAccount(){
        String accountInformation = "Account Number: : " + accountId + "\nAccount Type: " + accountType;
        return accountInformation;
    }
    public void closeCurrentAccount() {
        if (balance < 0) {
            System.out.println("Your balance: " + balance + "Close your debt");
        } else {
            System.out.println("Ending balance: " + balance);
        }
    }

}
</code>```

And this is SavingsAccount

```<code>public class SavingsAccount extends Account {
    private static double balance = 0;
    private static final double RATE = 1.0;
    private static  String accountType = "Savings Account";
    private static int accountId;

    public SavingsAccount(){
        super();
    }

    public double getBalance(){
        return balance;
    }

    public void deposit(double amount){
        balance = balance + amount;
    }

    public boolean withdraw(double amount){
        if (balance<= amount){
            System.out.println("You have only" + amount + "left on your account.");
        return false;
        }
        else{
            balance -= amount;
            System.out.println("You put:" + amount);
            return true;
        }
    }

    public static String getAccountType(){
        return accountType;
    }

    public static double getRate(){
        return RATE;
    }
    public static double calculateRate(){
        return balance += (balance * RATE) / 100;
    }
    public String getAccount(){
        String accountInformation = "Account Number: : " + accountId + "\nAccount Type: " + accountType +
            "\nBalance: " + balance + "\nRate: " + RATE;
        return accountInformation;
    }
}
</code>```

Maybe it's not needed but here is Customer class as well

```<code>import java.util.ArrayList;

public class Customer {
    private String name;
    private String surname;
    private String personalNumber;
    private ArrayList<Account> accounts;

    public Customer(String customerName, String customerSurname, String customerPersonalNumber)
    {
        name = customerName;
        surname = customerSurname;
        personalNumber = customerPersonalNumber;
        this.accounts = new ArrayList<Account>();
    }
    public Customer(){

    }
    public String getName(){
        return name;
    }
    public String getSurname(){
        return surname;
    }
    public String getPersonalNumber(){
        return personalNumber;
    }
    public void setName(String aName){
        name = aName;
    }
    public void setSurname(String aSurname){
        surname = aSurname;
    }

    public void setPersonalNumber(String aPersonalNumber){
        personalNumber = aPersonalNumber;
    }

    public void addAccounts(Account acc){
        accounts.add(acc);
    }

    public String getCustomerInfo(){
        return  name + " " +  surname + " " + personalNumber;
    }

    public int getFirstAccountNumber(){
        return accounts.get(0).getAccountNumber();

    }
    public int getLastAccountNumber(){
        return accounts.get(accounts.size()-1).getAccountNumber();
    }

    public ArrayList<Account> getAllAccounts(){
        return accounts;
    }
}
</code>```

When I do some tests this unique number doesn't get assigned.

Is it something wrong with a constructor?

答:
You marked accountId as static as well, so every instance of Account will acquire the same id, that is the latest you "generated".

Just mark accountId as a normal instance variable (i.e., remove static).

As a side note, re-declaring accountId in SavingsAccount breaks encapsulation and is, frankly, weird. You inherited getAccountNumber() from Account. Use that instead of accessing accountId directly. You're treating it as a read-only variable anyway.

Body:
I have one abstract class Account and one subclass SavingsAccount, but when I create SavingsAccount object it doesn't assign a number like 1001, 1002, 1003 and so on. Any idea why?

import java.util.ArrayList;

public abstract class Account {
    private String accountType;
    private static double balance = 0;
    private static int accountId;
    private static int accountNumberCounter = 1000;
    private ArrayList<Account> accounts;

    public Account(String acType, int acNumber){
        accountType = acType;
        accountNumberCounter ++;
        accountId = accountNumberCounter;

    }

    public Account() {
        accountNumberCounter++;
        accountId = accountNumberCounter;
    }
    public void addAccounts(Account acc){
        accounts.add(acc);

    }
    public void deposit(double amount){
        balance += amount;
    }
    public abstract boolean withdraw(double value);

    public String getAccountInfo(){
        return "Account type: " + accountType + ", Account number: " + accountId;
    }

    public int getAccountNumber(){
        return accountId;
    }
    public String getAccount(){
        String accountInformation = "Account Number: : " + accountId + "\nAccount Type: " + accountType;
        return accountInformation;
    }
    public void closeCurrentAccount() {
        if (balance < 0) {
            System.out.println("Your balance: " + balance + "Close your debt");
        } else {
            System.out.println("Ending balance: " + balance);
        }
    }

}

And this is SavingsAccount

public class SavingsAccount extends Account {
    private static double balance = 0;
    private static final double RATE = 1.0;
    private static  String accountType = "Savings Account";
    private static int accountId;

    public SavingsAccount(){
        super();
    }

    public double getBalance(){
        return balance;
    }

    public void deposit(double amount){
        balance = balance + amount;
    }

    public boolean withdraw(double amount){
        if (balance<= amount){
            System.out.println("You have only" + amount + "left on your account.");
        return false;
        }
        else{
            balance -= amount;
            System.out.println("You put:" + amount);
            return true;
        }
    }

    public static String getAccountType(){
        return accountType;
    }

    public static double getRate(){
        return RATE;
    }
    public static double calculateRate(){
        return balance += (balance * RATE) / 100;
    }
    public String getAccount(){
        String accountInformation = "Account Number: : " + accountId + "\nAccount Type: " + accountType +
            "\nBalance: " + balance + "\nRate: " + RATE;
        return accountInformation;
    }
}

Maybe it's not needed but here is Customer class as well

import java.util.ArrayList;

public class Customer {
    private String name;
    private String surname;
    private String personalNumber;
    private ArrayList<Account> accounts;

    public Customer(String customerName, String customerSurname, String customerPersonalNumber)
    {
        name = customerName;
        surname = customerSurname;
        personalNumber = customerPersonalNumber;
        this.accounts = new ArrayList<Account>();
    }
    public Customer(){

    }
    public String getName(){
        return name;
    }
    public String getSurname(){
        return surname;
    }
    public String getPersonalNumber(){
        return personalNumber;
    }
    public void setName(String aName){
        name = aName;
    }
    public void setSurname(String aSurname){
        surname = aSurname;
    }

    public void setPersonalNumber(String aPersonalNumber){
        personalNumber = aPersonalNumber;
    }

    public void addAccounts(Account acc){
        accounts.add(acc);
    }

    public String getCustomerInfo(){
        return  name + " " +  surname + " " + personalNumber;
    }

    public int getFirstAccountNumber(){
        return accounts.get(0).getAccountNumber();

    }
    public int getLastAccountNumber(){
        return accounts.get(accounts.size()-1).getAccountNumber();
    }

    public ArrayList<Account> getAllAccounts(){
        return accounts;
    }
}

When I do some tests this unique number doesn't get assigned.

Is it something wrong with a constructor?


问:
pandas copy value from one column to another if condition is met
I have a dataframe:

```<code>df =
col1  col2  col3
1      2     3
1      4     6
3      7     2
</code>```

I want to edit df, such that when the value of col1 is smaller than 2 , take the value from col3.

So I will get:

```<code>new_df =
col1  col2  col3
3      2     3
6      4     6
3      7     2
</code>```

I tried to use assign and df.loc but it didn't work.

What is the best way to do so?

答:
The most eficient way is by using the loc operator:

mask = df["col1"] < df["col2"]
df.loc[mask, "col1"] = df.loc[mask, "col3"]
```

Body:
I have a dataframe:

df =
col1  col2  col3
1      2     3
1      4     6
3      7     2

I want to edit df, such that when the value of col1 is smaller than 2 , take the value from col3.

So I will get:

new_df =
col1  col2  col3
3      2     3
6      4     6
3      7     2

I tried to use assign and df.loc but it didn't work.

What is the best way to do so?