问:
DRF nested serializers custom output
Couldn't find problem like this, so here is my problem:

models.py (simplified)

```<code>class Root(models.Model):
    name = models.CharField()

class TextFile(models.Model):
    root = models.ForeignKey(Root)
    name = models.CharField()

class ImageFile(models.Model):
    root = models.ForeignKey(Root)
    name = models.CharField()
</code>```

serializers.py

```<code>class TextFileSerializer(serializers.Modelserializer):
    class Meta:
        model = TextFile
        fields = '__all__'

class ImageFileSerializer(serializers.Modelserializer):
    class Meta:
        model = ImageFile
        fields = '__all__'

class FilesSerializer(serializers.Modelserializer):
    Texts = TextFileSerializer(source='textfile_set', many=True, read_only=True)
    Images = ImageFileSerializer(source='imagefile_set', many=True, read_only=True)
    class Meta:
        model = Root
        fields = '__all__'

class RootSerializer(serializers.Modelserializer):
    files = FilesSerializer(many=True, read_only=True)
    class Meta:
        model = Root
        fields = '__all__'
</code>```

I've got only root 'id' and 'name' in output but no 'files'.

I expect output like this:

```<code>{
    'id': 0,
    'name': 'Root instance 1',
    'files': {
        'Texts': [
            {'id': 0, 'name': 'Text1'},
            {'id': 1, 'name': 'Text2'},
             ...
        ],
        'Images': [
            {'id': 0, 'name': 'Image1'},
            {'id': 1, 'name': 'Image2'},
             ...
        ]
    }
}
</code>```

Can anyone help me with that?

答:
Your FilesSerializer field in RootSerializer is always returning None because Root have no property named 'files'. DRF serializer don't add None fields in the response by default. Your FileSerializer ask for a RootModel.

What you want is a way to retrieve files from your root model, so what you can do is using a SerializerMethodField, and in this method, fetch the data you need, and serializer them using your FileSerializer (but as a normal serializer).

Like so :

```<code>class TextFileSerializer(serializers.ModelSerializer):
class Meta:
    model = TextFile
    fields = '__all__'

 class ImageFileSerializer(serializers.ModelSerializer):
    class Meta:
        model = ImageFile
        fields = '__all__'

 class FilesSerializer(serializers.Serializer):
     Texts = TextFileSerializer(source='textfile_set', many=True)
     Images = ImageFileSerializer(source='imagefile_set', many=True)

     class Meta:
         fields = '__all__'

class RootSerializer(serializers.ModelSerializer):
    files = serializers.SerializerMethodField()
    class Meta:
        model = Root
        fields = '__all__'

    def get_files(self, instance):
        return FilesSerializer(instance).data
</code>```

It returns

```<code>[
    {
        "id": 1,
        "files": {
            "Texts": [],
            "Images": [
                {
                    "id": 1,
                    "name": "testimage",
                    "root": 1
                }
            ]
        },
        "name": ""
    }
]
</code>```

Title: DRF nested serializers custom output

Body:
Couldn't find problem like this, so here is my problem:

models.py (simplified)

class Root(models.Model):
    name = models.CharField()

class TextFile(models.Model):
    root = models.ForeignKey(Root)
    name = models.CharField()

class ImageFile(models.Model):
    root = models.ForeignKey(Root)
    name = models.CharField()

serializers.py

class TextFileSerializer(serializers.Modelserializer):
    class Meta:
        model = TextFile
        fields = '__all__'

class ImageFileSerializer(serializers.Modelserializer):
    class Meta:
        model = ImageFile
        fields = '__all__'

class FilesSerializer(serializers.Modelserializer):
    Texts = TextFileSerializer(source='textfile_set', many=True, read_only=True)
    Images = ImageFileSerializer(source='imagefile_set', many=True, read_only=True)
    class Meta:
        model = Root
        fields = '__all__'

class RootSerializer(serializers.Modelserializer):
    files = FilesSerializer(many=True, read_only=True)
    class Meta:
        model = Root
        fields = '__all__'

I've got only root 'id' and 'name' in output but no 'files'.

I expect output like this:

{
    'id': 0,
    'name': 'Root instance 1',
    'files': {
        'Texts': [
            {'id': 0, 'name': 'Text1'},
            {'id': 1, 'name': 'Text2'},
             ...
        ],
        'Images': [
            {'id': 0, 'name': 'Image1'},
            {'id': 1, 'name': 'Image2'},
             ...
        ]
    }
}

Can anyone help me with that?

Body:
Your FilesSerializer field in RootSerializer is always returning None because Root have no property named 'files'. DRF serializer don't add None fields in the response by default. Your FileSerializer ask for a RootModel.

What you want is a way to retrieve files from your root model, so what you can do is using a SerializerMethodField, and in this method, fetch the data you need, and serializer them using your FileSerializer (but as a normal serializer).

Like so :

class TextFileSerializer(serializers.ModelSerializer):
class Meta:
    model = TextFile
    fields = '__all__'

 class ImageFileSerializer(serializers.ModelSerializer):
    class Meta:
        model = ImageFile
        fields = '__all__'

 class FilesSerializer(serializers.Serializer):
     Texts = TextFileSerializer(source='textfile_set', many=True)
     Images = ImageFileSerializer(source='imagefile_set', many=True)

     class Meta:
         fields = '__all__'

class RootSerializer(serializers.ModelSerializer):
    files = serializers.SerializerMethodField()
    class Meta:
        model = Root
        fields = '__all__'

    def get_files(self, instance):
        return FilesSerializer(instance).data

It returns

[
    {
        "id": 1,
        "files": {
            "Texts": [],
            "Images": [
                {
                    "id": 1,
                    "name": "testimage",
                    "root": 1
                }
            ]
        },
        "name": ""
    }
]


来源: stackexchange

问:
Worker threads vs node cluster for server application with internal data exchange
I understand that questions like this can be a matter of opinion, which is why I tried to provide more details.

I'm developing a WebSocket server app with the following 'features':

2-3 connections can point to the same User

Users can occasionally interact with each other. Either in bursts or in continuous exchange of data

A portion of global data should be always synced between all users

A portion of global data should be lazily (on demand) synced between some users

2 possible structures come to mind:

Worker threads. Main thread handles all network IO, connection->User bundling and stores/interacts with global data. It also sends lots of postMessage-s to worker threads. Worker threads occasionally talk to each other when 2 players from different threads need to interact. Possible issues:

postMessage overhead (mostly from serialization from what I understand). Theoretically for most messages I could try to use SharedArrayBuffer. I don't think it could be optimized beyond that.

Main thread would handle both network IO and global data interactions. Maybe this could become a bottleneck?

Stateless NodeJS cluster that stores all data in Redis and also utilizes occasional locking. Issues/questions:

Would use more RAM

No matter how fast Redis is, communicating with it will most likely be slower than using postMessage-s.

Will multiple servers actually be benefitial? I heard that splitting the same type IO into multiple processes is a bad idea. Or at least is not as benefitial as using native Node asynchronous IO.

I don't think there is a way to bundle connections based on something like User id.

Getting and setting Redis data on request is fine. But how would one process know if some key was modified by another process?

答:
It sounds like you're perhaps in the design phase and don't yet have running code that you can measure.  If that's the case, do not assume you know where your bottlenecks are yet and spend time designing and implementing for a problem that has not yet been measured.  Performance bottlenecks are often not where you think they might be.  Spending lots of time implementing a more complex architecture to address where you think a bottleneck might be can very easily be a lot of wasted development time if you're wrong.

Instead, implement the simpler architecture or even prototype and test and measure at scale.  Find out where your real bottlenecks are.  Then, you will be sure your are focusing on the right problem and will have a test engine that you can measure when you implement an alternative to see how well you did.

If the main focus of your question is addressing the CPU intensive operations in your code, I would probably first explore using worker threads and a job queue.  Still have one main process that the webSockets connect to and where you keep all your state.

When a request comes in, create a job and put it in the job queue (the job queue can just be an array of job objects waiting to be processed).  If there's an idle thread, grab the oldest job from the job queue and send that thread the job to do.  It will crunch on it in whatever CPU intensive way it needs to.  When it finishes, it messages the result back to your main thread and your main thread sends it the next job and does whatever it needs to with the result.

You can have as many worker threads as you have CPU cores (more than that loses efficiency).

This architecture tries to localize the CPU intensive operations and farm them off to worker threads while keeping the rest of the architecture (your webSocket connections and state management) the same to keep things as simple as possible.

If large amounts of state needs to be accessed by the CPU-intensive operations, then probably you want to move the state to a database where multi-threaded access to the state can be managed by the database (that's one of the helpful things that a database does).  If the state is not persistent, the database could be Redis.  This is generally preferred over a synchronizing architecture because managing concurrency when updating the state and synchronizing in any general way is probably not something you want to implement yourself (it's a hard problem).

ContentLicense: CC BY-SA 4.0


问:
AWS CloudFront vs Global Accelerator for Dynamic contents
What is the difference between CloudFront and Global Accelerator when we want to serve dynamic contents?

https://aws.amazon.com/cloudfront/dynamic-content/

I expect that CloudFront is CDN, so it is used for static files such as images and videos. However, this webpage above says CloudFront can be used for dynamic contents too. Therefore, no cache will be used and every time CloudFront asks the origin server (e.g. ALB) for new contents. Obviously, clients access edge locations, so responses will be faster than accessing directly to
ALB.

https://aws.amazon.com/global-accelerator/

On the other hand, Global Accelerator is a service to let clients access edge locations and make response time shorter.

I don't really see the difference between these two in the context of dynamic contents. Could anyone explain this?

答: AWS Global Accelerator and Amazon CloudFront are separate services that use the AWS global network and its edge locations around the world. CloudFront improves performance for both cacheable content (such as images and videos) and dynamic content (such as API acceleration and dynamic site delivery). Global Accelerator improves performance for a wide range of applications over TCP or UDP by proxying packets at the edge to applications running in one or more AWS Regions. Global Accelerator is a good fit for non-HTTP use cases, such as gaming (UDP), IoT (MQTT), or Voice over IP, as well as for HTTP use cases that specifically require static IP addresses or deterministic, fast regional failover. Both services integrate with AWS Shield for DDoS protection.</p>


问:
FileProviderExtension won't be loaded in macOS 12.2
I am new to macOS development.

I am trying to develop macOS FileProvider extension, and everything was fine until I updated my macOS from 11 to 12.2.

After updating OS, FileProvider extension won't being loaded by NSFileProviderManager.add(domain) and its completion handler returns error - NSFileProviderDomain.Error.providerNotFound

```<code>@IBAction func tapAddDomainButton(_ sender: Any) {
NSFileProviderManager.add(domain) { error in
    print("Error: \(error)") // <- Error: Optional(Error Domain=NSFileProviderErrorDomain Code=-2001 "The application cannot be used right now." UserInfo={NSLocalizedDescription=The application cannot be used right now.})
}
</code>```

}

I've made a new boilerplate project with default macOS > App + 'File Provider Extension' in Xcode, and still got same error.
Same code works on macOS 11.6.1.

Weird thing is that apple sample code won't return error and still works in macOS 12.2.
I can't find any difference between my code and Apple Sample Code.

I uploaded my test project here.
Please help

Thanks in advance.

Additional info: My colleague tested in macOS 12.0.1/12.1 and my test project works fine.

答:
I managed to fix it by changing the app and extension group (com.apple.security.application-groups):

From $(APP_TEAM_ID).MyGroup

To group.MyGroup

Body:
I am new to macOS development.

I am trying to develop macOS FileProvider extension, and everything was fine until I updated my macOS from 11 to 12.2.

After updating OS, FileProvider extension won't being loaded by NSFileProviderManager.add(domain) and its completion handler returns error - NSFileProviderDomain.Error.providerNotFound

@IBAction func tapAddDomainButton(_ sender: Any) {
NSFileProviderManager.add(domain) { error in
    print("Error: \(error)") // <- Error: Optional(Error Domain=NSFileProviderErrorDomain Code=-2001 "The application cannot be used right now." UserInfo={NSLocalizedDescription=The application cannot be used right now.})
}

}

I've made a new boilerplate project with default macOS > App + 'File Provider Extension' in Xcode, and still got same error.
Same code works on macOS 11.6.1.

Weird thing is that apple sample code won't return error and still works in macOS 12.2.
I can't find any difference between my code and Apple Sample Code.

I uploaded my test project here.
Please help

Thanks in advance.

Additional info: My colleague tested in macOS 12.0.1/12.1 and my test project works fine.


问:
Using Android Management API without google account
I am developing an application in the "fully managed device" mode. Now implemented "Dedicated devices". The installation of the application is carried out via a QR code immediately in the "Device owner" mode.

```<code>{
  "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME": "your_name",
  "android.app.extra.PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM": "your_checksum",
  "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION": "your_location",
  "android.app.extra.PROVISIONING_USE_MOBILE_DATA":true
}
</code>```

The problem is that after installing the application, there is a need to give permissions and configure some areas of the smartphone (such as disabling auto-update software, installing from unknown sources) in order to work correctly in a fully managed mode. As I understand it, using the Android Management API, you can set up a policy to immediately grant part of the permissions. But all the examples that describe the Android Management API mention working through a google account and google play market for enterprice solutions.

Is it possible to do without a google account? I understand that all examples are tied to EMM from google, and if I don't want to be tied to google, I either need to use a third-party EMM API or implement my own, am I right?

答: It is possible to use Android Management API without an EMM, you need to create a Service Account and create a new Enterprise with a  gmail account,You will be able to provision device to the Enterprise and  set up policies for those devices.This notebook will show you how to get started https://colab.sandbox.google.com/github/google/android-management-api-samples/blob/master/notebooks/quickstart.ipynb</p>

Body:
I am developing an application in the "fully managed device" mode. Now implemented "Dedicated devices". The installation of the application is carried out via a QR code immediately in the "Device owner" mode.

{
  "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME": "your_name",
  "android.app.extra.PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM": "your_checksum",
  "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION": "your_location",
  "android.app.extra.PROVISIONING_USE_MOBILE_DATA":true
}

The problem is that after installing the application, there is a need to give permissions and configure some areas of the smartphone (such as disabling auto-update software, installing from unknown sources) in order to work correctly in a fully managed mode. As I understand it, using the Android Management API, you can set up a policy to immediately grant part of the permissions. But all the examples that describe the Android Management API mention working through a google account and google play market for enterprice solutions.

Is it possible to do without a google account? I understand that all examples are tied to EMM from google, and if I don't want to be tied to google, I either need to use a third-party EMM API or implement my own, am I right?


问:
c++17 filesystem::remove_all with wildcard path
I want to delete all files, folders and subfolders but not the parent folder.

So I tried to use filesystem::remove_all with a wildcard, but this doesn't seems to work.

```<code>filesystem::removeall("pathtofolder/*");
</code>```

There is no exception, but it doesn't delete anything.

Are wildcards are not allowed?

Do I really need  to call for each file and folder inside of pathtofolder the removeall method?

答:
Example:

std::wregex regExpName { LR"(^.*\.tmp$)" };
const auto tmpPath { std::filesystem::temp_directory_path() };
for (const auto& element : std::filesystem::directory_iterator(tmpPath))
    if (not element.is_directory() and std::regex_match(element.path().filename().wstring(), regExpName))
        std::filesystem::remove(element.path());
```

Body:
I want to delete all files, folders and subfolders but not the parent folder.

So I tried to use filesystem::remove_all with a wildcard, but this doesn't seems to work.

filesystem::removeall("pathtofolder/*");

There is no exception, but it doesn't delete anything.

Are wildcards are not allowed?

Do I really need  to call for each file and folder inside of pathtofolder the removeall method?


问:
Show more rows across two HTML tables on click with jQuery
I am trying to display some historical data in 2 different tables (at one point in the history the data is slightly different). The older table only has 4 columns and the newer table has 6 columns. I'm trying to add a show more.. button to display more rows and its working fine, the problem is the button ceases to work after getting part of the way into the second table.

This code shows the headers and the first 10 rows of the table, then clicking the show more button displays the next 12 rows. This all works great until the 2nd table starts to show. Once it displays the first x number of rows in the 2nd table the button no longer does anything.

What am I missing?

jQuery(function($) {
  $('table tr:lt(11)').addClass('active');

  $('a.load_more').on('click', function(e) {
    e.preventDefault();
    var $rows = $('table tr');
    var lastActiveIndex = $rows.filter('.active:last').index();
    $rows.filter(':lt(' + (lastActiveIndex + 13) + ')').addClass('active');

    // hide the button when all elements visible
    $(this).toggle($rows.filter(':hidden').length !== 0);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<table>
  <thead>
    <tr>
      <th>A</th>
      <th>B</th>
      <th>C</th>
      <th>D</th>
      <th>E</th>
      <th>F</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
  </tbody>
</table>
<table>
  <thead>
    <tr>
      <th>A</th>
      <th>B</th>
      <th>C</th>
      <th>D</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
  </tbody>
</table>

Load more</code>```

答:
It's hard to say how your script is supposed to work given I don't have the data. However, var $rows = $('table tr'); works with both tables together so in the next row, you're asking for last index of all rows together. Could this be the problem?

Have you tried debugging it in browser with DevTools, iterating over the rows of your code to see what's in lastActiveIndex, what $rows.filter() returns etc.?

Body:
I am trying to display some historical data in 2 different tables (at one point in the history the data is slightly different). The older table only has 4 columns and the newer table has 6 columns. I'm trying to add a show more.. button to display more rows and its working fine, the problem is the button ceases to work after getting part of the way into the second table.

This code shows the headers and the first 10 rows of the table, then clicking the show more button displays the next 12 rows. This all works great until the 2nd table starts to show. Once it displays the first x number of rows in the 2nd table the button no longer does anything.

What am I missing?

jQuery(function($) {
  $('table tr:lt(11)').addClass('active');

  $('a.load_more').on('click', function(e) {
    e.preventDefault();
    var $rows = $('table tr');
    var lastActiveIndex = $rows.filter('.active:last').index();
    $rows.filter(':lt(' + (lastActiveIndex + 13) + ')').addClass('active');

    // hide the button when all elements visible
    $(this).toggle($rows.filter(':hidden').length !== 0);
  });
});

      A
      B
      C
      D
      E
      F

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      A
      B
      C
      D

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

Load more


问:
Selecting a count into a variable in oracle
Hi I have been trying this today and haven't had any luck. this stored procedure does not work :(</p>

```<code>CREATE OR REPLACE PROCEDURE LEAD_PURGE(closed IN DATE,
oprtr IN INTEGER,
leadscount OUT INTEGER)

is
BEGIN

SELECT COUNT(*) FROM LEADS_DELETED INTO leadscount;

COMMIT;
END LEAD_PURGE;
</code>```

答:
you have the into at the wrong place.

Try something like this instead and proceed from there:

```<code>declare
  cnt number;
begin
  select count(*)
  into cnt
  from leads_delete;
end;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hi I have been trying this today and haven't had any luck. this stored procedure does not work :(

CREATE OR REPLACE PROCEDURE LEAD_PURGE(closed IN DATE,
oprtr IN INTEGER,
leadscount OUT INTEGER)

is
BEGIN

SELECT COUNT(*) FROM LEADS_DELETED INTO leadscount;

COMMIT;
END LEAD_PURGE;

Body:
you have the into at the wrong place.

Try something like this instead and proceed from there:

declare
  cnt number;
begin
  select count(*)
  into cnt
  from leads_delete;
end;


问:
Hosting 2 blazor server apps(mainsite and admin app) and asp net core web api in same windows hosting package
I have hosted two blazor server apps and .net core web api in windows package by deploying the main site app in the httpdocs directory which and the other apps in subfolders of the http docs but only the main site app works the rest apps dont work at all. I need to deploy all three apps on same windows hosting package so that I can also share the same domain?</p>

答:
The best way to answer this question is to demostrate how to do it with the out-of-the-box Blazor templates.

There are some issues around routing and page reloading you will need to solve once you get the basics working.

Create a Blazor Solution with the Blazor Server template.  Call the solution Blazor.Medusa and the project Blazor.Medusa.Web.

Add two more Blazor Server projects Blazor.Medusa.Red and Blazor.Medusa.Blue.

Add Dependencies on Web to Red and Blue.

Change the Sidebar colors on Red and Blue projects so you can see where you are!

MainLayout.razor.css

.sidebar {
    background-color: rgb(0, 0, 64);
}
```
<p>And</p>
<pre class="lang-css prettyprint-override"><code>.sidebar {
    background-color: rgb(128, 0, 0);
}
</code>```

Update the Index components in each so they have their "colour" routes.

@page "/"
@page "/Red"

<PageTitle>Index</PageTitle>
```
<pre class="lang-html prettyprint-override"><code>@page "/"
@page "/Blue"

<PageTitle>Index</PageTitle>
</code>```

In Web add the launch pages for each application.  Add Red.cshtml razor page to Pages.  Note we're just specifying a different root component for the application.

```<code>@page "/Red"
@namespace Blazor.Medusa.Web.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
    Layout = "_Layout";
}

<component type="typeof(Blazor.Medusa.Red.App)" render-mode="ServerPrerendered" />
</code>```

And Blue.cshtml

```<code>@page "/Blue"
@namespace Blazor.Medusa.Web.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
    Layout = "_Layout";
}

<component type="typeof(Blazor.Medusa.Blue.App)" render-mode="ServerPrerendered" />
</code>```

Update _Host.cshtml

```<code>@page "/"
@namespace Blazor.Medusa.Web.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
    Layout = "_Layout";
}

<component type="typeof(Blazor.Medusa.Web.App)" render-mode="ServerPrerendered" />
</code>```

Add the additional services to Web Services.

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton<Blazor.Medusa.Red.Data.WeatherForecastService>();
builder.Services.AddSingleton<Blazor.Medusa.Web.Data.WeatherForecastService>();
builder.Services.AddSingleton<Blazor.Medusa.Blue.Data.WeatherForecastService>();
```
<p>Note I've used the full namespaced class names to ensure clarity.</p>
<p>Update <em>Web</em> <code>Index.razor</code>.  It's the home page: we need links to Red and Blue.</p>
```@page "/"

<PageTitle>Index</PageTitle>

Hello, world!

Welcome to your new app.

    <button class="btn btn-primary me-1" @onclick="GoBlue">Go Blue</button>
    <button class="btn btn-danger me-1" @onclick="GoRed">Go Red</button>

<SurveyPrompt Title="How is Blazor working for you?" />

@code {

    [Inject] private NavigationManager? NavManager { get; set; }

    private void GoRed()
        => this.NavManager?.NavigateTo("/Red", true);

    private void GoBlue()
        => this.NavManager?.NavigateTo("/Blue", true);
}
```

Hopefully I've covered all the steps and this will now run as I expect.  Add a comment if you're having problems.

Here's some screenshots so you can see what I've got in each project (I've cleared the redundant web stuff out or Red and Blue):

Body:
The best way to answer this question is to demostrate how to do it with the out-of-the-box Blazor templates.

There are some issues around routing and page reloading you will need to solve once you get the basics working.

Create a Blazor Solution with the Blazor Server template.  Call the solution Blazor.Medusa and the project Blazor.Medusa.Web.

Add two more Blazor Server projects Blazor.Medusa.Red and Blazor.Medusa.Blue.

Add Dependencies on Web to Red and Blue.

Change the Sidebar colors on Red and Blue projects so you can see where you are!

MainLayout.razor.css

.sidebar {
    background-color: rgb(0, 0, 64);
}

And

.sidebar {
    background-color: rgb(128, 0, 0);
}

Update the Index components in each so they have their "colour" routes.

@page "/"
@page "/Red"

<PageTitle>Index</PageTitle>

@page "/"
@page "/Blue"

<PageTitle>Index</PageTitle>

In Web add the launch pages for each application.  Add Red.cshtml razor page to Pages.  Note we're just specifying a different root component for the application.

@page "/Red"
@namespace Blazor.Medusa.Web.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
    Layout = "_Layout";
}

<component type="typeof(Blazor.Medusa.Red.App)" render-mode="ServerPrerendered" />

And Blue.cshtml

@page "/Blue"
@namespace Blazor.Medusa.Web.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
    Layout = "_Layout";
}

<component type="typeof(Blazor.Medusa.Blue.App)" render-mode="ServerPrerendered" />

Update _Host.cshtml

@page "/"
@namespace Blazor.Medusa.Web.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
    Layout = "_Layout";
}

<component type="typeof(Blazor.Medusa.Web.App)" render-mode="ServerPrerendered" />

Add the additional services to Web Services.

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton<Blazor.Medusa.Red.Data.WeatherForecastService>();
builder.Services.AddSingleton<Blazor.Medusa.Web.Data.WeatherForecastService>();
builder.Services.AddSingleton<Blazor.Medusa.Blue.Data.WeatherForecastService>();

Note I've used the full namespaced class names to ensure clarity.

Update Web Index.razor.  It's the home page: we need links to Red and Blue.

@page "/"

<PageTitle>Index</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

<div class="p-2 m-2 text-end">
    <button class="btn btn-primary me-1" @onclick="GoBlue">Go Blue</button>
    <button class="btn btn-danger me-1" @onclick="GoRed">Go Red</button>
</div>

<SurveyPrompt Title="How is Blazor working for you?" />

@code {

    [Inject] private NavigationManager? NavManager { get; set; }

    private void GoRed()
        => this.NavManager?.NavigateTo("/Red", true);

    private void GoBlue()
        => this.NavManager?.NavigateTo("/Blue", true);
}

Hopefully I've covered all the steps and this will now run as I expect.  Add a comment if you're having problems.

Here's some screenshots so you can see what I've got in each project (I've cleared the redundant web stuff out or Red and Blue):


问:
Sum of the values in nested dicts excluding some based on other key in MongoDB database
I have a MongoDB database with the following format:

```<code>    {
    "_id": xxx,
    "timestamp": "1643649900000",
    "scores":
        [{
        "name": "APPL",
        "price": 80
        },
        {
        "name": "GOOGL",
        "price": 83,
        },
        {
        "name": "COMPI",
        "price": 76,
        },
        {
        "name": "and more names which also can change in the following documents",
        "price": 76,
        }]
    },
    {
    "_id": yyy,
    "time": "1644350400000",
    "scores":
        [{
        "name": "STCMP",
        "price": 33
        },
        {
        "name": "APPL",
        "price": 95,
        },
        {
        "name": "GOOGL",
        "price": 83,
        },
        {
        "name": "MINN",
        "price": 76,
        }]
    },
</code>```

I need to sum all prices per time but excluding (or subtract from the sum) some.

My scores list has around 200 dicts and I want to exclude around 5 of them.
I only managed to do the summing part, but after two days of search still can't manage to exclude with my limited knowledge.

```<code>toBeExcluded = ["APPL", "GOOGL"]
</code>```
```<code>sums.aggregate([
            {
                "$unwind" : "$scores"
            },
            {
                "$group": {
                    "_id": "$time",
                    "total": {
                        "$sum": "$scores.price"
                    }
                }
            },
            {
                "$addFields":{
                    "timeAdj": {"$toInt": [{"$subtract":[{"$divide": ["$_id", 1000]}, 300]}]}
                }
            },
            {
                "$sort": {"timeAdj":1}
            }
            ]))
</code>```

答:
use $cond and check names to be excluded using $in, in your $sum:

mongo playground

```<code>db.collection.aggregate([
  {
    "$unwind": "$scores"
  },
  {
    "$group": {
      "_id": "$time",
      "total": {
        "$sum": {
          "$cond": [
            {
              "$in": [
                "$scores.name",
                [
                  "APPL",
                  "GOOGL"
                ]
              ]
            },
            0,
            "$scores.price"
          ],

        }
      }
    }
  },

])
</code>```

Body:
I have a MongoDB database with the following format:

    {
    "_id": xxx,
    "timestamp": "1643649900000",
    "scores":
        [{
        "name": "APPL",
        "price": 80
        },
        {
        "name": "GOOGL",
        "price": 83,
        },
        {
        "name": "COMPI",
        "price": 76,
        },
        {
        "name": "and more names which also can change in the following documents",
        "price": 76,
        }]
    },
    {
    "_id": yyy,
    "time": "1644350400000",
    "scores":
        [{
        "name": "STCMP",
        "price": 33
        },
        {
        "name": "APPL",
        "price": 95,
        },
        {
        "name": "GOOGL",
        "price": 83,
        },
        {
        "name": "MINN",
        "price": 76,
        }]
    },

I need to sum all prices per time but excluding (or subtract from the sum) some.

My scores list has around 200 dicts and I want to exclude around 5 of them.
I only managed to do the summing part, but after two days of search still can't manage to exclude with my limited knowledge.

toBeExcluded = ["APPL", "GOOGL"]

sums.aggregate([
            {
                "$unwind" : "$scores"
            },
            {
                "$group": {
                    "_id": "$time",
                    "total": {
                        "$sum": "$scores.price"
                    }
                }
            },
            {
                "$addFields":{
                    "timeAdj": {"$toInt": [{"$subtract":[{"$divide": ["$_id", 1000]}, 300]}]}
                }
            },
            {
                "$sort": {"timeAdj":1}
            }
            ]))

Body:
use $cond and check names to be excluded using $in, in your $sum:

mongo playground

db.collection.aggregate([
  {
    "$unwind": "$scores"
  },
  {
    "$group": {
      "_id": "$time",
      "total": {
        "$sum": {
          "$cond": [
            {
              "$in": [
                "$scores.name",
                [
                  "APPL",
                  "GOOGL"
                ]
              ]
            },
            0,
            "$scores.price"
          ],

        }
      }
    }
  },

])


问:
Trim string in JavaScript
How do I remove all whitespace from the start and end of the string?</p>

答:
If you are using jQuery, use the jQuery.trim() function. For example:

```<code>if( jQuery.trim(StringVariable) == '')
</code>```

Title: Trim string in JavaScript

LastEditorDisplayName: Paul Tomblin

Body:
If you are using jQuery, use the jQuery.trim() function. For example:

if( jQuery.trim(StringVariable) == '')


问:
Docker bind user file ownership
It was provided to me an image that run a service with the root user.

I have the need to bind mount a directory where the service running in the container must create files that will be used as input files of another non-containerized service.

The problem is well know: the generated files keep UID and GID from the in-container user.

So, I tried with this config:

```<code>  myservice:
    image: "someonewho/liketorunwithroot: latest"
    user: "${UID}:${GID}"
    volumes:
       - type: bind
         source: /home/user/output
         target: /service/path/outputdir
       - type: bind
         source: /etc/passwd
         target: /etc/passwd
       - type: bind
         source: /etc/group
         target: /etc/group
    ports:
      - "80:80"
</code>```

doing like this, I can force the in-container user to use uid and gid that are the same of the user on the docker host, so I have no problem at all with the files generated under /service/path/outputdir.

But in this way the service is not working anymore, because the user with those ID can't read and write in other folders.

So I tried with the user namespace, forcing the range of subuid to one specif id (the same of the docker host user)

In this case I get this error:

docker: failed to register layer: Error processing tar file (exit status 1): Container ID 100 cannot be mapped to a host ID.

I can't manipulate the Dockerfile, nor the container, because it must be "portable".

Is there a solution?

答:
The best I can come up with is running this on the host

```<code>mkdir container-files
chmod g+s container-files
docker run --rm -v $(pwd)/container-files:/output ubuntu bash -c "echo test > /output/test.txt"
</code>```

Now there's a file in the container-files directory that was created by a container running as root:root. But on the host, the file is owned by root:your group. And since you're in your group, you can read the file. Unfortunately, you can't do much else with it.

It uses the SGID bit on the container-files directory, so files created in the directory will have the same group ownership as the container-files directory.
On my Linux machine, the s-bit is set by default when the directory is created, so you might not need to run chmod.

The best solution, though, is to change the container so it doesn't need to run as root. I don't see how running as root is more portable. In fact, there are container environments that don't allow containers to run as root due to the security risks it poses (OpenShift).

Title: Docker bind user file ownership

Body:
It was provided to me an image that run a service with the root user.

I have the need to bind mount a directory where the service running in the container must create files that will be used as input files of another non-containerized service.

The problem is well know: the generated files keep UID and GID from the in-container user.

So, I tried with this config:

  myservice:
    image: "someonewho/liketorunwithroot: latest"
    user: "${UID}:${GID}"
    volumes:
       - type: bind
         source: /home/user/output
         target: /service/path/outputdir
       - type: bind
         source: /etc/passwd
         target: /etc/passwd
       - type: bind
         source: /etc/group
         target: /etc/group
    ports:
      - "80:80"

doing like this, I can force the in-container user to use uid and gid that are the same of the user on the docker host, so I have no problem at all with the files generated under /service/path/outputdir.

But in this way the service is not working anymore, because the user with those ID can't read and write in other folders.

So I tried with the user namespace, forcing the range of subuid to one specif id (the same of the docker host user)

In this case I get this error:

docker: failed to register layer: Error processing tar file (exit status 1): Container ID 100 cannot be mapped to a host ID.

I can't manipulate the Dockerfile, nor the container, because it must be "portable".

Is there a solution?

Body:
The best I can come up with is running this on the host

mkdir container-files
chmod g+s container-files
docker run --rm -v $(pwd)/container-files:/output ubuntu bash -c "echo test > /output/test.txt"

Now there's a file in the container-files directory that was created by a container running as root:root. But on the host, the file is owned by root:your group. And since you're in your group, you can read the file. Unfortunately, you can't do much else with it.

It uses the SGID bit on the container-files directory, so files created in the directory will have the same group ownership as the container-files directory.
On my Linux machine, the s-bit is set by default when the directory is created, so you might not need to run chmod.

The best solution, though, is to change the container so it doesn't need to run as root. I don't see how running as root is more portable. In fact, there are container environments that don't allow containers to run as root due to the security risks it poses (OpenShift).


问:
configuring image filepaths correctly in mkdocs
I have an issue with MkDocs not being able to find my images.  The images are in a subfolder, called microsatsFigures, in my docs folder.  So my /docs folder contains index.md, traces.md and the folder microsatsFigures which has the images.  In my Markdown file traces.md I am using html syntax for the images so the path to the image is:

```<code><img src="microsatsFigures/Figure_setLoci.png"/>
</code>```

This works perfectly in markdown editors that I am using (Typora and Macdown), and the image is displayed no problem.  However mkdocs can't find the image - I get

WARNING  -  [15:02:53] "GET /traces/microsatsFigures/Figure_setLoci.png HTTP/1.1" code 404

There is no "traces" folder, so its not surprising it cannot find the image.

If I change the image path to  , it works in Mkdocs but not in the markdown editor.

I don't understand why mkdocs can't use the relative path microsatsFigures/Figure_setLoci.png, and why it requires a / in front.  And why does it look for the image in a /traces folder that does not exist if I don't use the /?

I'm using html because I need additional formatting on the images, but the same issue occurs with standard markdown image syntax.

Is there something I need to configure in MkDocs to get it to recognise the path in the same way that the markdown editors do? I'd really like to be able to preview my images in the markdown editing tools I'm using but at the moment I can either get it to work in MkDocs or the editor, but not both.

答:
I suspect this will work as expected if you use Markdown instead of HTML:

```<code>![Alt Text](microsatsFigures/Figure_setLoci.png)
</code>```

Here is what the documentation says about linking to images from :

Markdown allows document authors to fall back to raw HTML when the Markdown syntax does not meets the author's needs. MkDocs does not limit Markdown in this regard. However, as all raw HTML is ignored by the Markdown parser, MkDocs is not able to validate or convert links contained in raw HTML. When including internal links within raw HTML, you will need to manually format the link appropriately for the rendered document.

Why doesn't it work with raw HTML?

Assuming MkDocs generates URLs like https://your-site.tld/traces/, your browser sees that as a directory. A link to some-image.png will be interpreted as https://your-site.tld/traces/some-image.png.

Body:
I have an issue with MkDocs not being able to find my images.  The images are in a subfolder, called microsatsFigures, in my docs folder.  So my /docs folder contains index.md, traces.md and the folder microsatsFigures which has the images.  In my Markdown file traces.md I am using html syntax for the images so the path to the image is:

This works perfectly in markdown editors that I am using (Typora and Macdown), and the image is displayed no problem.  However mkdocs can't find the image - I get

WARNING  -  [15:02:53] "GET /traces/microsatsFigures/Figure_setLoci.png HTTP/1.1" code 404

There is no "traces" folder, so its not surprising it cannot find the image.

If I change the image path to  , it works in Mkdocs but not in the markdown editor.

I don't understand why mkdocs can't use the relative path microsatsFigures/Figure_setLoci.png, and why it requires a / in front.  And why does it look for the image in a /traces folder that does not exist if I don't use the /?

I'm using html because I need additional formatting on the images, but the same issue occurs with standard markdown image syntax.

Is there something I need to configure in MkDocs to get it to recognise the path in the same way that the markdown editors do? I'd really like to be able to preview my images in the markdown editing tools I'm using but at the moment I can either get it to work in MkDocs or the editor, but not both.

Body:
I suspect this will work as expected if you use Markdown instead of HTML:

![Alt Text](microsatsFigures/Figure_setLoci.png)

Here is what the documentation says about linking to images from :

Markdown allows document authors to fall back to raw HTML when the Markdown syntax does not meets the author's needs. MkDocs does not limit Markdown in this regard. However, as all raw HTML is ignored by the Markdown parser, MkDocs is not able to validate or convert links contained in raw HTML. When including internal links within raw HTML, you will need to manually format the link appropriately for the rendered document.

Why doesn't it work with raw HTML?

Assuming MkDocs generates URLs like https://your-site.tld/traces/, your browser sees that as a directory. A link to some-image.png will be interpreted as https://your-site.tld/traces/some-image.png.


问:
How do I dynamically add CSS classes to HTML elements if value is less or greater than 0?
How can I dynamically add css classes to the
 elements based on whether or not the value of the element is greater than 0?

HTML:

```<code><template>
    <div class="coin-block-wrapper">
        <div class="coin__wrapper">
            <div v-for="(value, key) in coins" :key="value" class="coin__row">
                <div class="coin__row-div">
                    <img src="{{ }}" class="coin__row-logo">
                    <div class="coin-name">{{key}}</div>
                    <div class="coin-name">USDT</div>
                </div>
                <div class="coin__row-div-large">
                    <div id="coin__row-small-div">
                        <div class="coin__row-text">{{value.USD.PRICE}}</div>
                        <div class="coin__row-text">{{value.BTC.PRICE}}</div>
                    </div>
                    <div id="coin__row-small-div">
                        <div class="coin__row-text">{{value.USD.CHANGEPCTHOUR}}%</div>
                        <div class="coin__row-text">{{value.BTC.CHANGEPCTHOUR}}%</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
</code>```

Styles:

```<code><style scoped>
    .positive {
        color: green;
    }

    .negative {
        color: red;
    }
</style>
</code>```

答:
You should try binding class.
Something like that:

```<code><div :class="getDivClasses(value.USD.PRICE)">
</code>```

and inside methods:

```<code>getDivClasses(value) {
  return value > 0 ? "positive" : "negative";
},
</code>```

Body:
How can I dynamically add css classes to the
 elements based on whether or not the value of the element is greater than 0?

HTML:

<template>

{{key}}

USDT

{{value.USD.PRICE}}

{{value.BTC.PRICE}}

{{value.USD.CHANGEPCTHOUR}}%

{{value.BTC.CHANGEPCTHOUR}}%

</template>

Styles:

Body:
You should try binding class.
Something like that:

<div :class="getDivClasses(value.USD.PRICE)">

and inside methods:

getDivClasses(value) {
  return value > 0 ? "positive" : "negative";
},


问:
What are the minimal access rights for the upstream user when using RabbitMQ Exchange Federation
I want to ensure that all users on my RabbitMQ clusters only have the rights they need for their intended purpose.

I'm using Exchange Federation between 2 RabbitMQ clusters and I want to restrict the rights of the user on the upstream cluster so that it can only federate messages from one Exchange. This is to ensure that the user used by the downstream cluster is not able to publish/subscribe/configure anything beyond it's intended purpose (or at least as much as is possible).

I understand that the permissions may be complex, as a worker queue and bindings must be dynamically created on the upstream cluster so this may not be straightforward.

All examples I've found specify to set the user's permissions as:

Configure regexp
Write regexp
Read regexp

.*
.*
.*

The federation works fine when the user has these settings but this is an all powerful user and I'm not comfortable with this. If I try to reconfigure it to anything more specific then I end up an error like the below:

```<code>{server_initiated_close,403,
<<"ACCESS_REFUSED - access to exchange 'exchange-a' in vhost 'vhost-a' refused for user 'user-a'">>}
</code>```

How can I restrict these permissions to prevent the federation user having more access than it needs?

答:
I've not found an answer to this question in any of my books or online resources so this answer is based on observation and trial and error....

Solution

Exchange federation seems to require an upstream user which has permissions to read from the target upstream exchange and also to configure, read and write to an upstream federation exchange and queue which are dynamically created.

The names of the dynamically created exchange and queue use the original exchange name and are both prefixed with federation:  and suffixed with -> and the downstream cluster name. The dynamically created exchange is also suffixed by an additional letter of the alphabet.

Based on this I have found that these minimal access rights work very nicely (with the exchange and downstream cluster names corrected):

Configure regexp
Write regexp
Read regexp

^federation: exc\.name -> dwn_cluster_name
^federation: exc\.name -> dwn_cluster_name
^exc\.name$|^federation: exc\.name -> dwn_cluster_name

Example

Let's say I have an exchange called my.exchange. The minimal access rights to read from this exchange alone would be ^my\.exchange$.

When a federation policy is setup on the downstream a new exchange and queue are created on the upstream cluster. These have names as shown below:

Exchange name: federation: my.exchange -> MY_DOWNSTREAM_CLUSTER A (final character can vary)

Queue name: federation: my.exchange -> MY_DOWNSTREAM_CLUSTER

Permissions can therefore be setup as:

Configure regexp
Write regexp
Read regexp

^federation: my\.exchange -> MY_DOWNSTREAM_CLUSTER
^federation: my\.exchange -> MY_DOWNSTREAM_CLUSTER
^my\.exchange$|^federation: my\.exchange -> MY_DOWNSTREAM_CLUSTER

What about federated queues?

Obviously off topic but worth answering here anyway as relatively simple by comparison.

This is simply a case of needing both configure and read permissions for the queue itself. Therefore a very explicit pattern for a full line match can be used for these e.g. ^my\.queue$.

Configure regexp
Write regexp
Read regexp

^my\.queue$
^$
^my\.queue$

Body:
I want to ensure that all users on my RabbitMQ clusters only have the rights they need for their intended purpose.

I'm using Exchange Federation between 2 RabbitMQ clusters and I want to restrict the rights of the user on the upstream cluster so that it can only federate messages from one Exchange. This is to ensure that the user used by the downstream cluster is not able to publish/subscribe/configure anything beyond it's intended purpose (or at least as much as is possible).

I understand that the permissions may be complex, as a worker queue and bindings must be dynamically created on the upstream cluster so this may not be straightforward.

All examples I've found specify to set the user's permissions as:

Configure regexp
Write regexp
Read regexp

.*
.*
.*

The federation works fine when the user has these settings but this is an all powerful user and I'm not comfortable with this. If I try to reconfigure it to anything more specific then I end up an error like the below:

{server_initiated_close,403,
<<"ACCESS_REFUSED - access to exchange 'exchange-a' in vhost 'vhost-a' refused for user 'user-a'">>}

How can I restrict these permissions to prevent the federation user having more access than it needs?


问:
create a function using data masking in R
inorder to do a paired analysis i need to write a function that sums integer counts. The total number required to be summed is specified in the corresponding "Yrs_Before" and "Yrs_After" columns in "df".  Is there a way i can avoid writing "fm_after" with just one function? Is this a variable masking for "Yrs_Before", "Yrs_After","Before.Yr_1...n+1" and "After.Yr_1...n+1" columns?

data frame

```<code>set.seed(123)
(df=data.frame(
  Yrs_Before=sample(1:8, 3),
  Yrs_After=sample(1:8, 3),
  Before.Yr_1=sample(1:8, 3),
  Before.Yr_2=sample(1:8, 3),
  Before.Yr_3=sample(1:8, 3),
  Before.Yr_4=sample(1:8, 3),
  Before.Yr_5=sample(1:8, 3),
  Before.Yr_6=sample(1:8, 3),
  Before.Yr_7=sample(1:8, 3),
  Before.Yr_8=sample(1:8, 3),
  After.Yr_1=sample(1:8, 3),
  After.Yr_2=sample(1:8, 3),
  After.Yr_3=sample(1:8, 3),
  After.Yr_4=sample(1:8, 3),
  After.Yr_5=sample(1:8, 3),
  After.Yr_6=sample(1:8, 3),
  After.Yr_7=sample(1:8, 3),
  After.Yr_8=sample(1:8, 3)

))
</code>```

function sums the corresponding rows based on the number of years in the before period.

```<code>fm=function(data,Yrs_Before){
  data |> dplyr::mutate(sums=
  ifelse(
  Yrs_Before == 1, rowSums(across(Before.Yr_1)),
  ifelse(
    Yrs_Before == 2, rowSums(across(Before.Yr_1:Before.Yr_2)),
    ifelse(
      Yrs_Before == 3, rowSums(across(Before.Yr_1:Before.Yr_3)),
      ifelse(
        Yrs_Before == 4, rowSums(across(Before.Yr_1:Before.Yr_4)),
        ifelse(
          Yrs_Before == 5, rowSums(across(Before.Yr_1:Before.Yr_5)),
          ifelse(
            Yrs_Before == 6, rowSums(across(Before.Yr_1:Before.Yr_6)),
            ifelse(
              Yrs_Before == 7, rowSums(across(Before.Yr_1:Before.Yr_7)),
              ifelse(
                Yrs_Before == 8, rowSums(across(Before.Yr_1:Before.Yr_8)),"")))))))))
}

</code>```

output

```<code>
fm(df,Yrs_Before)
Yrs_Before Yrs_After Before.Yr_1 Before.Yr_2 Before.Yr_3 Before.Yr_4 Before.Yr_5 Before.Yr_6 Before.Yr_7 Before.Yr_8 After.Yr_1 After.Yr_2 After.Yr_3 After.Yr_4 After.Yr_5 After.Yr_6 After.Yr_7 After.Yr_8 sums
1          7         6           2           5           6           3           3           1           3           1          4          3          4          5          1          4          3          2   23
2          8         3           6           4           1           5           1           8           2           6          6          7          7          7          2          5          6          5   33
3          3         2           3           6           2           8           4           5           7           3          1          5          2          1          3          7          1          7   11

</code>```

duplicated function with variable name changed to "After"

```<code>
fm_after=function(data,Yrs_After){
  data |> dplyr::mutate(sums=
                   ifelse(
                     Yrs_After == 1, rowSums(across(After.Yr_1)),
                     ifelse(
                       Yrs_After == 2, rowSums(across(After.Yr_1:After.Yr_2)),
                       ifelse(
                         Yrs_After == 3, rowSums(across(After.Yr_1:After.Yr_3)),
                         ifelse(
                           Yrs_After == 4, rowSums(across(After.Yr_1:After.Yr_4)),
                           ifelse(
                             Yrs_After == 5, rowSums(across(After.Yr_1:After.Yr_5)),
                             ifelse(
                               Yrs_After == 6, rowSums(across(After.Yr_1:After.Yr_6)),
                               ifelse(
                                 Yrs_After == 7, rowSums(across(After.Yr_1:After.Yr_7)),
                                 ifelse(
                                   Yrs_After == 8, rowSums(across(After.Yr_1:After.Yr_8)),"")))))))))
}

</code>```

output

```<code>fm_after(df,Yrs_After)
Yrs_Before Yrs_After Before.Yr_1 Before.Yr_2 Before.Yr_3 Before.Yr_4 Before.Yr_5 Before.Yr_6 Before.Yr_7 Before.Yr_8 After.Yr_1 After.Yr_2 After.Yr_3 After.Yr_4 After.Yr_5 After.Yr_6 After.Yr_7 After.Yr_8 sums
1          7         6           2           5           6           3           3           1           3           1          4          3          4          5          1          4          3          2   21
2          8         3           6           4           1           5           1           8           2           6          6          7          7          7          2          5          6          5   20
3          3         2           3           6           2           8           4           5           7           3          1          5          2          1          3          7          1          7    6

</code>```

UPDATE:

As recommended,  the following tidyverse function was used for counting Before.Yr and After.Yr crash counts.

```<code>sums=function(data,crashes,yrs){
data %>%
  dplyr::rowwise() %>%
    dplyr::transmute(sum = cumsum(c_across(matches(.data[[crashes]])))[.data[[yrs]]])
}
</code>```

however an  error was returned.

```<code>> sums(df,"Before.Yr","Yrs_Before")
Error: Problem with `mutate()` column `sum`.
ℹ `sum = cumsum(c_across(matches(.data[["Before.Yr"]])))[.data[["Yrs_Before"]]]`.
x Column `Before.Yr` not found in `.data`
ℹ The error occurred in row 1.
Run `rlang::last_error()` to see where the error occurred.
</code>```

suggestions for fixing the error?

答:
EDIT:

in base R you could do:

```<code>A <- split.default(df, sub('.*(After|Before).*', '\\1', names(df)))
sapply(A, \(x) rowSums(x[-1] * (col(x[-1]) <= x[[1]])))
    After Before
[1,]    21     23
[2,]    20     33
[3,]     6     11
</code>```

You can then cbind this to the original dataframe

tidyverse:

use mutate instead of transmute in order to retain the original dataframe.

```<code>df %>%
  rowwise() %>%
  transmute(After = cumsum(c_across(matches('Before.Yr')))[Yrs_Before],
            Before = cumsum(c_across(matches('After.Yr')))[Yrs_After])

# A tibble: 3 x 2
# Rowwise:
  After Before
  <int>  <int>
1    23     21
2    33     20
3    11      6
</code>```

Body:
inorder to do a paired analysis i need to write a function that sums integer counts. The total number required to be summed is specified in the corresponding "Yrs_Before" and "Yrs_After" columns in "df".  Is there a way i can avoid writing "fm_after" with just one function? Is this a variable masking for "Yrs_Before", "Yrs_After","Before.Yr_1...n+1" and "After.Yr_1...n+1" columns?

data frame

set.seed(123)
(df=data.frame(
  Yrs_Before=sample(1:8, 3),
  Yrs_After=sample(1:8, 3),
  Before.Yr_1=sample(1:8, 3),
  Before.Yr_2=sample(1:8, 3),
  Before.Yr_3=sample(1:8, 3),
  Before.Yr_4=sample(1:8, 3),
  Before.Yr_5=sample(1:8, 3),
  Before.Yr_6=sample(1:8, 3),
  Before.Yr_7=sample(1:8, 3),
  Before.Yr_8=sample(1:8, 3),
  After.Yr_1=sample(1:8, 3),
  After.Yr_2=sample(1:8, 3),
  After.Yr_3=sample(1:8, 3),
  After.Yr_4=sample(1:8, 3),
  After.Yr_5=sample(1:8, 3),
  After.Yr_6=sample(1:8, 3),
  After.Yr_7=sample(1:8, 3),
  After.Yr_8=sample(1:8, 3)

))

function sums the corresponding rows based on the number of years in the before period.

fm=function(data,Yrs_Before){
  data |> dplyr::mutate(sums=
  ifelse(
  Yrs_Before == 1, rowSums(across(Before.Yr_1)),
  ifelse(
    Yrs_Before == 2, rowSums(across(Before.Yr_1:Before.Yr_2)),
    ifelse(
      Yrs_Before == 3, rowSums(across(Before.Yr_1:Before.Yr_3)),
      ifelse(
        Yrs_Before == 4, rowSums(across(Before.Yr_1:Before.Yr_4)),
        ifelse(
          Yrs_Before == 5, rowSums(across(Before.Yr_1:Before.Yr_5)),
          ifelse(
            Yrs_Before == 6, rowSums(across(Before.Yr_1:Before.Yr_6)),
            ifelse(
              Yrs_Before == 7, rowSums(across(Before.Yr_1:Before.Yr_7)),
              ifelse(
                Yrs_Before == 8, rowSums(across(Before.Yr_1:Before.Yr_8)),"")))))))))
}

output

fm(df,Yrs_Before)
Yrs_Before Yrs_After Before.Yr_1 Before.Yr_2 Before.Yr_3 Before.Yr_4 Before.Yr_5 Before.Yr_6 Before.Yr_7 Before.Yr_8 After.Yr_1 After.Yr_2 After.Yr_3 After.Yr_4 After.Yr_5 After.Yr_6 After.Yr_7 After.Yr_8 sums
1          7         6           2           5           6           3           3           1           3           1          4          3          4          5          1          4          3          2   23
2          8         3           6           4           1           5           1           8           2           6          6          7          7          7          2          5          6          5   33
3          3         2           3           6           2           8           4           5           7           3          1          5          2          1          3          7          1          7   11

duplicated function with variable name changed to "After"

fm_after=function(data,Yrs_After){
  data |> dplyr::mutate(sums=
                   ifelse(
                     Yrs_After == 1, rowSums(across(After.Yr_1)),
                     ifelse(
                       Yrs_After == 2, rowSums(across(After.Yr_1:After.Yr_2)),
                       ifelse(
                         Yrs_After == 3, rowSums(across(After.Yr_1:After.Yr_3)),
                         ifelse(
                           Yrs_After == 4, rowSums(across(After.Yr_1:After.Yr_4)),
                           ifelse(
                             Yrs_After == 5, rowSums(across(After.Yr_1:After.Yr_5)),
                             ifelse(
                               Yrs_After == 6, rowSums(across(After.Yr_1:After.Yr_6)),
                               ifelse(
                                 Yrs_After == 7, rowSums(across(After.Yr_1:After.Yr_7)),
                                 ifelse(
                                   Yrs_After == 8, rowSums(across(After.Yr_1:After.Yr_8)),"")))))))))
}

output

fm_after(df,Yrs_After)
Yrs_Before Yrs_After Before.Yr_1 Before.Yr_2 Before.Yr_3 Before.Yr_4 Before.Yr_5 Before.Yr_6 Before.Yr_7 Before.Yr_8 After.Yr_1 After.Yr_2 After.Yr_3 After.Yr_4 After.Yr_5 After.Yr_6 After.Yr_7 After.Yr_8 sums
1          7         6           2           5           6           3           3           1           3           1          4          3          4          5          1          4          3          2   21
2          8         3           6           4           1           5           1           8           2           6          6          7          7          7          2          5          6          5   20
3          3         2           3           6           2           8           4           5           7           3          1          5          2          1          3          7          1          7    6

UPDATE:

As recommended,  the following tidyverse function was used for counting Before.Yr and After.Yr crash counts.

sums=function(data,crashes,yrs){
data %>%
  dplyr::rowwise() %>%
    dplyr::transmute(sum = cumsum(c_across(matches(.data[[crashes]])))[.data[[yrs]]])
}

however an  error was returned.

> sums(df,"Before.Yr","Yrs_Before")
Error: Problem with `mutate()` column `sum`.
ℹ `sum = cumsum(c_across(matches(.data[["Before.Yr"]])))[.data[["Yrs_Before"]]]`.
x Column `Before.Yr` not found in `.data`
ℹ The error occurred in row 1.
Run `rlang::last_error()` to see where the error occurred.

suggestions for fixing the error?

Body:
EDIT:

in base R you could do:

A <- split.default(df, sub('.*(After|Before).*', '\\1', names(df)))
sapply(A, \(x) rowSums(x[-1] * (col(x[-1]) <= x[[1]])))
    After Before
[1,]    21     23
[2,]    20     33
[3,]     6     11

You can then cbind this to the original dataframe

tidyverse:

use mutate instead of transmute in order to retain the original dataframe.

df %>%
  rowwise() %>%
  transmute(After = cumsum(c_across(matches('Before.Yr')))[Yrs_Before],
            Before = cumsum(c_across(matches('After.Yr')))[Yrs_After])

# A tibble: 3 x 2
# Rowwise:
  After Before
  <int>  <int>
1    23     21
2    33     20
3    11      6


问:
view encrypted variable in playbook gives "unbalanced" error
I have a playbook that runs correctly when used with ansible-playbook.
It contains an encrypted variable. According to the manual https://docs.ansible.com/ansible/latest/user_guide/vault.html#id16, I can view the variable with

$ ansible localhost -m ansible.builtin.debug -a var="ansible_value" -e
"'debug_playbook.yml" --vault-password-file=./pw_file

But I get an error of

ERROR! failed at splitting arguments, either an unbalanced jinja2 block or quotes: 'debug_playbook.yml

As the playbook itself runs, presumably its syntax is correct.

The playbook is

- name: Run a series of debug tasks to see the value of variables
  hosts: localhost
  vars:
    ansible_password: vault |
          $ANSIBLE_VAULT;1.1;AES256
          63343064633966653833383264346638303466663265363566643062623436383364376639636630
          3032653839323831316361613138333999999999999999999a313439383536353737616334326636
          63616162323230333635663364643935383330623637633239626632626539656434333434316631
          3965373931643338370a393530323165393762656264306130386561376362353863303232346462
          3039
  user: myuser
  tasks:
    - name: show env variable HOME and LOGNAME
      debug:
        msg: "environment variable {{ item }}"
      with_items:
      - "{{ lookup('env','HOME') }}"
      - "{{ lookup('env','LOGNAME') }}"
    - name: now show all of the variables for the current managed machine
      debug:
        msg: "{{ hostvars[inventory_hostname] }}"
    - name: now show all of the hosts in the group from inventory file
      debug:
        msg: "server {{ item }}"
      with_items:
      - "{{ groups.mintServers }}"
      - "{{ groups.centosServers }}"
```

I have googled the error and nothing jumps out (to me anyway). Is the manual correct? I have seen other methods where the encrypted variable is echoed into ansible-vault decrypt but it is all a bit of a bother.

I have yamllint'd the playbook. So interested to know what the error means and a way of debugging.

Regards

答:
Following my comments: you cannot view an encrypted var inside a playbook with the technique proposed in the documentation, for memory:

```<code>ansible localhost -m debug -a "var=your_var" \
  -e @your_file.yml --ask-vault-password
</code>```

This will only work if your file is a "simple" var file where the top level element is a dictionary.

What I have done in the past is use the yq command line tool (which is a wrapper above jq) that you can easily install with pip install yq. (Note that jq needs to be installed separately and is available in most linux distribution channels. On ubuntu: apt install jq).

Once the prerequisites are available you can use yq to extract the var from you playbook and decrypt it with ansible-vault directly.

For this to work, you will still need to fix your var value which is not a valid vault definition as it misses a question mark in front of the vault marker:

  vars:
    ansible_password: !vault |
          $ANSIBLE_VAULT;1.1;AES256
          63343064633966653833383264346638303466663265363566643062623436383364376639636630
          3032653839323831316361613138333999999999999999999a313439383536353737616334326636
          63616162323230333635663364643935383330623637633239626632626539656434333434316631
          3965373931643338370a393530323165393762656264306130386561376362353863303232346462
          3039
```
<p>The solution is not so trivial as <code>yq</code> will get the vault value adding some garbage white-space and new line at the end that will make <code>ansible-vault</code> literally freak out. With your above fixed playbook example, this would give:</p>
```yq -r '.[0].vars.ansible_password|rtrimstr(" \n")' your_playbook.yaml \
  | ansible-vault decrypt --ask-vault-pass
```

Body:
I have a playbook that runs correctly when used with ansible-playbook.
It contains an encrypted variable. According to the manual https://docs.ansible.com/ansible/latest/user_guide/vault.html#id16, I can view the variable with

$ ansible localhost -m ansible.builtin.debug -a var="ansible_value" -e
"'debug_playbook.yml" --vault-password-file=./pw_file

But I get an error of

ERROR! failed at splitting arguments, either an unbalanced jinja2 block or quotes: 'debug_playbook.yml

As the playbook itself runs, presumably its syntax is correct.

The playbook is

- name: Run a series of debug tasks to see the value of variables
  hosts: localhost
  vars:
    ansible_password: vault |
          $ANSIBLE_VAULT;1.1;AES256
          63343064633966653833383264346638303466663265363566643062623436383364376639636630
          3032653839323831316361613138333999999999999999999a313439383536353737616334326636
          63616162323230333635663364643935383330623637633239626632626539656434333434316631
          3965373931643338370a393530323165393762656264306130386561376362353863303232346462
          3039
  user: myuser
  tasks:
    - name: show env variable HOME and LOGNAME
      debug:
        msg: "environment variable {{ item }}"
      with_items:
      - "{{ lookup('env','HOME') }}"
      - "{{ lookup('env','LOGNAME') }}"
    - name: now show all of the variables for the current managed machine
      debug:
        msg: "{{ hostvars[inventory_hostname] }}"
    - name: now show all of the hosts in the group from inventory file
      debug:
        msg: "server {{ item }}"
      with_items:
      - "{{ groups.mintServers }}"
      - "{{ groups.centosServers }}"

I have googled the error and nothing jumps out (to me anyway). Is the manual correct? I have seen other methods where the encrypted variable is echoed into ansible-vault decrypt but it is all a bit of a bother.

I have yamllint'd the playbook. So interested to know what the error means and a way of debugging.

Regards

Body:
Following my comments: you cannot view an encrypted var inside a playbook with the technique proposed in the documentation, for memory:

ansible localhost -m debug -a "var=your_var" \
  -e @your_file.yml --ask-vault-password

This will only work if your file is a "simple" var file where the top level element is a dictionary.

What I have done in the past is use the yq command line tool (which is a wrapper above jq) that you can easily install with pip install yq. (Note that jq needs to be installed separately and is available in most linux distribution channels. On ubuntu: apt install jq).

Once the prerequisites are available you can use yq to extract the var from you playbook and decrypt it with ansible-vault directly.

For this to work, you will still need to fix your var value which is not a valid vault definition as it misses a question mark in front of the vault marker:

  vars:
    ansible_password: !vault |
          $ANSIBLE_VAULT;1.1;AES256
          63343064633966653833383264346638303466663265363566643062623436383364376639636630
          3032653839323831316361613138333999999999999999999a313439383536353737616334326636
          63616162323230333635663364643935383330623637633239626632626539656434333434316631
          3965373931643338370a393530323165393762656264306130386561376362353863303232346462
          3039

The solution is not so trivial as yq will get the vault value adding some garbage white-space and new line at the end that will make ansible-vault literally freak out. With your above fixed playbook example, this would give:

yq -r '.[0].vars.ansible_password|rtrimstr(" \n")' your_playbook.yaml \
  | ansible-vault decrypt --ask-vault-pass


问:
How to convert a hexadecimal string of data to an ArrayBuffer in JavaScript
How do I convert the string 'AA5504B10000B5' to an ArrayBuffer?

答:
Compact one-liner version:</p>
```<code>new Uint8Array('AA5504B10000B5'.match(/../g).map(h=>parseInt(h,16))).buffer
</code>```

Body:
Compact one-liner version:

new Uint8Array('AA5504B10000B5'.match(/../g).map(h=>parseInt(h,16))).buffer


问:
Horizontal scrolling with mouse wheel in a div
How to scroll horizontal in na div with mouse wheel, or drag with jquery?

I've tried draggable, but in my code it isn't useful.

Now I've got a horizontal scrollbar. Is there a posibility to scroll the content in my div using the mouse wheel?

答:
```<code>why is mine failing?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style type="text/css">

        * {
          margin:0;
          padding:0;
        }

        #page-wrap {
          width:500%; /* 100% x length of panel */
          height:100%;
          overflow:hidden;
        }

        .panel {
          width:20%; /* 100% / length of panel */
          float:left;
          height:100%;
        }

        .panel .inner {padding:2em}

        /* Details (Ignore this!) */
        body {
          font:italic normal 13px/1.4 Georgia,Serif;
          color:#666;
        }

        h2 {
          font-weight:bold;
          font-size:200%;
          margin:0 0 1em;
        }

        p {margin:1.5em 0}

        #panel-1 {
          background-color:black;
          color:white;
        }

        #panel-2 {
          background-color:magenta;
          color:yellow;
        }

        #panel-3 {
          background-color:darkblue;
          color:lightgreen;
        }

        #panel-4 {
          background-color:pink;
          color:brown;
        }

        #panel-5 {
          background-color:darkred;
          color:cyan;
        }

        </style>
</head>
<body >
    <div  >
        <section style="height:500px;width:100%;color: rgb(29, 121, 202);">
            <h2>WWF History</h2>
            <p>The World Wide Fund for Nature (WWF) is an international organization working on issues regarding the conservation, research and restoration of the environment, formerly named the World Wildlife Fund. WWF was founded in 1961.</p>
          </section>

          <section style="height:500px;width:100%;color: rgb(223, 12, 135);">
            <h2>WWF's Symbol</h2>
            <p>The Panda has become the symbol of WWF. The well-known panda logo of WWF originated from a panda named Chi Chi that was transferred from the Beijing Zoo to the London Zoo in the same year of the establishment of WWF.</p>
          </section>
          <section id="vane">
                <div id="page-wrap">
            <div class="panel" id="panel-1">
                <div class="inner"><h2>Eodem Modo Typi</h2><div style="-webkit-column-count:4;-moz-column-count:4;column-count:4;-webkit-column-gap:1em;-moz-column-gap:1em;column-gap:1em;text-align:right;"><p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p><p>Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum.</p><p>Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.</p></div><p style="font-size:500%;font-style:normal;text-align:right;">⇒</p></div>
            </div>
            <div class="panel" id="panel-2">
                <div class="inner"><h2>Facilisis At Vero Eros</h2><div style="-webkit-column-count:2;-moz-column-count:2;column-count:2;-webkit-column-gap:2em;-moz-column-gap:2em;column-gap:2em;"><p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p><p>Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum.</p><p>Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.</p></div></div>
            </div>
            <div class="panel" id="panel-3">
                <div class="inner"><img src="http://lorempixel.com/400/400/food/" alt="Image" width="400" height="400" style="float:right;margin:0 0 0 3em;"><h2>Euismod Tincidunt</h2><div><p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p></div></div>
            </div>
            <div class="panel" id="panel-4">
                <div class="inner"><h2>Claritas est Etiam Processus Dynamicus</h2><img src="http://lorempixel.com/200/200/food/" alt="Image" width="200" height="200" style="float:right;margin:0 0 0 3em;"><div style="-webkit-column-count:2;-moz-column-count:2;column-count:2;-webkit-column-gap:2em;-moz-column-gap:2em;column-gap:2em;"><p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p><p>Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum.</p><p>Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.</p></div></div>
            </div>
            <div class="panel" id="panel-5">
                <div class="inner"><img src="http://lorempixel.com/400/400/food/" alt="Image" width="400" height="400" style="float:left;margin:0 3em 0 0;"><h2>Vulputate Velit Esse Molestie</h2><div style="-webkit-column-count:4;-moz-column-count:4;column-count:4;-webkit-column-gap:1em;-moz-column-gap:1em;column-gap:1em;"><p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p><p>Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum.</p><p>Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.</p></div></div>
            </div>
        </div>
          </section>

          <section  style="height:500px;width:200%; color: rgb(29, 121, 202);  ">
          <div  >
            <h2>WWF History</h2>
            <p >The World Wide Fund for Nature (WWF) is an international organization working on issues regarding the conservation, research and restoration of the environment, formerly named the World Wildlife Fund. WWF was founded in 1961.</p>
          </div>
          </section>

          <section style="height:500px;width:100%;color: rgb(223, 12, 135);">
            <h2>WWF's Symbol</h2>
            <p>The Panda has become the symbol of WWF. The well-known panda logo of WWF originated from a panda named Chi Chi that was transferred from the Beijing Zoo to the London Zoo in the same year of the establishment of WWF.</p>
          </section>
    </div>

</body>
<script>
     (function() {
    function scrollHorizontally(e) {
        e = window.event || e;
        var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
        console.log(delta)
      var resultado =  document.getElementById('vane').scrollLeft -= (delta * 40 ); // Multiplied by 40
        e.preventDefault();
        console.log()
    }
    if (document.getElementById('vane').addEventListener) {
        // IE9, Chrome, Safari, Opera
        document.getElementById('vane').addEventListener('mousewheel', scrollHorizontally, false);
        // Firefox
        document.getElementById('vane').addEventListener('DOMMouseScroll', scrollHorizontally, false);
    } else {
        // IE 6/7/8
        document.getElementById('vane').attachEvent('onmousewheel', scrollHorizontally);
    }
})();
</script>
</html>

</code>```

Body:
why is mine failing?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style type="text/css">

        * {
          margin:0;
          padding:0;
        }

        #page-wrap {
          width:500%; /* 100% x length of panel */
          height:100%;
          overflow:hidden;
        }

        .panel {
          width:20%; /* 100% / length of panel */
          float:left;
          height:100%;
        }

        .panel .inner {padding:2em}

        /* Details (Ignore this!) */
        body {
          font:italic normal 13px/1.4 Georgia,Serif;
          color:#666;
        }

        h2 {
          font-weight:bold;
          font-size:200%;
          margin:0 0 1em;
        }

        p {margin:1.5em 0}

        #panel-1 {
          background-color:black;
          color:white;
        }

        #panel-2 {
          background-color:magenta;
          color:yellow;
        }

        #panel-3 {
          background-color:darkblue;
          color:lightgreen;
        }

        #panel-4 {
          background-color:pink;
          color:brown;
        }

        #panel-5 {
          background-color:darkred;
          color:cyan;
        }

        </style>
</head>
<body >
    <div  >
        <section style="height:500px;width:100%;color: rgb(29, 121, 202);">
            <h2>WWF History</h2>
            <p>The World Wide Fund for Nature (WWF) is an international organization working on issues regarding the conservation, research and restoration of the environment, formerly named the World Wildlife Fund. WWF was founded in 1961.</p>
          </section>

          <section style="height:500px;width:100%;color: rgb(223, 12, 135);">
            <h2>WWF's Symbol</h2>
            <p>The Panda has become the symbol of WWF. The well-known panda logo of WWF originated from a panda named Chi Chi that was transferred from the Beijing Zoo to the London Zoo in the same year of the establishment of WWF.</p>
          </section>
          <section id="vane">
                <div id="page-wrap">
            <div class="panel" id="panel-1">
                <div class="inner"><h2>Eodem Modo Typi</h2><div style="-webkit-column-count:4;-moz-column-count:4;column-count:4;-webkit-column-gap:1em;-moz-column-gap:1em;column-gap:1em;text-align:right;"><p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p><p>Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum.</p><p>Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.</p></div><p style="font-size:500%;font-style:normal;text-align:right;">&rArr;</p></div>
            </div>
            <div class="panel" id="panel-2">
                <div class="inner"><h2>Facilisis At Vero Eros</h2><div style="-webkit-column-count:2;-moz-column-count:2;column-count:2;-webkit-column-gap:2em;-moz-column-gap:2em;column-gap:2em;"><p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p><p>Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum.</p><p>Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.</p></div></div>
            </div>
            <div class="panel" id="panel-3">
                <div class="inner"><img src="http://lorempixel.com/400/400/food/" alt="Image" width="400" height="400" style="float:right;margin:0 0 0 3em;"><h2>Euismod Tincidunt</h2><div><p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p></div></div>
            </div>
            <div class="panel" id="panel-4">
                <div class="inner"><h2>Claritas est Etiam Processus Dynamicus</h2><img src="http://lorempixel.com/200/200/food/" alt="Image" width="200" height="200" style="float:right;margin:0 0 0 3em;"><div style="-webkit-column-count:2;-moz-column-count:2;column-count:2;-webkit-column-gap:2em;-moz-column-gap:2em;column-gap:2em;"><p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p><p>Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum.</p><p>Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.</p></div></div>
            </div>
            <div class="panel" id="panel-5">
                <div class="inner"><img src="http://lorempixel.com/400/400/food/" alt="Image" width="400" height="400" style="float:left;margin:0 3em 0 0;"><h2>Vulputate Velit Esse Molestie</h2><div style="-webkit-column-count:4;-moz-column-count:4;column-count:4;-webkit-column-gap:1em;-moz-column-gap:1em;column-gap:1em;"><p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p><p>Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum.</p><p>Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.</p></div></div>
            </div>
        </div>
          </section>

          <section  style="height:500px;width:200%; color: rgb(29, 121, 202);  ">
          <div  >
            <h2>WWF History</h2>
            <p >The World Wide Fund for Nature (WWF) is an international organization working on issues regarding the conservation, research and restoration of the environment, formerly named the World Wildlife Fund. WWF was founded in 1961.</p>
          </div>
          </section>

          <section style="height:500px;width:100%;color: rgb(223, 12, 135);">
            <h2>WWF's Symbol</h2>
            <p>The Panda has become the symbol of WWF. The well-known panda logo of WWF originated from a panda named Chi Chi that was transferred from the Beijing Zoo to the London Zoo in the same year of the establishment of WWF.</p>
          </section>
    </div>

</body>
<script>
     (function() {
    function scrollHorizontally(e) {
        e = window.event || e;
        var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
        console.log(delta)
      var resultado =  document.getElementById('vane').scrollLeft -= (delta * 40 ); // Multiplied by 40
        e.preventDefault();
        console.log()
    }
    if (document.getElementById('vane').addEventListener) {
        // IE9, Chrome, Safari, Opera
        document.getElementById('vane').addEventListener('mousewheel', scrollHorizontally, false);
        // Firefox
        document.getElementById('vane').addEventListener('DOMMouseScroll', scrollHorizontally, false);
    } else {
        // IE 6/7/8
        document.getElementById('vane').attachEvent('onmousewheel', scrollHorizontally);
    }
})();
</script>
</html>