问:
How to store boost::hana::map inside a class?
I want to store boost::hana::map inside a class so that I can write code like this inside the class:

```<code>if constexpr (boost::hana::contains(map_, "name"_s)){
    std::cout << map_["name"_s] << std::endl;
}
</code>```

But I am getting an error:

note: implicit use of 'this' pointer is only allowed within the
evaluation of a call to a 'constexpr' member function

With this->map_:

note: use of 'this' pointer is only allowed within the evaluation of a call to a 'constexpr' member function

The most interesting thing is if I write like this:

```<code>if (boost::hana::contains(map_, "name"_s)){
    std::cout << map_["name"_s] << std::endl;
}
</code>```

I get an error that there is no such field (it really may not exist, that's why there was an if constexpr).

And yet, it works like this(WHY?!):

```<code>auto map = map_;
if constexpr (boost::hana::contains(map, "name"_s)){
    std::cout << map["name"_s] << std::endl;
}
</code>```

I absolutely don't understand how it works. How is boost::hana::map supposed to be used in this case?

Full example

Stupid workaround

答:
Yes, using this here appears to be right out.

Since the information you are trying to access should be accessible at compile-time, one simple workaround would be to use the type of the entire expression.

```<code>void print_name()
{
    if constexpr (decltype(boost::hana::contains(map, "name"_s)){})
    {
        Print(map["name"_s]);
    }
}
</code>```

Note that hana::contains returns an object derived from std::integral_constant so the contained value is static constexpr, and it implicitly converts to bool.

Body:
I want to store boost::hana::map inside a class so that I can write code like this inside the class:

if constexpr (boost::hana::contains(map_, "name"_s)){
    std::cout << map_["name"_s] << std::endl;
}

But I am getting an error:

note: implicit use of 'this' pointer is only allowed within the
evaluation of a call to a 'constexpr' member function

With this->map_:

note: use of 'this' pointer is only allowed within the evaluation of a call to a 'constexpr' member function

The most interesting thing is if I write like this:

if (boost::hana::contains(map_, "name"_s)){
    std::cout << map_["name"_s] << std::endl;
}

I get an error that there is no such field (it really may not exist, that's why there was an if constexpr).

And yet, it works like this(WHY?!):

auto map = map_;
if constexpr (boost::hana::contains(map, "name"_s)){
    std::cout << map["name"_s] << std::endl;
}

I absolutely don't understand how it works. How is boost::hana::map supposed to be used in this case?

Full example

Stupid workaround

Body:
Yes, using this here appears to be right out.

Since the information you are trying to access should be accessible at compile-time, one simple workaround would be to use the type of the entire expression.

void print_name()
{
    if constexpr (decltype(boost::hana::contains(map, "name"_s)){})
    {
        Print(map["name"_s]);
    }
}

Note that hana::contains returns an object derived from std::integral_constant so the contained value is static constexpr, and it implicitly converts to bool.


来源: stackexchange

问:
TinyMCE - how to remove controls that appear when you select a word or a phrase
When I click a word or a phrase, TinyMCE shows few handy controls like Bold, Italics, Link, H2, H3 and Blockquote. I'd like to remove Htags (h2 and h3) as seen in the screenshot. I'm not sure how to go about achieving this.

Here is how do the initialization:

```<code>$.fn.initTiny = function(selector, data, mode){
    var this_mode = mode ? mode : "";
    this_mode = this_mode == "inline";
    tinymce.init({
      selector: selector,
      inline: this_mode,
      placeholder: 'Type here...',
      menubar: true,
      statusbar: false,
      toolbar: true,
      toolbar_mode: 'scrolling',
      plugins: 'lists searchreplace preview image importcss autoresize searchreplace  powerpaste autolink  directionality code visualblocks visualchars fullscreen  link  table charmap hr insertdatetime advlist lists wordcount imagetools textpattern noneditable charmap quickbars emoticons',
      toolbar: ' undo redo  |  fontselect | fontsizeselect |  bold italic | alignleft aligncenter alignright alignjustify | outdent indent numlist bullist',
      advlist_bullet_styles: 'default,circle,disc,square',
      fontsize_formats: '8pt 10pt 12pt 14pt 16pt 18pt 24pt 36pt 48pt',
      paste_data_images: true,

      autoresize_on_init: true,
      min_height: 400,
      setup: function (editor) {
          editor.on('init', function (e) {
            editor.setContent(data);
          });
          editor.on("focusout",function(){
                $.fn.save_data();
          });
      }

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

Also is that option called context menu?

Have any of you had this scenario before - would love to hear your thoughts....

答:
Got it.It is called as Quick Toolbar

This is how I fixed it

```<code>tinymce.init({
  selector: 'div.tinymce',
  plugins: 'quickbars',
  quickbars_selection_toolbar: true,
  quickbars_selection_toolbar: 'bold italic | formatselect | quicklink   blockquote'
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When I click a word or a phrase, TinyMCE shows few handy controls like Bold, Italics, Link, H2, H3 and Blockquote. I'd like to remove Htags (h2 and h3) as seen in the screenshot. I'm not sure how to go about achieving this.

Here is how do the initialization:

$.fn.initTiny = function(selector, data, mode){
    var this_mode = mode ? mode : "";
    this_mode = this_mode == "inline";
    tinymce.init({
      selector: selector,
      inline: this_mode,
      placeholder: 'Type here...',
      menubar: true,
      statusbar: false,
      toolbar: true,
      toolbar_mode: 'scrolling',
      plugins: 'lists searchreplace preview image importcss autoresize searchreplace  powerpaste autolink  directionality code visualblocks visualchars fullscreen  link  table charmap hr insertdatetime advlist lists wordcount imagetools textpattern noneditable charmap quickbars emoticons',
      toolbar: ' undo redo  |  fontselect | fontsizeselect |  bold italic | alignleft aligncenter alignright alignjustify | outdent indent numlist bullist',
      advlist_bullet_styles: 'default,circle,disc,square',
      fontsize_formats: '8pt 10pt 12pt 14pt 16pt 18pt 24pt 36pt 48pt',
      paste_data_images: true,

      autoresize_on_init: true,
      min_height: 400,
      setup: function (editor) {
          editor.on('init', function (e) {
            editor.setContent(data);
          });
          editor.on("focusout",function(){
                $.fn.save_data();
          });
      }

    });
};

Also is that option called context menu?

Have any of you had this scenario before - would love to hear your thoughts....

Body:
Got it.It is called as Quick Toolbar

This is how I fixed it

tinymce.init({
  selector: 'div.tinymce',
  plugins: 'quickbars',
  quickbars_selection_toolbar: true,
  quickbars_selection_toolbar: 'bold italic | formatselect | quicklink   blockquote'
});


问:
What are practical uses of applicative style?
I am a Scala programmer, learning Haskell now. It's easy to find practical use cases and real world examples for OO concepts, such as decorators, strategy pattern etc. Books and interwebs are filled with it.

I came to the realization that this somehow is not the case for functional concepts. Case in point: applicatives.

I am struggling to find practical use cases for applicatives. Almost all of the tutorials and books I have come across so far provide the examples of [] and Maybe. I expected applicatives to be more applicable than that, seeing all the attention they get in the FP community.

I think I understand the conceptual basis for applicatives (maybe I am wrong), and I have waited long for my moment of enlightenment. But it doesn't seem to be happening. Never while programming, have I had a moment when I would shout with a joy, "Eureka! I can use applicative here!" (except again, for [] and Maybe).

Can someone please guide me how applicatives can be used in a day-to-day programming? How do I start spotting the pattern? Thanks!

答:
Since many applicatives are also monads, I feel there's really two sides to this question.

Why would I want to use the applicative interface instead of the monadic one when both are available?

This is mostly a matter of style. Although monads have the syntactic sugar of do-notation, using applicative style frequently leads to more compact code.

In this example, we have a type Foo and we want to construct random values of this type. Using the monad instance for IO, we might write

data Foo = Foo Int Double

randomFoo = do
    x <- randomIO
    y <- randomIO
    return $ Foo x y
```

<p>The applicative variant is quite a bit shorter.</p>

<pre class="lang-hs prettyprint-override"><code>randomFoo = Foo <$> randomIO <*> randomIO
</code>```

Of course, we could use liftM2 to get similar brevity, however the applicative style is neater than having to rely on arity-specific lifting functions.

In practice, I mostly find myself using applicatives much in the same way like I use point-free style: To avoid naming intermediate values when an operation is more clearly expressed as a composition of other operations.

Why would I want to use an applicative that is not a monad?

Since applicatives are more restricted than monads, this means that you can extract more useful static information about them.

An example of this is applicative parsers. Whereas monadic parsers support sequential composition using (>>=) :: Monad m => m a -> (a -> m b) -> m b, applicative parsers only use (<*>) :: Applicative f => f (a -> b) -> f a -> f b. The types make the difference obvious: In monadic parsers the grammar can change depending on the input, whereas in an applicative parser the grammar is fixed.

By limiting the interface in this way, we can for example determine whether a parser will accept the empty string without running it. We can also determine the first and follow sets, which can be used for optimization, or, as I've been playing with recently, constructing parsers that support better error recovery.

ContentLicense: CC BY-SA 3.0

Body:
Since many applicatives are also monads, I feel there's really two sides to this question.

Why would I want to use the applicative interface instead of the monadic one when both are available?

This is mostly a matter of style. Although monads have the syntactic sugar of do-notation, using applicative style frequently leads to more compact code.

In this example, we have a type Foo and we want to construct random values of this type. Using the monad instance for IO, we might write

data Foo = Foo Int Double

randomFoo = do
    x <- randomIO
    y <- randomIO
    return $ Foo x y

The applicative variant is quite a bit shorter.

randomFoo = Foo <$> randomIO <*> randomIO

Of course, we could use liftM2 to get similar brevity, however the applicative style is neater than having to rely on arity-specific lifting functions.

In practice, I mostly find myself using applicatives much in the same way like I use point-free style: To avoid naming intermediate values when an operation is more clearly expressed as a composition of other operations.

Why would I want to use an applicative that is not a monad?

Since applicatives are more restricted than monads, this means that you can extract more useful static information about them.

An example of this is applicative parsers. Whereas monadic parsers support sequential composition using (>>=) :: Monad m => m a -> (a -> m b) -> m b, applicative parsers only use (<*>) :: Applicative f => f (a -> b) -> f a -> f b. The types make the difference obvious: In monadic parsers the grammar can change depending on the input, whereas in an applicative parser the grammar is fixed.

By limiting the interface in this way, we can for example determine whether a parser will accept the empty string without running it. We can also determine the first and follow sets, which can be used for optimization, or, as I've been playing with recently, constructing parsers that support better error recovery.


问:
In Ruby, can you decide from a main method to return or continue when calling a submethod?
I'm using Pundit gem for my authorization classes, where each controller action is checked against the model policy, to see if action is allowed by the user.

These methods are sometimes becoming quite bloated and unreadable, because I'm checking quite some stuff for some objects.

Now I'm thinking to refactor those methods, and place every "validation" in it's own method:

Previous:

```<code>class PostPolicy < ApplicationPolicy

 def update
   return true if @user.has_role? :admin
   return true if @object.owner == user
   return true if 'some other reason'

   false
 end
end
</code>```

Now ideally, I want to refactor this in something like:

```<code>class PostPolicy < ApplicationPolicy

 def update
   allow_if_user_is_admin
   allow_if_user_owns_record
   allow_for_some_other_reason

   false
 end

 private

 def allow_if_user_is_admin
  # this would go in the parent class, as the logic is the same for other objects
  return true if @user.has_role? :admin
 end
end
</code>```

The problem now is, that the mane update method will keep on going, even if the user is admin, as there's no return. If I would inlcude a return, then the other methods will never be evalutaed. Is there a way in ruby to do kind of a "superreturn", so that when the user is an admin, the main update method would stop evaluting?

Thanks!

答:
What you can do is chain && operators.

As soon as one is false, ruby will not evaluate the others (And the update method will return false).

class PostPolicy < ApplicationPolicy

 def update
   allow_if_user_is_admin &&
     allow_if_user_owns_record &&
     allow_for_some_other_reason &&
 end

 private

 def allow_if_user_is_admin
  # this would go in the parent class, as the logic is the same for other objects
  return true if @user.has_role? :admin
 end
end
```

Body:
I'm using Pundit gem for my authorization classes, where each controller action is checked against the model policy, to see if action is allowed by the user.

These methods are sometimes becoming quite bloated and unreadable, because I'm checking quite some stuff for some objects.

Now I'm thinking to refactor those methods, and place every "validation" in it's own method:

Previous:

class PostPolicy < ApplicationPolicy

 def update
   return true if @user.has_role? :admin
   return true if @object.owner == user
   return true if 'some other reason'

   false
 end
end

Now ideally, I want to refactor this in something like:

class PostPolicy < ApplicationPolicy

 def update
   allow_if_user_is_admin
   allow_if_user_owns_record
   allow_for_some_other_reason

   false
 end

 private

 def allow_if_user_is_admin
  # this would go in the parent class, as the logic is the same for other objects
  return true if @user.has_role? :admin
 end
end

The problem now is, that the mane update method will keep on going, even if the user is admin, as there's no return. If I would inlcude a return, then the other methods will never be evalutaed. Is there a way in ruby to do kind of a "superreturn", so that when the user is an admin, the main update method would stop evaluting?

Thanks!


问:
Loading, please wait message doesn't hide after the data has been loaded
I have this bootstrap-table data table, and after all the data are loaded, the message continues to display. Anyone has any idea why this is happenning? Thank you in advance.

```<code><table class='table table-striped table-hover' id='main_table' data-url={{ db_json }} data-click-to-select='true' data-filter-control="true" clickToSelect='true'>
    <thead>
        <tr>
          <th data-checkbox="true" data-checkbox-enabled="true"></th>
          <th data-field="ID" data-visible="false">Id</th>
          <th data-field="data1" data-filter-control="input">data1</th>
          <th data-field="data2" data-filter-control="select">data2</th>
          <th data-field="data3" data-filter-control="select">data3</th>

        </tr>
    </thead>
</table>
</code>```

答:
What worked for me was overriding Bootstrap´s CSS with my own. In a yourname.css file that has to be declared in HEAD after the Bootstrap CSS link, include this:

```<code>.fixed-table-loading {
    visibility: hidden;
    top: 0px;
    display: none;
}

.loading-wrap {
    visibility: hidden;
    display: none;
}

.table-loading {
    visibility: hidden;
    display: none;
}

.loading {
    visibility: hidden;
    display: none;
}
</code>```

This prevents the div that contains the "Loading, please wait" from appearing.

Body:
I have this bootstrap-table data table, and after all the data are loaded, the message continues to display. Anyone has any idea why this is happenning? Thank you in advance.

          Id
          data1
          data2
          data3

Body:
What worked for me was overriding Bootstrap´s CSS with my own. In a yourname.css file that has to be declared in HEAD after the Bootstrap CSS link, include this:

.fixed-table-loading {
    visibility: hidden;
    top: 0px;
    display: none;
}

.loading-wrap {
    visibility: hidden;
    display: none;
}

.table-loading {
    visibility: hidden;
    display: none;
}

.loading {
    visibility: hidden;
    display: none;
}

This prevents the div that contains the "Loading, please wait" from appearing.


问:
React jsx Error Must be used within the ConnectProvider Component
Public Registry App Step 3

Ive been following the tutorial with no issues. On step 3 ill have to add the PublicUrlRegistrar tag.

Ill get this Error:

Error: This must be used within the ConnectProvider component.

```<code>  22 | const useConnectDispatch = () => {
  23 |   const dispatch = useContext(ConnectDispatchContext);
  24 |   if (!dispatch) {
> 25 |     throw new Error('This must be used within the ConnectProvider component.');
  26 |   }
  27 |   return dispatch;
  28 | };
</code>```

PublicUrlRegistrar.jsx Component

```<code>import React from "react";
import { Text } from "@blockstack/ui";
import { useConnect } from "@stacks/connect-react";
import { bufferCVFromString } from "@stacks/transactions";
import { CONTRACT_ADDRESS, CONTRACT_NAME } from "../assets/constants";

export const PublicUrlRegistrar = ({ userSession }) => {
  const { doContractCall  } = useConnect();  // <<<<<-------------------throwing error--------
  const { username } = userSession.loadUserData();
  const url = `${document.location.origin}/todos/${username}`;

  const register = () => {

    // do the contract call
    doContractCall({
      contractAddress: CONTRACT_ADDRESS,
      contractName: CONTRACT_NAME,
      functionName: "register",
      functionArgs: [bufferCVFromString(username), bufferCVFromString(url)],
      onFinish: (data) => {
        console.log({ data });
      },
    });
  };
  return (
    <>
      <Text
        color="blue"
        cursor="pointer"
        fontSize={1}
        fontWeight="500"
        onClick={() => {
          // register the public URL
          register();
        }}
      >
        Register on-chain
      </Text>
    </>
  );
};
</code>```

It seems useConnect() must be used in the ConnectProvider Component.

Even if I comment out the PublicUrlRegistrar.jsx functions and only leave line 8 ill get the same error.

Im trying to figure out how to use this library correctly

```<code>import { useConnect } from "@stacks/connect-react";
</code>```

I've tried many things and been working on this for a while now with no way to progress.
Any insights into this would be very helpful! Thank you!

答:
This solved the issue, wrap PublicUrlRegistrar in Connect Component.</p>
```<code>  //Sharer.jsx

  import { Connect } from "@stacks/connect-react";

  ...

  const authOption = {
    appDetails: {
      name: 'Todos',
      icon: window.location.origin + '/logo.svg',
    },
    redirectTo: '/',
    userSession: userSession,
  }

  ...

  <Connect authOptions={authOption} >
     <PublicUrlRegistrar userSession={userSession} />
  </Connect>
</code>```

Body:
Public Registry App Step 3

Ive been following the tutorial with no issues. On step 3 ill have to add the PublicUrlRegistrar tag.

Ill get this Error:

Error: This must be used within the ConnectProvider component.

  22 | const useConnectDispatch = () => {
  23 |   const dispatch = useContext(ConnectDispatchContext);
  24 |   if (!dispatch) {
> 25 |     throw new Error('This must be used within the ConnectProvider component.');
  26 |   }
  27 |   return dispatch;
  28 | };

PublicUrlRegistrar.jsx Component

import React from "react";
import { Text } from "@blockstack/ui";
import { useConnect } from "@stacks/connect-react";
import { bufferCVFromString } from "@stacks/transactions";
import { CONTRACT_ADDRESS, CONTRACT_NAME } from "../assets/constants";

export const PublicUrlRegistrar = ({ userSession }) => {
  const { doContractCall  } = useConnect();  // <<<<<-------------------throwing error--------
  const { username } = userSession.loadUserData();
  const url = `${document.location.origin}/todos/${username}`;

  const register = () => {

    // do the contract call
    doContractCall({
      contractAddress: CONTRACT_ADDRESS,
      contractName: CONTRACT_NAME,
      functionName: "register",
      functionArgs: [bufferCVFromString(username), bufferCVFromString(url)],
      onFinish: (data) => {
        console.log({ data });
      },
    });
  };
  return (
    <>
      <Text
        color="blue"
        cursor="pointer"
        fontSize={1}
        fontWeight="500"
        onClick={() => {
          // register the public URL
          register();
        }}
      >
        Register on-chain
      </Text>
    </>
  );
};

It seems useConnect() must be used in the ConnectProvider Component.

Even if I comment out the PublicUrlRegistrar.jsx functions and only leave line 8 ill get the same error.

Im trying to figure out how to use this library correctly

import { useConnect } from "@stacks/connect-react";

I've tried many things and been working on this for a while now with no way to progress.
Any insights into this would be very helpful! Thank you!

Body:
This solved the issue, wrap PublicUrlRegistrar in Connect Component.

  //Sharer.jsx

  import { Connect } from "@stacks/connect-react";

  ...

  const authOption = {
    appDetails: {
      name: 'Todos',
      icon: window.location.origin + '/logo.svg',
    },
    redirectTo: '/',
    userSession: userSession,
  }

  ...

  <Connect authOptions={authOption} >
     <PublicUrlRegistrar userSession={userSession} />
  </Connect>


问:
Javascript Changing button inner text without chaning the icon
I created the following button, and want to change the inner text "test" to other word.

```<code>            <button type="button" id="test"><i class="fa-2x fa-regular fa-floppy-disk"></i>test</button>
</code>```

I tried below method it can change the word but also deleted the icon.

```<code>$('button#bkmarktest').on('click', function(e){
e.preventDefault();
$(this).text("other");
});
</code>```

Is there any way that can only change the word, but keeping the icon, thanks!

答:
You can also replace this using Regex without adding span or any other element in that button. Here is solution:

$('#test').on('click', function(e){
  e.preventDefault();
  const regex = /([^>]+)$/;
  $(this).html($(this).html().replace(regex,'other'));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="test"><i class="fa-2x fa-regular fa-floppy-disk"></i>test</button></code>```

Another solution is to change text inside of  element:

$('#test').on('click', function(e){
  $(this).find('i').text("Other");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="test"><i class="fa-2x fa-regular fa-floppy-disk">test</i></button></code>```

Body:
I created the following button, and want to change the inner text "test" to other word.

            <button type="button" id="test">test</button>

I tried below method it can change the word but also deleted the icon.

$('button#bkmarktest').on('click', function(e){
e.preventDefault();
$(this).text("other");
});

Is there any way that can only change the word, but keeping the icon, thanks!

Body:
You can also replace this using Regex without adding span or any other element in that button. Here is solution:

$('#test').on('click', function(e){
  e.preventDefault();
  const regex = /([^>]+)$/;
  $(this).html($(this).html().replace(regex,'other'));
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="test"><i class="fa-2x fa-regular fa-floppy-disk"></i>test</button>

Another solution is to change text inside of <i> element:

$('#test').on('click', function(e){
  $(this).find('i').text("Other");
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="test"><i class="fa-2x fa-regular fa-floppy-disk">test</i></button>


问:
Install package in the dockerfile
Below is dockerfile with installation details of ffmpeg.

```<code>FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base

RUN sed -i 's/deb.debian.org/mirrors.ustc.edu.cn/g' /etc/apt/sources.list \
    && apt-get update \
    && apt-get install -y ffmpeg \
    && apt-get clean && apt-get autoclean && apt-get autoremove \
    && rm -rf /var/lib/apt/lists/*

RUN apt-get update && apt-get install -y libgdiplus libc6-dev && ln -s /usr/lib/libgdiplus.so /usr/lib/gdiplus.dll
WORKDIR /app
EXPOSE 80
EXPOSE 443
...
</code>```

How can I install different ffmpeg package, more specifically alfg/ffmpeg
in that way to preserve the rest of the dockerfile intact and with same installation path /usr/bin/ffmpeg.

EDIT

Here's my Dockerfile

```<code>#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS build

ARG FFMPEG_VERSION=4.4

ARG PREFIX=/opt/ffmpeg
ARG LD_LIBRARY_PATH=/opt/ffmpeg/lib
ARG MAKEFLAGS="-j4"

# FFmpeg build dependencies.
RUN apk add --update \
  build-base \
  coreutils \
  freetype-dev \
  gcc \
  lame-dev \
  libogg-dev \
  libass \
  libass-dev \
  libvpx-dev \
  libvorbis-dev \
  libwebp-dev \
  libtheora-dev \
  opus-dev \
  openssl \
  openssl-dev \
  pkgconf \
  pkgconfig \
  rtmpdump-dev \
  wget \
  x264-dev \
  x265-dev \
  yasm

# Get fdk-aac from community.
RUN echo http://dl-cdn.alpinelinux.org/alpine/edge/community >> /etc/apk/repositories && \
  apk add --update fdk-aac-dev

# Get rav1e from testing.
RUN echo http://dl-cdn.alpinelinux.org/alpine/edge/testing >> /etc/apk/repositories && \
  apk add --update rav1e-dev

# Get ffmpeg source.
RUN cd /tmp/ && \
  wget http://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.gz && \
  tar zxf ffmpeg-${FFMPEG_VERSION}.tar.gz && rm ffmpeg-${FFMPEG_VERSION}.tar.gz

# Compile ffmpeg.
RUN cd /tmp/ffmpeg-${FFMPEG_VERSION} && \
  ./configure \
  --enable-version3 \
  --enable-gpl \
  --enable-nonfree \
  --enable-small \
  --enable-libmp3lame \
  --enable-libx264 \
  --enable-libx265 \
  --enable-libvpx \
  --enable-libtheora \
  --enable-libvorbis \
  --enable-libopus \
  --enable-libfdk-aac \
  --enable-libass \
  --enable-libwebp \
  --enable-librtmp \
  --enable-librav1e \
  --enable-postproc \
  --enable-libfreetype \
  --enable-openssl \
  --disable-debug \
  --disable-doc \
  --disable-ffplay \
  --extra-cflags="-I${PREFIX}/include" \
  --extra-ldflags="-L${PREFIX}/lib" \
  --extra-libs="-lpthread -lm" \
  --prefix="${PREFIX}" && \
  make && make install && make distclean

FROM mcr.microsoft.com/dotnet/aspnet:6.0
ENV PATH=/opt/ffmpeg/bin:$PATH

RUN apk add --update \
  ca-certificates \
  openssl \
  pcre \
  lame \
  libogg \
  libass \
  libvpx \
  libvorbis \
  libwebp \
  libtheora \
  opus \
  rtmpdump \
  x264-dev \
  x265-dev

COPY --from=build /opt/ffmpeg /opt/ffmpeg
COPY --from=build /usr/lib/libfdk-aac.so.2 /usr/lib/libfdk-aac.so.2
COPY --from=build /usr/lib/librav1e.so /usr/lib/librav1e.so

RUN apt-get update && apt-get install -y libgdiplus libc6-dev && ln -s /usr/lib/libgdiplus.so /usr/lib/gdiplus.dll

WORKDIR /app
EXPOSE 80
EXPOSE 49154
ENV ASPNETCORE_URLS=http://+:49154

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["CarPrjP/CarPrjP.csproj", "CarPrjP/"]
RUN dotnet restore "CarPrjP/CarPrjP.csproj"
COPY . .
WORKDIR "/src/CarPrjP"
RUN dotnet build "CarPrjP.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "CarPrjP.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "CarPrjP.dll"]
</code>```

not sure with this changes what is the path for ffmpe binaries. With the old Dockerfile (1st in this example) it worked fine (when it comes to finding ffmpeg binaries). It was referenced from the code like this

```<code>string ffmpegPath = "/usr/bin/ffmpeg";
string ffprobePath = "/usr/bin/ffprobe";
</code>```

Now with new dockerfile I'm getting

System.ComponentModel.Win32Exception: 'An error occurred trying to
start process '/usr/bin/ffmpeg' with working directory '/app'. No such
file or directory
Obviously I need to change path to match the new installation path, tried with /opt/ffmpeg but that doesn't work.

答:
You can find the Dockerfile for their build here https://github.com/alfg/docker-ffmpeg/blob/master/Dockerfile.

Maybe you can copy parts of their dockerfile into yours.

Here's my attempt. I switched your aspnet image to alpine since the ffmpeg dockerfile is alpine and changing package managers seemed like a big task.

```<code>FROM alpine:3.14 as build

ARG FFMPEG_VERSION=4.4

ARG PREFIX=/opt/ffmpeg
ARG LD_LIBRARY_PATH=/opt/ffmpeg/lib
ARG MAKEFLAGS="-j4"

# FFmpeg build dependencies.
RUN apk add --update \
  build-base \
  coreutils \
  freetype-dev \
  gcc \
  lame-dev \
  libogg-dev \
  libass \
  libass-dev \
  libvpx-dev \
  libvorbis-dev \
  libwebp-dev \
  libtheora-dev \
  opus-dev \
  openssl \
  openssl-dev \
  pkgconf \
  pkgconfig \
  rtmpdump-dev \
  wget \
  x264-dev \
  x265-dev \
  yasm

# Get fdk-aac from community.
RUN echo http://dl-cdn.alpinelinux.org/alpine/edge/community >> /etc/apk/repositories && \
  apk add --update fdk-aac-dev

# Get rav1e from testing.
RUN echo http://dl-cdn.alpinelinux.org/alpine/edge/testing >> /etc/apk/repositories && \
  apk add --update rav1e-dev

# Get ffmpeg source.
RUN cd /tmp/ && \
  wget http://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.gz && \
  tar zxf ffmpeg-${FFMPEG_VERSION}.tar.gz && rm ffmpeg-${FFMPEG_VERSION}.tar.gz

# Compile ffmpeg.
RUN cd /tmp/ffmpeg-${FFMPEG_VERSION} && \
  ./configure \
  --enable-version3 \
  --enable-gpl \
  --enable-nonfree \
  --enable-small \
  --enable-libmp3lame \
  --enable-libx264 \
  --enable-libx265 \
  --enable-libvpx \
  --enable-libtheora \
  --enable-libvorbis \
  --enable-libopus \
  --enable-libfdk-aac \
  --enable-libass \
  --enable-libwebp \
  --enable-librtmp \
  --enable-librav1e \
  --enable-postproc \
  --enable-libfreetype \
  --enable-openssl \
  --disable-debug \
  --disable-doc \
  --disable-ffplay \
  --extra-cflags="-I${PREFIX}/include" \
  --extra-ldflags="-L${PREFIX}/lib" \
  --extra-libs="-lpthread -lm" \
  --prefix="${PREFIX}" && \
  make && make install && make distclean

FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-alpine
ENV PATH=/opt/ffmpeg/bin:$PATH

RUN apk add --update \
  ca-certificates \
  openssl \
  pcre \
  lame \
  libogg \
  libass \
  libvpx \
  libvorbis \
  libwebp \
  libtheora \
  opus \
  rtmpdump \
  x264-dev \
  x265-dev

COPY --from=build /opt/ffmpeg /opt/ffmpeg
COPY --from=build /usr/lib/libfdk-aac.so.2 /usr/lib/libfdk-aac.so.2
COPY --from=build /usr/lib/librav1e.so /usr/lib/librav1e.so
</code>```

Build and run

```<code>docker build -t test .
docker run --rm test /bin/sh -c "ffmpeg -version; dotnet --list-runtimes"
</code>```

Title: Install package in the dockerfile

Body:
Below is dockerfile with installation details of ffmpeg.

FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base

RUN sed -i 's/deb.debian.org/mirrors.ustc.edu.cn/g' /etc/apt/sources.list \
    && apt-get update \
    && apt-get install -y ffmpeg \
    && apt-get clean && apt-get autoclean && apt-get autoremove \
    && rm -rf /var/lib/apt/lists/*

RUN apt-get update && apt-get install -y libgdiplus libc6-dev && ln -s /usr/lib/libgdiplus.so /usr/lib/gdiplus.dll
WORKDIR /app
EXPOSE 80
EXPOSE 443
...

How can I install different ffmpeg package, more specifically alfg/ffmpeg
in that way to preserve the rest of the dockerfile intact and with same installation path /usr/bin/ffmpeg.

EDIT

Here's my Dockerfile

#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS build

ARG FFMPEG_VERSION=4.4

ARG PREFIX=/opt/ffmpeg
ARG LD_LIBRARY_PATH=/opt/ffmpeg/lib
ARG MAKEFLAGS="-j4"

# FFmpeg build dependencies.
RUN apk add --update \
  build-base \
  coreutils \
  freetype-dev \
  gcc \
  lame-dev \
  libogg-dev \
  libass \
  libass-dev \
  libvpx-dev \
  libvorbis-dev \
  libwebp-dev \
  libtheora-dev \
  opus-dev \
  openssl \
  openssl-dev \
  pkgconf \
  pkgconfig \
  rtmpdump-dev \
  wget \
  x264-dev \
  x265-dev \
  yasm

# Get fdk-aac from community.
RUN echo http://dl-cdn.alpinelinux.org/alpine/edge/community >> /etc/apk/repositories && \
  apk add --update fdk-aac-dev

# Get rav1e from testing.
RUN echo http://dl-cdn.alpinelinux.org/alpine/edge/testing >> /etc/apk/repositories && \
  apk add --update rav1e-dev

# Get ffmpeg source.
RUN cd /tmp/ && \
  wget http://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.gz && \
  tar zxf ffmpeg-${FFMPEG_VERSION}.tar.gz && rm ffmpeg-${FFMPEG_VERSION}.tar.gz

# Compile ffmpeg.
RUN cd /tmp/ffmpeg-${FFMPEG_VERSION} && \
  ./configure \
  --enable-version3 \
  --enable-gpl \
  --enable-nonfree \
  --enable-small \
  --enable-libmp3lame \
  --enable-libx264 \
  --enable-libx265 \
  --enable-libvpx \
  --enable-libtheora \
  --enable-libvorbis \
  --enable-libopus \
  --enable-libfdk-aac \
  --enable-libass \
  --enable-libwebp \
  --enable-librtmp \
  --enable-librav1e \
  --enable-postproc \
  --enable-libfreetype \
  --enable-openssl \
  --disable-debug \
  --disable-doc \
  --disable-ffplay \
  --extra-cflags="-I${PREFIX}/include" \
  --extra-ldflags="-L${PREFIX}/lib" \
  --extra-libs="-lpthread -lm" \
  --prefix="${PREFIX}" && \
  make && make install && make distclean

FROM mcr.microsoft.com/dotnet/aspnet:6.0
ENV PATH=/opt/ffmpeg/bin:$PATH

RUN apk add --update \
  ca-certificates \
  openssl \
  pcre \
  lame \
  libogg \
  libass \
  libvpx \
  libvorbis \
  libwebp \
  libtheora \
  opus \
  rtmpdump \
  x264-dev \
  x265-dev

COPY --from=build /opt/ffmpeg /opt/ffmpeg
COPY --from=build /usr/lib/libfdk-aac.so.2 /usr/lib/libfdk-aac.so.2
COPY --from=build /usr/lib/librav1e.so /usr/lib/librav1e.so

RUN apt-get update && apt-get install -y libgdiplus libc6-dev && ln -s /usr/lib/libgdiplus.so /usr/lib/gdiplus.dll

WORKDIR /app
EXPOSE 80
EXPOSE 49154
ENV ASPNETCORE_URLS=http://+:49154

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["CarPrjP/CarPrjP.csproj", "CarPrjP/"]
RUN dotnet restore "CarPrjP/CarPrjP.csproj"
COPY . .
WORKDIR "/src/CarPrjP"
RUN dotnet build "CarPrjP.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "CarPrjP.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "CarPrjP.dll"]

not sure with this changes what is the path for ffmpe binaries. With the old Dockerfile (1st in this example) it worked fine (when it comes to finding ffmpeg binaries). It was referenced from the code like this

string ffmpegPath = "/usr/bin/ffmpeg";
string ffprobePath = "/usr/bin/ffprobe";

Now with new dockerfile I'm getting

System.ComponentModel.Win32Exception: 'An error occurred trying to
start process '/usr/bin/ffmpeg' with working directory '/app'. No such
file or directory
Obviously I need to change path to match the new installation path, tried with /opt/ffmpeg but that doesn't work.

Body:
You can find the Dockerfile for their build here https://github.com/alfg/docker-ffmpeg/blob/master/Dockerfile.

Maybe you can copy parts of their dockerfile into yours.

Here's my attempt. I switched your aspnet image to alpine since the ffmpeg dockerfile is alpine and changing package managers seemed like a big task.

FROM alpine:3.14 as build

ARG FFMPEG_VERSION=4.4

ARG PREFIX=/opt/ffmpeg
ARG LD_LIBRARY_PATH=/opt/ffmpeg/lib
ARG MAKEFLAGS="-j4"

# FFmpeg build dependencies.
RUN apk add --update \
  build-base \
  coreutils \
  freetype-dev \
  gcc \
  lame-dev \
  libogg-dev \
  libass \
  libass-dev \
  libvpx-dev \
  libvorbis-dev \
  libwebp-dev \
  libtheora-dev \
  opus-dev \
  openssl \
  openssl-dev \
  pkgconf \
  pkgconfig \
  rtmpdump-dev \
  wget \
  x264-dev \
  x265-dev \
  yasm

# Get fdk-aac from community.
RUN echo http://dl-cdn.alpinelinux.org/alpine/edge/community >> /etc/apk/repositories && \
  apk add --update fdk-aac-dev

# Get rav1e from testing.
RUN echo http://dl-cdn.alpinelinux.org/alpine/edge/testing >> /etc/apk/repositories && \
  apk add --update rav1e-dev

# Get ffmpeg source.
RUN cd /tmp/ && \
  wget http://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.gz && \
  tar zxf ffmpeg-${FFMPEG_VERSION}.tar.gz && rm ffmpeg-${FFMPEG_VERSION}.tar.gz

# Compile ffmpeg.
RUN cd /tmp/ffmpeg-${FFMPEG_VERSION} && \
  ./configure \
  --enable-version3 \
  --enable-gpl \
  --enable-nonfree \
  --enable-small \
  --enable-libmp3lame \
  --enable-libx264 \
  --enable-libx265 \
  --enable-libvpx \
  --enable-libtheora \
  --enable-libvorbis \
  --enable-libopus \
  --enable-libfdk-aac \
  --enable-libass \
  --enable-libwebp \
  --enable-librtmp \
  --enable-librav1e \
  --enable-postproc \
  --enable-libfreetype \
  --enable-openssl \
  --disable-debug \
  --disable-doc \
  --disable-ffplay \
  --extra-cflags="-I${PREFIX}/include" \
  --extra-ldflags="-L${PREFIX}/lib" \
  --extra-libs="-lpthread -lm" \
  --prefix="${PREFIX}" && \
  make && make install && make distclean

FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-alpine
ENV PATH=/opt/ffmpeg/bin:$PATH

RUN apk add --update \
  ca-certificates \
  openssl \
  pcre \
  lame \
  libogg \
  libass \
  libvpx \
  libvorbis \
  libwebp \
  libtheora \
  opus \
  rtmpdump \
  x264-dev \
  x265-dev

COPY --from=build /opt/ffmpeg /opt/ffmpeg
COPY --from=build /usr/lib/libfdk-aac.so.2 /usr/lib/libfdk-aac.so.2
COPY --from=build /usr/lib/librav1e.so /usr/lib/librav1e.so

Build and run

docker build -t test .
docker run --rm test /bin/sh -c "ffmpeg -version; dotnet --list-runtimes"


问:
Pandas long to wide by subsets
I have a dataframe of the following format

```<code>YR    WEEK  ACCOUNT   Tax   AMOUNT   SURCHARGE  Label
2021   1      1       10     5000     5          0
2021   1      2       20     10000    10         1
2021   2      1       20     2000      2         0
2021   2      2        5      10       3         1
2021   3      1       20     10000    10         1
2021   3      2       10     40000    50         1
</code>```

I want to reshape it such that, it results in the following

```<code>ACCOUNT    YR    WEEK    Tax_1   Amount_1   Surcharge_1    Tax_2   Amount_2   Surcharge_2   Label
1         2021    2      10       5000         5             20     2000        2           0
2         2021    2      20       10000       10             5      10          3           1
1         2021    3      0         2000        2             20     10000       10          1
2         2021    3      5          10       3              10     40000        50          1
</code>```

Each row is reshaped such that it is a function of the past 2 rows by account, year and week. And the Label is the current label of the WEEK
I tried first to reshape it to wide

```<code>df.pivot('ACCOUNT', columns=['YR','WEEK'])
</code>```

And was going to try a reshape after, but the pivotresulted in NaN values
Any ideas on how I can achieve this in pandas
Thx!

答:
What you want is not a pivot, as pivot reshapes the data, while you here want to duplicate/shift it (you have more data cells after than before).

To take a simpler example, the goal is to go from something like this (6 values):

```<code>   id  group value
0   1      1     A
1   1      2     B
2   1      3     C
3   2      1     D
4   2      2     E
5   2      3     F
</code>```

to this (8 values):

```<code>   id  group_1 value_1  group_2 value_2
0   1        1       A        2       B
1   1        2       B        3       C
2   2        1       D        2       E
3   2        2       E        3       F
</code>```

How do we do it?

You can achieve what you want by doing a selection per group and concatenating the two outputs:

```<code>cols = ['YR', 'ACCOUNT']
g = df.sort_values(by=['YR', 'WEEK']).groupby(cols)

out = (
 pd.concat([g.apply(lambda d: d.drop(columns=cols+['WEEK']).iloc[:-1]).droplevel(-1).add_suffix('_1'),
            g.apply(lambda d: d.drop(columns=cols).iloc[1:]).droplevel(-1).add_suffix('_2')
            ], axis=1)
   .reset_index()
)
</code>```

NB. the output is slightly different for the labels

output:

```<code>     YR  ACCOUNT  Tax_1  AMOUNT_1  SURCHARGE_1  Label_1  WEEK_2  Tax_2  AMOUNT_2  SURCHARGE_2  Label_2
0  2021        1     10      5000            5        0       2     20      2000            2        0
1  2021        1     20      2000            2        0       3     20     10000           10        1
2  2021        2     20     10000           10        1       2      5        10            3        1
3  2021        2      5        10            3        1       3     10     40000           50        1
</code>```

slightly more condensed version

NB. This requires not to have NaNs

```<code>cols = ['YR', 'ACCOUNT']
g = df.sort_values(by=['YR', 'WEEK']).groupby(cols)
pd.concat([g.shift().add_suffix('_1'), df.add_suffix('_2')], axis=1).dropna(how='any', axis=0)
</code>```

Title: Pandas long to wide by subsets

Body:
I have a dataframe of the following format

YR    WEEK  ACCOUNT   Tax   AMOUNT   SURCHARGE  Label
2021   1      1       10     5000     5          0
2021   1      2       20     10000    10         1
2021   2      1       20     2000      2         0
2021   2      2        5      10       3         1
2021   3      1       20     10000    10         1
2021   3      2       10     40000    50         1

I want to reshape it such that, it results in the following

ACCOUNT    YR    WEEK    Tax_1   Amount_1   Surcharge_1    Tax_2   Amount_2   Surcharge_2   Label
1         2021    2      10       5000         5             20     2000        2           0
2         2021    2      20       10000       10             5      10          3           1
1         2021    3      0         2000        2             20     10000       10          1
2         2021    3      5          10       3              10     40000        50          1

Each row is reshaped such that it is a function of the past 2 rows by account, year and week. And the Label is the current label of the WEEK
I tried first to reshape it to wide

df.pivot('ACCOUNT', columns=['YR','WEEK'])

And was going to try a reshape after, but the pivotresulted in NaN values
Any ideas on how I can achieve this in pandas
Thx!

Body:
What you want is not a pivot, as pivot reshapes the data, while you here want to duplicate/shift it (you have more data cells after than before).

To take a simpler example, the goal is to go from something like this (6 values):

   id  group value
0   1      1     A
1   1      2     B
2   1      3     C
3   2      1     D
4   2      2     E
5   2      3     F

to this (8 values):

   id  group_1 value_1  group_2 value_2
0   1        1       A        2       B
1   1        2       B        3       C
2   2        1       D        2       E
3   2        2       E        3       F

How do we do it?

You can achieve what you want by doing a selection per group and concatenating the two outputs:

cols = ['YR', 'ACCOUNT']
g = df.sort_values(by=['YR', 'WEEK']).groupby(cols)

out = (
 pd.concat([g.apply(lambda d: d.drop(columns=cols+['WEEK']).iloc[:-1]).droplevel(-1).add_suffix('_1'),
            g.apply(lambda d: d.drop(columns=cols).iloc[1:]).droplevel(-1).add_suffix('_2')
            ], axis=1)
   .reset_index()
)

NB. the output is slightly different for the labels

output:

     YR  ACCOUNT  Tax_1  AMOUNT_1  SURCHARGE_1  Label_1  WEEK_2  Tax_2  AMOUNT_2  SURCHARGE_2  Label_2
0  2021        1     10      5000            5        0       2     20      2000            2        0
1  2021        1     20      2000            2        0       3     20     10000           10        1
2  2021        2     20     10000           10        1       2      5        10            3        1
3  2021        2      5        10            3        1       3     10     40000           50        1

slightly more condensed version

NB. This requires not to have NaNs

cols = ['YR', 'ACCOUNT']
g = df.sort_values(by=['YR', 'WEEK']).groupby(cols)
pd.concat([g.shift().add_suffix('_1'), df.add_suffix('_2')], axis=1).dropna(how='any', axis=0)


问:
How to delete some elements from UITableViewController with CoreData?
So i can add some city from API and when i try to delete some city from UITableViewController then all cities are deleted. Can someone help me please where i made mistake. I gave an example of the code below</p>
```<code>//this is my delete func from CoreData
 func deleteCity() {

        let fetchRequest: NSFetchRequest<Cities> = Cities.fetchRequest()

        if let cities = try? context.fetch(fetchRequest) {
            for city in cities {
                context.delete(city)
            }
        }

        do {
            try context.save()
        } catch let error as NSError {
            print(error.localizedDescription)
        }
    }
    //this is how i create cities array
    func fetch() -> [Weather] {

        let fetchRequest: NSFetchRequest<Cities> = Cities.fetchRequest()

        do {
            let cities = try context.fetch(fetchRequest)
            return cities.map({Weather(name: $0.cityName ?? "", temp: $0.cityTemp)})
        } catch  {
            return []
        }
    }

    //and this how i try to delete city from UITableViewController

  override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let actionDel = UIContextualAction(style: .destructive, title: "Delete") { _, _, completionHandler in
            self.cityTemps.remove(at: indexPath.row)
            self.coreDataManaer.deleteCity()
            DispatchQueue.main.async {
                tableView.reloadData()
            }
        }
        let actions = UISwipeActionsConfiguration(actions: [actionDel])
        return actions
    }

</code>```

答:
Your deleteCity() function actually deletes all cities. Here's why:

First your fetch request fetches all cities, since there's no predicate:

```<code>let fetchRequest: NSFetchRequest<Cities> = Cities.fetchRequest()
</code>```

Then your loop goes through the results of the fetch and deletes every city it finds-- which is all of them.

```<code>if let cities = try? context.fetch(fetchRequest) {
    for city in cities {
        context.delete(city)
    }
}
</code>```

It sounds like you want to delete only the city that the person swipes on, which is the city at indexPath in the last function above. You could change your fetch request, but you probably don't need to do that. In your data source methods (for example your tableView(_:cellForRowAt:) function) you already have a list of the cities you're showing, probably in an array. To delete a single city then, you'd do something like

Get the correct city from that array

Delete that city from the managed object context.

Body:
So i can add some city from API and when i try to delete some city from UITableViewController then all cities are deleted. Can someone help me please where i made mistake. I gave an example of the code below

//this is my delete func from CoreData
 func deleteCity() {

        let fetchRequest: NSFetchRequest<Cities> = Cities.fetchRequest()

        if let cities = try? context.fetch(fetchRequest) {
            for city in cities {
                context.delete(city)
            }
        }

        do {
            try context.save()
        } catch let error as NSError {
            print(error.localizedDescription)
        }
    }
    //this is how i create cities array
    func fetch() -> [Weather] {

        let fetchRequest: NSFetchRequest<Cities> = Cities.fetchRequest()

        do {
            let cities = try context.fetch(fetchRequest)
            return cities.map({Weather(name: $0.cityName ?? "", temp: $0.cityTemp)})
        } catch  {
            return []
        }
    }

    //and this how i try to delete city from UITableViewController

  override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let actionDel = UIContextualAction(style: .destructive, title: "Delete") { _, _, completionHandler in
            self.cityTemps.remove(at: indexPath.row)
            self.coreDataManaer.deleteCity()
            DispatchQueue.main.async {
                tableView.reloadData()
            }
        }
        let actions = UISwipeActionsConfiguration(actions: [actionDel])
        return actions
    }

Body:
Your deleteCity() function actually deletes all cities. Here's why:

First your fetch request fetches all cities, since there's no predicate:

let fetchRequest: NSFetchRequest<Cities> = Cities.fetchRequest()

Then your loop goes through the results of the fetch and deletes every city it finds-- which is all of them.

if let cities = try? context.fetch(fetchRequest) {
    for city in cities {
        context.delete(city)
    }
}

It sounds like you want to delete only the city that the person swipes on, which is the city at indexPath in the last function above. You could change your fetch request, but you probably don't need to do that. In your data source methods (for example your tableView(_:cellForRowAt:) function) you already have a list of the cities you're showing, probably in an array. To delete a single city then, you'd do something like

Get the correct city from that array

Delete that city from the managed object context.


问:
dbOpenDynaset vs dbOpenTable with index
I just did a split of an Access database and I've got a couple of linked tables that use a line similar to VL2.Index = "ReportKey" after being opened via VL2.Index = db.OpenRecordset("VolunteerDetail", dbOpenTable), which no longer works because they're now linked tables.

So what do I do instead? I can open the recordset by omitting the dbOpenTable part, but it's the index that I don't know how to handle, because the dynaset piece doesn't have an index in the same way. I understand that VL2.Index = "ReportKey" is assigning the name to the index, but what is the equivalent of that with dbOpenDynaset? I've seen references to things like FindFirst, but those don't make sense to me.

What do I replace VL2.Index = "ReportKey"` with, when using a dynaset?

答:
It is FindFirst and FindNext to use, so if these "don't make sense to me", read up the documentation:

Recordset.FindFirst method (DAO)

Title: dbOpenDynaset vs dbOpenTable with index


问:
refer to own class in python class method when subclassing
I'm wanting to keep a class attribute on a base class which keeps track of all names of all its subclasses.

class SomeThing(abc.ABC):
   subclass_names = set()
   def __init_subclass__(cls):
       cls.subclass_names.add(cls.__name__)
       print(cls.subclass_names)
```
<p>However, I'm afraid that because I'm creating an abstract class, users might overwrite the class attribute I am keeping.</p>
<pre class="lang-py prettyprint-override"><code>class SomeSub(SomeThing):
    subclass_names = set()

out: {'SomeSub'}

class SomeOtherSub(SomeThing):
    pass

out: {'SomeOtherThing'} # should be {'SomeSub', 'SomeOtherThing'}
# but SomeOtherThing is registered in SomeOtherThing's, not SomeThing's subclass_names

</code>```

Is there a way to refer to "own class" in a class method? It seems like the cls in __init_subclass__ ends up being whichever subclass is passed in (which makes sense).

答:
Use a double-underscore to designate an attribute as private to a particular class.  Python will "name-mangle" it behind the scenes to ensure that child classes can't accidentally override it.</p>
```<code>import abc

class SomeThing(abc.ABC):
   __subclass_names = set()
   def __init_subclass__(cls):
       SomeThing.__subclass_names.add(cls.__name__)
       print(SomeThing.__subclass_names)

class SomeSub(SomeThing):
    __subclass_names = set()

# {'SomeSub'}

class SomeOtherThing(SomeThing):
    pass

# {'SomeOtherSub', 'SomeSub'}
</code>```

Body:
I'm wanting to keep a class attribute on a base class which keeps track of all names of all its subclasses.

class SomeThing(abc.ABC):
   subclass_names = set()
   def __init_subclass__(cls):
       cls.subclass_names.add(cls.__name__)
       print(cls.subclass_names)

However, I'm afraid that because I'm creating an abstract class, users might overwrite the class attribute I am keeping.

class SomeSub(SomeThing):
    subclass_names = set()

out: {'SomeSub'}

class SomeOtherSub(SomeThing):
    pass

out: {'SomeOtherThing'} # should be {'SomeSub', 'SomeOtherThing'}
# but SomeOtherThing is registered in SomeOtherThing's, not SomeThing's subclass_names

Is there a way to refer to "own class" in a class method? It seems like the cls in __init_subclass__ ends up being whichever subclass is passed in (which makes sense).

Body:
Use a double-underscore to designate an attribute as private to a particular class.  Python will "name-mangle" it behind the scenes to ensure that child classes can't accidentally override it.

import abc

class SomeThing(abc.ABC):
   __subclass_names = set()
   def __init_subclass__(cls):
       SomeThing.__subclass_names.add(cls.__name__)
       print(SomeThing.__subclass_names)

class SomeSub(SomeThing):
    __subclass_names = set()

# {'SomeSub'}

class SomeOtherThing(SomeThing):
    pass

# {'SomeOtherSub', 'SomeSub'}


问:
Python Tkinter use iconbitmap without needing a filepath (like a picture url)
i am trying to include a iconbitmap in my Tkinter project, but i want it to be a single .exe file. For that reason i dont want to use other files, that are needed (like in the same directory). My idea was, to just use an URL of a picture. What i found was that:

```<code>root.tk.call('wm', 'iconphoto', root._w, tk.PhotoImage(file="icon.png"))
</code>```

How is it possible to use a URL instead? Or maybe there is a completely other way to store the icon, except as a seperate file.

答:
You can embed PhotoImage data as base64 and include it directly in the code. Take the contents of a file of any supported file type (eg: gif, png for newer versions of python) and encode it with base64.

The following code defines some image data, then uses it to create a PhotoImage. The resulting image can be used anywhere a PhotoImage can be used.

```<code>image_data = """
    R0lGODlhGAAYAPZvAAIaLgwmOwcnQQcoQBMxSBc4VBQ6Vhk7VRY9WhY+XSI4RxJC
    ZRRCZi9KYSFNbzJUbSJOcCZVeiZUeyBWfy1Zei5afB1Wgh1XgyFXgDpjgSVjkyZl
    liZnmCxrmixsmjZtlSptoCpuoSxxqCxzqjh1oTV3qDR4qD5/rjV8tDV+tUFlgUZp
    hFNwhVVyh0ZzlUh7nnB8hUF8pkJ8pkx+oTuBuFmBn3SEkHeOn3mNnUeBqUiBqUqD
    q1CBpFKCpVuDoVyEokeGs0eHs0aKvkaMvlGOuGqKom+Pp3yUpziEwTiFwz2KxT+K
    xE6VylKUw1qaxV6fx0CQ0E+b1lCd1l6h0Wiq1Wyu12Wp22aq3FOi4F2s5WCt5W64
    7XW24Xu743u/6omfsZymroqhso6jtJynsJ2psaS1w6S2xIvH7YvI7d/h5ODi5eDk
    5+Dm6uLn7OPo7QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    AAAAAAAAAAAAAAAAACH+SUNvcHlyaWdodCBJTkNPUlMgR21iSCAod3d3Lmljb25l
    eHBlcmllbmNlLmNvbSkgLSBVbmxpY2Vuc2VkIHByZXZpZXcgaW1hZ2UAIfkEBQAA
    bwAsAAAAABgAGAAAB9eAb4KDhIWGh4iJiouMjY6PiGkwCgAACjBqj2ABBSw3Ny0H
    AWONYwIqYmFfX2FiKwNki2kEFEZFRba3RhUEa4o2Cy41NT/FPsMuDDaKDRYfLzM8
    PT0zMy8fFw2KBRoeJDI6Ojs5MSQdGwaKCCAmJ0FE8ERAJyUhCYoPIjRDTU5PT06a
    CKEx4oEiHBuWMJlCpUoVKlOYKOFwQxEbB0ikXOHSpQsXK1GSQGizyIwFKFq8oDnj
    JQsUDGYalYmAYsqWLVhSSIjpqM2RDBMuZDjiBpLRo0iTKjUaCAA7
"""

the_image = tk.PhotoImage(data=image_data)
</code>```

Body:
i am trying to include a iconbitmap in my Tkinter project, but i want it to be a single .exe file. For that reason i dont want to use other files, that are needed (like in the same directory). My idea was, to just use an URL of a picture. What i found was that:

root.tk.call('wm', 'iconphoto', root._w, tk.PhotoImage(file="icon.png"))

How is it possible to use a URL instead? Or maybe there is a completely other way to store the icon, except as a seperate file.

Body:
You can embed PhotoImage data as base64 and include it directly in the code. Take the contents of a file of any supported file type (eg: gif, png for newer versions of python) and encode it with base64.

The following code defines some image data, then uses it to create a PhotoImage. The resulting image can be used anywhere a PhotoImage can be used.

image_data = """
    R0lGODlhGAAYAPZvAAIaLgwmOwcnQQcoQBMxSBc4VBQ6Vhk7VRY9WhY+XSI4RxJC
    ZRRCZi9KYSFNbzJUbSJOcCZVeiZUeyBWfy1Zei5afB1Wgh1XgyFXgDpjgSVjkyZl
    liZnmCxrmixsmjZtlSptoCpuoSxxqCxzqjh1oTV3qDR4qD5/rjV8tDV+tUFlgUZp
    hFNwhVVyh0ZzlUh7nnB8hUF8pkJ8pkx+oTuBuFmBn3SEkHeOn3mNnUeBqUiBqUqD
    q1CBpFKCpVuDoVyEokeGs0eHs0aKvkaMvlGOuGqKom+Pp3yUpziEwTiFwz2KxT+K
    xE6VylKUw1qaxV6fx0CQ0E+b1lCd1l6h0Wiq1Wyu12Wp22aq3FOi4F2s5WCt5W64
    7XW24Xu743u/6omfsZymroqhso6jtJynsJ2psaS1w6S2xIvH7YvI7d/h5ODi5eDk
    5+Dm6uLn7OPo7QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    AAAAAAAAAAAAAAAAACH+SUNvcHlyaWdodCBJTkNPUlMgR21iSCAod3d3Lmljb25l
    eHBlcmllbmNlLmNvbSkgLSBVbmxpY2Vuc2VkIHByZXZpZXcgaW1hZ2UAIfkEBQAA
    bwAsAAAAABgAGAAAB9eAb4KDhIWGh4iJiouMjY6PiGkwCgAACjBqj2ABBSw3Ny0H
    AWONYwIqYmFfX2FiKwNki2kEFEZFRba3RhUEa4o2Cy41NT/FPsMuDDaKDRYfLzM8
    PT0zMy8fFw2KBRoeJDI6Ojs5MSQdGwaKCCAmJ0FE8ERAJyUhCYoPIjRDTU5PT06a
    CKEx4oEiHBuWMJlCpUoVKlOYKOFwQxEbB0ikXOHSpQsXK1GSQGizyIwFKFq8oDnj
    JQsUDGYalYmAYsqWLVhSSIjpqM2RDBMuZDjiBpLRo0iTKjUaCAA7
"""

the_image = tk.PhotoImage(data=image_data)


问:
Confused when I should and shouldn't use "const" in C
I have a dictionary that goes like this:

```<code>typedef struct dictNode {
    int key;
    char *value;
    struct dictNode *next;
} Dict;
</code>```

And a get() function that goes like this:

```<code>char *get(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            return currPtr->value;
        }

        currPtr = currPtr->next;
    }
}
</code>```

Compiling this code produces the following error:

dict.c:85: warning: initialization discards qualifiers from pointer target type

This warning refers to the line:

```<code>Dict *currPtr = dict;
</code>```

If I add a "const" before that line like this:

```<code>const Dict *currPtr = dict;
</code>```

The warning goes away...

1) First thing I don't understand is this: I added "const" to the dict argument in get() so that the compiler warns me if I try to change the address dict is pointing to, otherwise I won't be able to access the dictionary in the main program cause I lost the address I was pointing too. Now, I'm creating a new pointer, currPtr, that points to the same place as dict. This way, I use this pointer instead, to traverse the dictionary and keep dict pointer intact. Why do I also need to have const for currPtr?

2) Second thing I don't understand is this: The line currPtr = currPtr->next; is changing the currPtr pointer, so, why doesn't the compile warn me about that if I added a const to currPtr?

Then I have a del() function that goes like this:

```<code>Dict *del(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;
    Dict *prevPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            prevPtr->next = currPtr->next;
            free(currPtr);
        }

        prevPtr = currPtr;
        currPtr = currPtr->next;
    }

    return dict;
}
</code>```

Please note that I'm aware that this delete function code is not complete, it does not correctly work if I want to delete the first element for instance. It doesn't matter, I'll finish later, it suffices to demonstrate my problem...

3) So, in the get() function I needed to add const to currPtr but in this del() function, I don't need to add const to currPtr nor prevPtr? In both functions I am changing the currPtr pointer and in the case of the del() function I'm changing the prevPtr pointer too. Why does the get() function require me to add a const before currPtr and the del() function does not require me to add a const before currPtr and prevPtr?

I can basically resume this whole post to: When and where exactly in my get() and del() functions should I use const and why, and, when and where I shouldn't?

答:
The "Dummies Guide to const":

Use it whenever you can.

OwnerDisplayName: Nazgulled

ContentLicense: CC BY-SA 2.5

Body:
I have a dictionary that goes like this:

typedef struct dictNode {
    int key;
    char *value;
    struct dictNode *next;
} Dict;

And a get() function that goes like this:

char *get(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            return currPtr->value;
        }

        currPtr = currPtr->next;
    }
}

Compiling this code produces the following error:

dict.c:85: warning: initialization discards qualifiers from pointer target type

This warning refers to the line:

Dict *currPtr = dict;

If I add a "const" before that line like this:

const Dict *currPtr = dict;

The warning goes away...

1) First thing I don't understand is this: I added "const" to the dict argument in get() so that the compiler warns me if I try to change the address dict is pointing to, otherwise I won't be able to access the dictionary in the main program cause I lost the address I was pointing too. Now, I'm creating a new pointer, currPtr, that points to the same place as dict. This way, I use this pointer instead, to traverse the dictionary and keep dict pointer intact. Why do I also need to have const for currPtr?

2) Second thing I don't understand is this: The line currPtr = currPtr->next; is changing the currPtr pointer, so, why doesn't the compile warn me about that if I added a const to currPtr?

Then I have a del() function that goes like this:

Dict *del(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;
    Dict *prevPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            prevPtr->next = currPtr->next;
            free(currPtr);
        }

        prevPtr = currPtr;
        currPtr = currPtr->next;
    }

    return dict;
}

Please note that I'm aware that this delete function code is not complete, it does not correctly work if I want to delete the first element for instance. It doesn't matter, I'll finish later, it suffices to demonstrate my problem...

3) So, in the get() function I needed to add const to currPtr but in this del() function, I don't need to add const to currPtr nor prevPtr? In both functions I am changing the currPtr pointer and in the case of the del() function I'm changing the prevPtr pointer too. Why does the get() function require me to add a const before currPtr and the del() function does not require me to add a const before currPtr and prevPtr?

I can basically resume this whole post to: When and where exactly in my get() and del() functions should I use const and why, and, when and where I shouldn't?


问:
Remove duplicates from list but keep by color preference
I have a list that contains duplicates like this..

```<code>"id","name","type","price","color"
"23","item1","t-shirt","37","red"
"56","item66","jumper","3","yellow"
"366","item7","jumper","55","yellow"
"366","item7","jumper","55","red"
"745","item 9","t-shirt","45","green"
"3245","item 12","t-shirt","67","red"
"3245","item 12","t-shirt","67","purple"
"654","item 88","jumper","66","blue"
"2","item 99","jumper","77","purple"
"2","item 99","jumper","77","green"
</code>```

I want to remove the duplicates but keep the one by order or color prefence by this table..

```<code>1 - Red
2 - Purple
3 - Blue
4 - Green
5 - Yellow
</code>```

So the final list would look like this..

```<code>"id","name","type","price","color"
"23","item1","t-shirt","37","red"
"56","item66","jumper","3","yellow"
"366","item7","jumper","55","red"
"745","item 9","t-shirt","45","green"
"3245","item 12","t-shirt","67","red"
"654","item 88","jumper","66","blue"
"2","item 99","jumper","77","purple"
</code>```

What is my best approach? Would sorting them by color prefernce first and then removing duplicates be a workable solution? If so, does anybody have an example of something similar being achieved? I am not sure how to sort by order of preferenc.

答:
Sort the data according to the color preference and then groupby id, the first element and then get all the first elements of the group.

```<code>from itertools import groupby

data = [
    ["id", "name", "type", "price", "color"],
    ["23", "item1", "t-shirt", "37", "red"],
    ["56", "item66", "jumper", "3", "yellow"],
    ["366", "item7", "jumper", "55", "yellow"],
    ["366", "item7", "jumper", "55", "red"],
    ["745", "item 9", "t-shirt", "45", "green"],
    ["3245", "item 12", "t-shirt", "67", "red"],
    ["3245", "item 12", "t-shirt", "67", "purple"],
    ["654", "item 88", "jumper", "66", "blue"],
    ["2", "item 99", "jumper", "77", "purple"],
    ["2", "item 99", "jumper", "77", "green"]
]
header = data[0]
data = data[1:]
preference = {
    "red": 1,
    "purple": 2,
    "blue": 3,
    "green": 4,
    "yellow": 5
}

def key_function(element):
    color = element[-1]
    return (element[0], preference[color])

data.sort(key=key_function)
print(header)
for group, grouping in groupby(data, key=lambda x: x[0]):
    print(next(grouping))
</code>```

OUTPUT

```<code>['id', 'name', 'type', 'price', 'color']
['2', 'item 99', 'jumper', '77', 'purple']
['23', 'item1', 't-shirt', '37', 'red']
['3245', 'item 12', 't-shirt', '67', 'red']
['366', 'item7', 'jumper', '55', 'red']
['56', 'item66', 'jumper', '3', 'yellow']
['654', 'item 88', 'jumper', '66', 'blue']
['745', 'item 9', 't-shirt', '45', 'green']
</code>```

Body:
I have a list that contains duplicates like this..

"id","name","type","price","color"
"23","item1","t-shirt","37","red"
"56","item66","jumper","3","yellow"
"366","item7","jumper","55","yellow"
"366","item7","jumper","55","red"
"745","item 9","t-shirt","45","green"
"3245","item 12","t-shirt","67","red"
"3245","item 12","t-shirt","67","purple"
"654","item 88","jumper","66","blue"
"2","item 99","jumper","77","purple"
"2","item 99","jumper","77","green"

I want to remove the duplicates but keep the one by order or color prefence by this table..

1 - Red
2 - Purple
3 - Blue
4 - Green
5 - Yellow

So the final list would look like this..

"id","name","type","price","color"
"23","item1","t-shirt","37","red"
"56","item66","jumper","3","yellow"
"366","item7","jumper","55","red"
"745","item 9","t-shirt","45","green"
"3245","item 12","t-shirt","67","red"
"654","item 88","jumper","66","blue"
"2","item 99","jumper","77","purple"

What is my best approach? Would sorting them by color prefernce first and then removing duplicates be a workable solution? If so, does anybody have an example of something similar being achieved? I am not sure how to sort by order of preferenc.

Body:
Sort the data according to the color preference and then groupby id, the first element and then get all the first elements of the group.

from itertools import groupby

data = [
    ["id", "name", "type", "price", "color"],
    ["23", "item1", "t-shirt", "37", "red"],
    ["56", "item66", "jumper", "3", "yellow"],
    ["366", "item7", "jumper", "55", "yellow"],
    ["366", "item7", "jumper", "55", "red"],
    ["745", "item 9", "t-shirt", "45", "green"],
    ["3245", "item 12", "t-shirt", "67", "red"],
    ["3245", "item 12", "t-shirt", "67", "purple"],
    ["654", "item 88", "jumper", "66", "blue"],
    ["2", "item 99", "jumper", "77", "purple"],
    ["2", "item 99", "jumper", "77", "green"]
]
header = data[0]
data = data[1:]
preference = {
    "red": 1,
    "purple": 2,
    "blue": 3,
    "green": 4,
    "yellow": 5
}

def key_function(element):
    color = element[-1]
    return (element[0], preference[color])

data.sort(key=key_function)
print(header)
for group, grouping in groupby(data, key=lambda x: x[0]):
    print(next(grouping))

OUTPUT

['id', 'name', 'type', 'price', 'color']
['2', 'item 99', 'jumper', '77', 'purple']
['23', 'item1', 't-shirt', '37', 'red']
['3245', 'item 12', 't-shirt', '67', 'red']
['366', 'item7', 'jumper', '55', 'red']
['56', 'item66', 'jumper', '3', 'yellow']
['654', 'item 88', 'jumper', '66', 'blue']
['745', 'item 9', 't-shirt', '45', 'green']


问:
How to create a login on a test server without active directory domain?
I'm trying to create a login on our test server with:

CREATE LOGIN [<DOMAIN>\<LOGIN>] FROM WINDOWS;
GO
```
<p>As opposed to the live server the test server does not have any active directory. So it fails with:</p>
```Windows NT user or group 'DOMAIN\LOGIN' not found. Check the name again.
```

Worth to be mentioned, that on the test server we use a backup of a database dump from the last release and apply new migrations to this dump. This means, that this error would not occur, if a more recent dump from the live server was used, where the active directory login already exists.

To enable proper testing, we discussed three possible options:

Recreate the active directory on the test server: I would like to avoid this, because nobody really wants to administer an additional active directory clone for testing purposes.

Use a more recent database dump: The problem here is, that the live server is not ours and we only have restricted access to it. It is possible, but still not the optimal solution in regard to practicability. Also, it would mean, that we would play in migrations to the live server before having tested them on the test server.

Alternative SQL syntax: I am aware, that there alternative ways of creating logins, e.g., CREATE LOGIN <login_name> WITH PASSWORD. But I could not think of any way, which allows us to create logins depending on which system we are on.

Option 3 is our strong favorite, but we are missing a piece to the puzzle. Anything we are missing here?

答:
You can create a new user on your local computer.
And then add this new user to the instance.</p>
```<code>CREATE LOGIN [<domainName or your hostName>\<login_name>] FROM WINDOWS;
</code>```

Body:
I'm trying to create a login on our test server with:

CREATE LOGIN [<DOMAIN>\<LOGIN>] FROM WINDOWS;
GO

As opposed to the live server the test server does not have any active directory. So it fails with:

Windows NT user or group 'DOMAIN\LOGIN' not found. Check the name again.

Worth to be mentioned, that on the test server we use a backup of a database dump from the last release and apply new migrations to this dump. This means, that this error would not occur, if a more recent dump from the live server was used, where the active directory login already exists.

To enable proper testing, we discussed three possible options:

Recreate the active directory on the test server: I would like to avoid this, because nobody really wants to administer an additional active directory clone for testing purposes.

Use a more recent database dump: The problem here is, that the live server is not ours and we only have restricted access to it. It is possible, but still not the optimal solution in regard to practicability. Also, it would mean, that we would play in migrations to the live server before having tested them on the test server.

Alternative SQL syntax: I am aware, that there alternative ways of creating logins, e.g., CREATE LOGIN <login_name> WITH PASSWORD. But I could not think of any way, which allows us to create logins depending on which system we are on.

Option 3 is our strong favorite, but we are missing a piece to the puzzle. Anything we are missing here?

Body:
You can create a new user on your local computer.
And then add this new user to the instance.

CREATE LOGIN [<domainName or your hostName>\<login_name>] FROM WINDOWS;


问:
ASP.NET Core how to upload image to SQL Server database?
I am trying to do a simple app to register users to a database with name, surname, profile photo etc. then edit or delete them. I am planning to upload the image as IFileForm, then convert it to varbinary for SQL Server. But I am having a problem on how to implement uploading the image. The code works for other members. Any help would be appreciated.

My user model class for API

```<code>public partial class User
{
    public string UserId { get; set; };
    public string UserName { get; set; };
    public string UserSurname { get; set; };
    public string UserBirthdate { get; set; };
    public byte[] UserPicture { get; set; };
}
</code>```

Post method for my API

```<code>public async Task<ActionResult<User>> PostUser(User user)
{
    _context.UserTable1s.Add(user);

    try
    {
        await _context.SaveChangesAsync();
    }
    catch (DbUpdateException)
    {
        if (UserExists(user.UserId))
        {
             return Conflict();
        }
        else
        {
            throw;
        }
    }

    return CreatedAtAction("GetUser", new { id = user.UserId }, user);
}
</code>```

My user model for Web App

```<code>public class User
{
    public string UserId { get; set; }
    public string UserName { get; set; }
    public string UserSurname { get; set; }
    public string UserBirthdate { get; set; }
    public IFormFile UserPicture { get; set; }
}
</code>```

Post method for Web App to consume API

```<code>public async Task<IActionResult> AddUser(User user)
{
    User receivedUser = new User();

    using (var httpClient = new HttpClient())
    {
        StringContent content = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json");

        using (var response = await httpClient.PostAsync("https://localhost:7252/api/Users", content))
        {
            string apiResponse = await response.Content.ReadAsStringAsync();
            receivedUser = JsonConvert.DeserializeObject<User>(apiResponse);
        }
    }

    return View(receivedUser);
}
</code>```

And finally the view for AddUser. Removed the code for other members because too long.

```<code> <div class="col-md-4">
        <form asp-action="AddUser" enctype="multipart/form-data">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            /*some more code here for other members*/
            <div class="form-group">
                <label asp-for="UserPicture" type="file"class="control-label">User Picture</label>
                <input asp-for="UserPicture" type="file" class="form-control" />
                <span asp-validation-for="UserPicture" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</code>```

EDIT:
I managed to make it work after editing vega_gf's answer a little. I am pretty sure it is not the most optimal way but it works for now.

My AddUser method now:

```<code>public async Task<IActionResult> AddUser(User user, [FromForm]IFormFile imgfile)
{
    User receivedUser = new User();
    using (var httpClient = new HttpClient())
    {
            if (imgfile != null)
            {
                using var dataStream = new MemoryStream();
                await imgfile.CopyToAsync(dataStream);
                byte[] imageBytes = dataStream.ToArray();
                string base64String = Convert.ToBase64String(imageBytes);
                user.UserPicture = base64String;
            }

        StringContent content = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json");

        using (var response = await httpClient.PostAsync("https://localhost:7252/api/Users", content))
        {
            string apiResponse = await response.Content.ReadAsStringAsync();
            receivedUser = JsonConvert.DeserializeObject<User>(apiResponse);
        }
    }
    return View(receivedUser);
}
</code>```

Added an IFormFile imgfile property to my model and used it in view like this:

```<code><div class="form-group">
                <label asp-for="imgfile" type="file"class="control-label">User Picture</label>
                <input asp-for="imgfile" type="file" class="form-control" />
                <span asp-validation-for="imgfile" class="text-danger"></span>
            </div>
</code>```

答:
First I would change image type to string(optional)

Then on your AddUser method you add this

```<code>[BindProperty]
public IFormFile ImageFile { get; set; }
public string Msg { get; set; }
public static readonly List<string> ImageExtensions = new() { ".JPG", ".BMP", ".PNG" }; //to restrict file extensions

if (HttpContext.Request.Form.Files.Count > 0)// check if the user uploded something
{
     ImageFile = HttpContext.Request.Form.Files.GetFile("file_Main");
     if (ImageFile != null)
     {
          var extension = Path.GetExtension(ImageFile.FileName);//get file name
          if (ImageExtensions.Contains(extension.ToUpperInvariant()))
          {
              using var dataStream = new MemoryStream();
              await ImageFile.CopyToAsync(dataStream);
              byte[] imageBytes = dataStream.ToArray(); // you can save this to your byte array variable and remove the 2 lines below
              string base64String = Convert.ToBase64String(imageBytes);
              User.UserPicture = base64String; // to save the image as base64String
              }
              else
              {
                  Msg = "image format must be in JPG, BMP or PNG"; //Custom error message
                  return Page();
              }
          }
      }
}
</code>```

on your view just add this

```<code>@if (Model.User.UserPicture != null)
{
    <img src="data:image/png;base64,@Html.DisplayFor(model => model.User.UserPicture)" height="40" width="40">
}
</code>```

Body:
I am trying to do a simple app to register users to a database with name, surname, profile photo etc. then edit or delete them. I am planning to upload the image as IFileForm, then convert it to varbinary for SQL Server. But I am having a problem on how to implement uploading the image. The code works for other members. Any help would be appreciated.

My user model class for API

public partial class User
{
    public string UserId { get; set; };
    public string UserName { get; set; };
    public string UserSurname { get; set; };
    public string UserBirthdate { get; set; };
    public byte[] UserPicture { get; set; };
}

Post method for my API

public async Task<ActionResult<User>> PostUser(User user)
{
    _context.UserTable1s.Add(user);

    try
    {
        await _context.SaveChangesAsync();
    }
    catch (DbUpdateException)
    {
        if (UserExists(user.UserId))
        {
             return Conflict();
        }
        else
        {
            throw;
        }
    }

    return CreatedAtAction("GetUser", new { id = user.UserId }, user);
}

My user model for Web App

public class User
{
    public string UserId { get; set; }
    public string UserName { get; set; }
    public string UserSurname { get; set; }
    public string UserBirthdate { get; set; }
    public IFormFile UserPicture { get; set; }
}

Post method for Web App to consume API

public async Task<IActionResult> AddUser(User user)
{
    User receivedUser = new User();

    using (var httpClient = new HttpClient())
    {
        StringContent content = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json");

        using (var response = await httpClient.PostAsync("https://localhost:7252/api/Users", content))
        {
            string apiResponse = await response.Content.ReadAsStringAsync();
            receivedUser = JsonConvert.DeserializeObject<User>(apiResponse);
        }
    }

    return View(receivedUser);
}

And finally the view for AddUser. Removed the code for other members because too long.

        <form asp-action="AddUser" enctype="multipart/form-data">

            /*some more code here for other members*/

                User Picture
                <input asp-for="UserPicture" type="file" class="form-control" />

                <input type="submit" value="Create" class="btn btn-primary" />

        </form>

EDIT:
I managed to make it work after editing vega_gf's answer a little. I am pretty sure it is not the most optimal way but it works for now.

My AddUser method now:

public async Task<IActionResult> AddUser(User user, [FromForm]IFormFile imgfile)
{
    User receivedUser = new User();
    using (var httpClient = new HttpClient())
    {
            if (imgfile != null)
            {
                using var dataStream = new MemoryStream();
                await imgfile.CopyToAsync(dataStream);
                byte[] imageBytes = dataStream.ToArray();
                string base64String = Convert.ToBase64String(imageBytes);
                user.UserPicture = base64String;
            }

        StringContent content = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json");

        using (var response = await httpClient.PostAsync("https://localhost:7252/api/Users", content))
        {
            string apiResponse = await response.Content.ReadAsStringAsync();
            receivedUser = JsonConvert.DeserializeObject<User>(apiResponse);
        }
    }
    return View(receivedUser);
}

Added an IFormFile imgfile property to my model and used it in view like this:

                User Picture
                <input asp-for="imgfile" type="file" class="form-control" />

Body:
First I would change image type to string(optional)

Then on your AddUser method you add this

[BindProperty]
public IFormFile ImageFile { get; set; }
public string Msg { get; set; }
public static readonly List<string> ImageExtensions = new() { ".JPG", ".BMP", ".PNG" }; //to restrict file extensions

if (HttpContext.Request.Form.Files.Count > 0)// check if the user uploded something
{
     ImageFile = HttpContext.Request.Form.Files.GetFile("file_Main");
     if (ImageFile != null)
     {
          var extension = Path.GetExtension(ImageFile.FileName);//get file name
          if (ImageExtensions.Contains(extension.ToUpperInvariant()))
          {
              using var dataStream = new MemoryStream();
              await ImageFile.CopyToAsync(dataStream);
              byte[] imageBytes = dataStream.ToArray(); // you can save this to your byte array variable and remove the 2 lines below
              string base64String = Convert.ToBase64String(imageBytes);
              User.UserPicture = base64String; // to save the image as base64String
              }
              else
              {
                  Msg = "image format must be in JPG, BMP or PNG"; //Custom error message
                  return Page();
              }
          }
      }
}

on your view just add this

@if (Model.User.UserPicture != null)
{
    <img src="data:image/png;base64,@Html.DisplayFor(model => model.User.UserPicture)" height="40" width="40">
}


问:
How to copy a folder recursively in Rust?
From what I see in the documentation, there is no out-of-the-box solution.</p>

答:
I borrowed Doug's solution, but I think rayon makes the best bed sheets, so I did it with rayon. This is quick and dirty in that it doesn't handle any error cases (threads just crash instead of finishing) but you'll know when that happens if you use this as-is as it won't hide it. Should be easy to add your own error handling if you want it. I'm also a very amateurish programmer and my code shouldn't be used by anybody with any sense. I made it in such a way that you could use the indicatif crate to very easily add a nice looking progress bar.

When doing network copies of large folders of a ton of small files, this does the job pretty quickly in my tests.

No platform specific bits are used, so it should run anywhere that rust std compiles.

use clap::Parser;
use rayon::Scope;
use std::fs::{self, DirEntry};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use crossbeam::queue::SegQueue;
use rayon::iter::{ParallelIterator, IntoParallelRefIterator};

#[derive(Debug, Parser)]
#[clap(name = "mtcopy", about = "Multi-threaded copy...in rust!")]
struct Opt {
    /// Source directory
    source: String,

    /// Destination directory
    dest: String,
}

fn main() {
    let args = Opt::parse();
    copy(&args.source, &args.dest);
}

fn copy<U: AsRef<Path>, V: AsRef<Path>>(from: &U, to: &V) {

    let start = std::time::Instant::now();
    let source = PathBuf::from(from.as_ref());
    let dest = PathBuf::from(to.as_ref());

    let total_size = AtomicU64::new(0);
    // Could possibly use dashmap for the bag instead, slower but it can be used to avoid duplicate files from e.g. symlinks
    let bag = SegQueue::new();
    rayon::scope(|s| scan(&source, &bag, s, &total_size));

    // Convert to a vec so that we can rayon it and throw the bag away
    let files = bag.into_iter().collect::<Vec<_>>();
    let total_size = total_size.into_inner();

    files.par_iter().for_each(|entry| {
        let entry = entry.as_ref().unwrap();
        let spath = entry.path();
        let stem = spath.strip_prefix(&source).unwrap();
        let dpath = dest.join(&stem);
        let size = entry.metadata().unwrap().len();
        fs::create_dir_all(&dpath.parent().unwrap()).unwrap();
        // println!("  copy: {:?} -> {:?}", &path, &dpath);
        fs::copy(&spath, &dpath).unwrap();
    });

    println!("Copied {} files, {} bytes in {}",  files.len(), total_size, start.elapsed().as_secs());
}

fn scan<'a, U: AsRef<Path>>(src: &U, bag: &'a SegQueue<Result<DirEntry, std::io::Error>>, s: &Scope<'a>, total_size: &'a AtomicU64) {
    let dir = fs::read_dir(src).unwrap();
    dir.into_iter().for_each(|entry| {
        let info = entry.as_ref().unwrap();
        let path = info.path();

        if path.is_dir() {
            s.spawn(move |s| scan(&path, bag, s, total_size))
        } else {
            // println!("{}", path.as_os_str().to_string_lossy());
            let filelength = info.metadata().unwrap().len();
            total_size.fetch_add(filelength, Ordering::SeqCst);
            bag.push(entry)
        }
    })
}
```


问:
Microsoft ReportViewer control (Web) & displaying error messages
I have a Microsoft ReportViewer control on my web page. However, if someone types in an invalid input for one of the parameters then it displays a rather unfriendly error message where the report should go. For example: The value provided for the report parameter 'pToDate' is not valid for its type. (rsReportParameterTypeMismatch)

The control prompts the user for the information with "To Date" and "pToDate" is the internal name of the parameter. The users won't know this, nor will they likely react well to "rsReportParameterTypeMismatch" (what ever that means!? [while thinking like a user])

As I couldn't find somewhere in the ReportViewer control to put any error or custom message,  my solution was to create a label in which to put a more friendly error message. This works insofar as the friendly error message is displayed.

My problem is that once the user has corrected their mistake and clicks "View Report" the report is displayed but the error message is still visible. I've set the label text to string.Empty, I've set the label to Visible = false. I've tried this in various places, ensured the code is hit, but to no avail.

So, is there any way to get custom messages to appear and disappear with a ReportViewer control?

答:
Okay - I've got something that works

Previous I had this:

```<code><asp:Label runat="server" ID="ReportErrorMessage" Visible="false" CssClass="report-error-message">
</asp:Label>
</code>```

which I was updating in the code behind like this:

```<code>ReportErrorMessage.Text = GetErrorMessage(reportException);
ReportErrorMessage.Visible = true;
</code>```

and then removing like this:

```<code>ReportErrorMessage.Visible = false;
ReportErrorMessage.Text = string.Empty;
</code>```

The latter part didn't work.

I eventually realised that the ReportViewer control is using partial rendering and so wasn't actually changing the label at all (and consdering that, I've still not quite figured out how the initial display actually worked, but anyway...)

The solution was to wrap the label in an update panel like this:

```<code><asp:UpdatePanel runat="server">
    <ContentTemplate>
        <asp:Label runat="server" ID="ReportErrorMessage" Visible="false" CssClass="report-error-message">
        </asp:Label>
    </ContentTemplate>
</asp:UpdatePanel>
</code>```

UPDATE

I've also added a full explanation onto my blog: Friendly Error Messages with Microsoft Report Viewer

Body:
Okay - I've got something that works

Previous I had this:

<asp:Label runat="server" ID="ReportErrorMessage" Visible="false" CssClass="report-error-message">
</asp:Label>

which I was updating in the code behind like this:

ReportErrorMessage.Text = GetErrorMessage(reportException);
ReportErrorMessage.Visible = true;

and then removing like this:

ReportErrorMessage.Visible = false;
ReportErrorMessage.Text = string.Empty;

The latter part didn't work.

I eventually realised that the ReportViewer control is using partial rendering and so wasn't actually changing the label at all (and consdering that, I've still not quite figured out how the initial display actually worked, but anyway...)

The solution was to wrap the label in an update panel like this:

<asp:UpdatePanel runat="server">
    <ContentTemplate>
        <asp:Label runat="server" ID="ReportErrorMessage" Visible="false" CssClass="report-error-message">
        </asp:Label>
    </ContentTemplate>
</asp:UpdatePanel>

UPDATE

I've also added a full explanation onto my blog: Friendly Error Messages with Microsoft Report Viewer


问:
How do I convert a nested array of Woocommerce products into a Javascript object?
I am trying to access the stock_quantity, ID and SKU for woocommerce products in a php array.

I need to get the SKU to compare it against a value in my JavaScript code so that I can display the stock_quantity for the selected product and update an add to cart link with the selected product ID.

I am getting the products by creating a query that returns any product with a SKU containing the $tag variable I am passing it like this:

```<code>// Get any products with SKU that includes tag
$query = new WC_Product_Query();
$query->set( 'sku', $tag );
$products = $query->get_products();
</code>```

Ideally I would like to convert this php array into a javacript array with all the nested arrays/objects in tact. This snippet will successfully log the array to the console and I can see that the array does in fact contain the products I need access to.

```<code>echo "<script>console.log(".json_encode(var_export($products, true)).");</script>";
</code>```

If its not possible to simply convert the array and all the nested content into a javscript array, Im wondering if perhaps there is a way to recursively loop through the php array and push the content to a javascript array.

Any help would be greatly appreciated! This is my first stack overflow post!

答:
Unfortunately no one was albe to provide a snippet but I was able to come up with a solution, so here it is:

```<code>// Get any products with SKU that includes tag
$query = new WC_Product_Query();
$query->set( 'sku', $tag );
$products = $query->get_products();
// Initialize an empty array
$products_arr = array();
// Loop through products
foreach($products as $product){
// Create an empty object for each product
        $prod = new stdClass();
// Set get product data and add to object
        $prod->stock_quantity = $product->get_stock_quantity();
        $prod->sku = $product->get_sku();
        $prod->id = $product->get_id();
        $prod->price = $product->get_price();
// Push product object with data to array
        array_push($products_arr, $prod);
}
// Create JS var and set it to the array of objects
echo  "<script>var ticketsBySku = ".json_encode($products_arr).";</script>";
</code>```

Now I have a js variable that I can access anywhere in my code that contains the content from my woocommerce products query (php array)

Hope that helps somebody!

Body:
I am trying to access the stock_quantity, ID and SKU for woocommerce products in a php array.

I need to get the SKU to compare it against a value in my JavaScript code so that I can display the stock_quantity for the selected product and update an add to cart link with the selected product ID.

I am getting the products by creating a query that returns any product with a SKU containing the $tag variable I am passing it like this:

// Get any products with SKU that includes tag
$query = new WC_Product_Query();
$query->set( 'sku', $tag );
$products = $query->get_products();

Ideally I would like to convert this php array into a javacript array with all the nested arrays/objects in tact. This snippet will successfully log the array to the console and I can see that the array does in fact contain the products I need access to.

echo "";

If its not possible to simply convert the array and all the nested content into a javscript array, Im wondering if perhaps there is a way to recursively loop through the php array and push the content to a javascript array.

Any help would be greatly appreciated! This is my first stack overflow post!

Body:
Unfortunately no one was albe to provide a snippet but I was able to come up with a solution, so here it is:

// Get any products with SKU that includes tag
$query = new WC_Product_Query();
$query->set( 'sku', $tag );
$products = $query->get_products();
// Initialize an empty array
$products_arr = array();
// Loop through products
foreach($products as $product){
// Create an empty object for each product
        $prod = new stdClass();
// Set get product data and add to object
        $prod->stock_quantity = $product->get_stock_quantity();
        $prod->sku = $product->get_sku();
        $prod->id = $product->get_id();
        $prod->price = $product->get_price();
// Push product object with data to array
        array_push($products_arr, $prod);
}
// Create JS var and set it to the array of objects
echo  "<script>var ticketsBySku = ".json_encode($products_arr).";</script>";

Now I have a js variable that I can access anywhere in my code that contains the content from my woocommerce products query (php array)

Hope that helps somebody!