问:
JavaScript Use classList attribute to call internal variable
I'm creating a basic typing game to help teach myself Thai typing and I'm breaking down the keyboard into sections (14 total).

I'm using an onclick from HTML to call a function in my js file and that works great.  I pass 'thaiRightTop' from the initial onclick and the text loads fine.

HTML

```<code><a href="#" onclick="selector(thaiRightTop, className='thaiRightTop')">Thai Right Top</a>
</code>```

JS

```<code>const thaiRightTop = ['ภ','ถ']

function selector(ele, className){
        let textDisplay = document.querySelector('#textDisplay')
        textDisplay.innerHTML = ''
        textDisplay.classList = ''
        textDisplay.classList = className
        const words = createWords(ele, 3,5, 60)
        addSpan(words)
    }
</code>```

However once the user has typed out the full string of words correctly I want to load another set of words using the same array.

Where I'm confused and having issues is calling the same selector function from with JS and using the classList class name to call through the variable ele

```<code>if (correct === true){
    let textDisplay = document.querySelector('#textDisplay')
    className = textDisplay.classList
    selector(ele=className, className=String(className))
}
</code>```

I know I can define if/else if/switch case statement and hard code each array name (total of 14) but that seems like it's really redundant and unnecessary.  Is there an easy way to use a class name to refer to a const?

Thanks in advance and apologies if this is a repeat question but I couldn't find anything anywhere else...

Added a CodePen Link - Once the first sentence is completed I want to reload the the same set (thaiRightTop) which will create another random sequence of words.

I created an IneffecientSelector to show what I didn't want to do but how it should work (sorry if I used codePen instead of SO Snippet, I'm more familiar with CP).

codePen Link

答:
I found my mistake!
textDisplay.classList returns a DOMTokenList.  I wasn't parsing that as a list, I was passing the whole thing thinking it was a value already.  I also changed my keyboard sections to a dictionary which made it easier to work with.

Thanks!

Body:
I'm creating a basic typing game to help teach myself Thai typing and I'm breaking down the keyboard into sections (14 total).

I'm using an onclick from HTML to call a function in my js file and that works great.  I pass 'thaiRightTop' from the initial onclick and the text loads fine.

HTML

Thai Right Top

JS

const thaiRightTop = ['ภ','ถ']

function selector(ele, className){
        let textDisplay = document.querySelector('#textDisplay')
        textDisplay.innerHTML = ''
        textDisplay.classList = ''
        textDisplay.classList = className
        const words = createWords(ele, 3,5, 60)
        addSpan(words)
    }

However once the user has typed out the full string of words correctly I want to load another set of words using the same array.

Where I'm confused and having issues is calling the same selector function from with JS and using the classList class name to call through the variable ele

if (correct === true){
    let textDisplay = document.querySelector('#textDisplay')
    className = textDisplay.classList
    selector(ele=className, className=String(className))
}

I know I can define if/else if/switch case statement and hard code each array name (total of 14) but that seems like it's really redundant and unnecessary.  Is there an easy way to use a class name to refer to a const?

Thanks in advance and apologies if this is a repeat question but I couldn't find anything anywhere else...

Added a CodePen Link - Once the first sentence is completed I want to reload the the same set (thaiRightTop) which will create another random sequence of words.

I created an IneffecientSelector to show what I didn't want to do but how it should work (sorry if I used codePen instead of SO Snippet, I'm more familiar with CP).

codePen Link


来源: stackexchange

问:
Django rest_framework not serializing relationships
I am trying to serialize Foreign keys inline with Django rest_framework. Foreign keys are used to link lookup tables as per a normal DB normalisation setup.

An example of my model with the lookup:

```<code>class OrderStatus(models.Model):
    StatusId = models.PositiveSmallIntegerField(primary_key=True)
    StatusDescription = models.CharField(max_length=50)

class Order(models.Model):
    OrderId = models.AutoField(primary_key=True)
    OrderDate = models.DateTimeField(auto_now_add=True)
    Status = models.ForeignKey(OrderStatus, on_delete=models.CASCADE)
</code>```

My serializers:

```<code>class OrderStatusSerializer(serializers.ModelSerializer):
    class Meta:
        model = OrderStatus
        fields = ['StatusId', 'StatusDescription']

class OrderSerializer(serializers.ModelSerializer):
    class Meta:
        model = Order
        fields = ('OrderId', 'OrderDate', 'Status')
</code>```

What I obtain when I call the REST API is the following:

```<code>{
    "type": "Order",
    "id": "1",
    "attributes": {
        "OrderId": 1,
        "OrderDate": "2020-05-19T08:23:54"
     },
     "relationships": {
        "Status": {
            "data": {
                "type": "OrderStatus",
                "id": "1"
            }
        }
    }
}
</code>```

I would like to have the Status inline in the "attributes", either as a simple id or even as a JSON object with the two values inline. Both are good options, as long as it's not in that "relationships" field.

I tried to add the following to OrderSerializer:

```<code>Status = serializers.PrimaryKeyRelatedField(queryset=OrderStatus.objects.all())
</code>```

No difference.

I tried the following:

```<code>Status = OrderStatusSerializer(many=False)
</code>```

No difference.

I tried all the other options in
https://github.com/encode/django-rest-framework/blob/master/docs/api-guide/relations.md
including the SlugField to include the description instead that the ID, with no result.

It seems that what I change has no effect on the serialization.

答:
As per my own comment, the issue was caused by rest_framework_json_api.renderers.JSONRenderer.

By switching it back to rest_framework.renderers.JSONRenderer the expected documented behaviour has been re-established.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to serialize Foreign keys inline with Django rest_framework. Foreign keys are used to link lookup tables as per a normal DB normalisation setup.

An example of my model with the lookup:

class OrderStatus(models.Model):
    StatusId = models.PositiveSmallIntegerField(primary_key=True)
    StatusDescription = models.CharField(max_length=50)

class Order(models.Model):
    OrderId = models.AutoField(primary_key=True)
    OrderDate = models.DateTimeField(auto_now_add=True)
    Status = models.ForeignKey(OrderStatus, on_delete=models.CASCADE)

My serializers:

class OrderStatusSerializer(serializers.ModelSerializer):
    class Meta:
        model = OrderStatus
        fields = ['StatusId', 'StatusDescription']

class OrderSerializer(serializers.ModelSerializer):
    class Meta:
        model = Order
        fields = ('OrderId', 'OrderDate', 'Status')

What I obtain when I call the REST API is the following:

{
    "type": "Order",
    "id": "1",
    "attributes": {
        "OrderId": 1,
        "OrderDate": "2020-05-19T08:23:54"
     },
     "relationships": {
        "Status": {
            "data": {
                "type": "OrderStatus",
                "id": "1"
            }
        }
    }
}

I would like to have the Status inline in the "attributes", either as a simple id or even as a JSON object with the two values inline. Both are good options, as long as it's not in that "relationships" field.

I tried to add the following to OrderSerializer:

Status = serializers.PrimaryKeyRelatedField(queryset=OrderStatus.objects.all())

No difference.

I tried the following:

Status = OrderStatusSerializer(many=False)

No difference.

I tried all the other options in
https://github.com/encode/django-rest-framework/blob/master/docs/api-guide/relations.md
including the SlugField to include the description instead that the ID, with no result.

It seems that what I change has no effect on the serialization.


问:
Adding global session filter to repository entity
I need to add a global filter to a repository entity, i.e. it has to be applied everywhere this entity is accessed on Application service layer. My filter contains two conditions. Whereas adding the first condition, which depends on a constant, is easy and applied in OnModelCreating using HasQueryFilter, I have no idea how to apply automatically the second one, which depends on the currently selected (or default)  UI language.</p>

答:
Use dependency injection via constructor in your DbContext class. Set the currently selected UI language inside the class implementing the interface. Use the injected implementation in the OnModelCreating method to apply the filter globally with .HasQueryFilter() method like you normally would.

If you're using something like a .NET Core API, you could build a middleware that determines the language of the current incoming request. I guess the same will work for MVC too.


问:
Why I can't run "npm run sass"?
When I run "npm run sass" I got an error. Please check my screenshot npm run sass screnshot</p>

答: If it's not installed globally, you might have to run it from your node_modules folder: ./node_modules/.bin/node-sass.

Title: Why I can't run "npm run sass"?


问:
router.patch is returning 404 "not found"
I am working on small node api and I have an issue with patch method.
My router.patch is returning me 404.

This is how my route looks:

```<code>router.param('userId', findById);

router.patch(
  '/api/projects/update/:projectId/:userId',
  authCheck,
  isAdmin,
  findProjectById,
  update
);
</code>```

The findById is based on my :userId param. Whole method looks like this:

```<code>exports.findById = async (req, res, next) => {
  try {
    let user = await User.findById(req.params.userId);
    if (!user) return res.status(400).json({ msg: 'User not found' });
    next();
  } catch (err) {
    console.error(err.message);
    if (err.kind === 'ObjectId') {
      return res.status(400).json({ msg: 'User not found' });
    }
    res.status(500).send('Server Error');
  }
};
</code>```

Based on that I should get proper user for proper project.

My two ayhorization methods:

```<code>exports.authCheck = async (req, res, next) => {
  try {
    /* get token from header
    replace('Bearer', '') - this will remove bearer from token header
    */

    const token = req.header('Authorization').replace('Bearer', '');

    //check if no token
    if (!token) {
      return res.status(401).json({ msg: 'No token, authorization denied' });
    }

    /*
    decoded contains _id as a payload in token. Id is from getAuthToken */
    const decoded = jwt.verify(token, config.get('jwtSecret'));
    const user = await User.findOne({
      _id: decoded._id,
      'tokens.token': token,
    });

    if (!user) {
      throw new Error();
    }
    req.token = token;
    req.user = user;
    next();
  } catch (err) {
    res.status(401).json({ msg: 'Please authenticate' });
  }
};

exports.isAdmin = async (req, res, next) => {
  try {
    if (req.user.role !== config.get('roleSecret')) {
      return res.status(403).json({
        errors: [
          {
            msg: 'No Admin rights. Access Denied!!',
          },
        ],
      });
    }
    next();
  } catch (err) {
    res.status(403).json({ msg: 'Forbidden access' });
  }
};
</code>```

Finaly, my project controller where i have findProjectById, update
In findProjectById I am looking for project based on route param and i assing it to project

```<code>exports.findProjectById = async (req, res, next) => {
  const _id = req.params.projectId;
  try {
    let project = await Project.findById(_id);
    if (!project) return res.status(400).json({ msg: 'Porject not found' });
    req.project = project;
    next();
  } catch (err) {
    console.error(err.message);
    if (err.kind === 'ObjectId') {
      return res.status(400).json({ msg: 'Porject not found' });
    }
    res.status(500).send('Server Error');
  }
};

</code>```

My update method i s not done, because i was testing if anything heppens

```<code>exports.update = async (req, res) => {
  try {
    const proj = await req.project;
    const _id = proj._id;
    await Project.findByIdAndUpdate(_id, req.body, {
      new: true,
      runValidators: true,
    });
    if (!proj) {
      return res.status(404).json({ msg: 'Project not found' });
    }
    return res.json(proj);
  } catch (err) {
    res.status(500).send('Server Error');
  }
};
</code>```

Not sure what am I missing here, but after few hours and lot of searching still can't get this working

答:
Get this working. Issue was in my router path.

/api/projects/update/:projectId/:userId
Should be
/projects/update/:projectId/:userId

this can be closed

Body:
I am working on small node api and I have an issue with patch method.
My router.patch is returning me 404.

This is how my route looks:

router.param('userId', findById);

router.patch(
  '/api/projects/update/:projectId/:userId',
  authCheck,
  isAdmin,
  findProjectById,
  update
);

The findById is based on my :userId param. Whole method looks like this:

exports.findById = async (req, res, next) => {
  try {
    let user = await User.findById(req.params.userId);
    if (!user) return res.status(400).json({ msg: 'User not found' });
    next();
  } catch (err) {
    console.error(err.message);
    if (err.kind === 'ObjectId') {
      return res.status(400).json({ msg: 'User not found' });
    }
    res.status(500).send('Server Error');
  }
};

Based on that I should get proper user for proper project.

My two ayhorization methods:

exports.authCheck = async (req, res, next) => {
  try {
    /* get token from header
    replace('Bearer', '') - this will remove bearer from token header
    */

    const token = req.header('Authorization').replace('Bearer', '');

    //check if no token
    if (!token) {
      return res.status(401).json({ msg: 'No token, authorization denied' });
    }

    /*
    decoded contains _id as a payload in token. Id is from getAuthToken */
    const decoded = jwt.verify(token, config.get('jwtSecret'));
    const user = await User.findOne({
      _id: decoded._id,
      'tokens.token': token,
    });

    if (!user) {
      throw new Error();
    }
    req.token = token;
    req.user = user;
    next();
  } catch (err) {
    res.status(401).json({ msg: 'Please authenticate' });
  }
};

exports.isAdmin = async (req, res, next) => {
  try {
    if (req.user.role !== config.get('roleSecret')) {
      return res.status(403).json({
        errors: [
          {
            msg: 'No Admin rights. Access Denied!!',
          },
        ],
      });
    }
    next();
  } catch (err) {
    res.status(403).json({ msg: 'Forbidden access' });
  }
};

Finaly, my project controller where i have findProjectById, update
In findProjectById I am looking for project based on route param and i assing it to project

exports.findProjectById = async (req, res, next) => {
  const _id = req.params.projectId;
  try {
    let project = await Project.findById(_id);
    if (!project) return res.status(400).json({ msg: 'Porject not found' });
    req.project = project;
    next();
  } catch (err) {
    console.error(err.message);
    if (err.kind === 'ObjectId') {
      return res.status(400).json({ msg: 'Porject not found' });
    }
    res.status(500).send('Server Error');
  }
};

My update method i s not done, because i was testing if anything heppens

exports.update = async (req, res) => {
  try {
    const proj = await req.project;
    const _id = proj._id;
    await Project.findByIdAndUpdate(_id, req.body, {
      new: true,
      runValidators: true,
    });
    if (!proj) {
      return res.status(404).json({ msg: 'Project not found' });
    }
    return res.json(proj);
  } catch (err) {
    res.status(500).send('Server Error');
  }
};

Not sure what am I missing here, but after few hours and lot of searching still can't get this working


问:
Problem with datatables and rowgroup - won't collapse/expand more than 2 groups
I have followed some instructions how to apply rowgroup for collapse/expand but the rowgroups won't collapse when more than 2 rowgroups defined:

```<code>rowGroup: {
                dataSrc: [3,1,2]
            }
</code>```

Here is my example:

http://live.datatables.net/yosigodi/1/edit

does anyone know how to alter the script so more than 2 rowgroups can be used for collapse/expand?

答:
I tried to apply the following script:

http://live.datatables.net/migixiqi/1/edit

And just added an additional third row for you:

```<code>$(document).ready(function() {
    var collapsedGroups = {};
    var top = '';
    var table = $('#example').DataTable({
        order: [
            [1, 'asc'],
            [2, 'asc']
        ],
        rowGroup: {
            dataSrc: [3, 2, 1],
            startRender: function(rows, group, level) {
                var all;

                if (level === 0) {
                    top = group;
                    all = group;
                } else {
                    // if parent collapsed, nothing to do
                    if (!!collapsedGroups[top]) {
                        return;
                    }
                    all = top + group;
                }

                var collapsed = !!collapsedGroups[all];

                rows.nodes().each(function(r) {
                    r.style.display = collapsed ? 'none' : '';
                });

                // Add category name to the <tr>. NOTE: Hardcoded colspan
                return $('<tr/>')
                    .append('<td colspan="8">' + group + ' (' + rows.count() + ')</td>')
                    .attr('data-name', all)
                    .toggleClass('collapsed', collapsed);
            }
        }

    });

    $('#example tbody').on('click', 'tr.dtrg-start', function() {
        var name = $(this).data('name');

        collapsedGroups[name] = !collapsedGroups[name];
        table.draw(false);
    });

});
</code>```

But it does not work for more than 2 columns :-/

Body:
I have followed some instructions how to apply rowgroup for collapse/expand but the rowgroups won't collapse when more than 2 rowgroups defined:

rowGroup: {
                dataSrc: [3,1,2]
            }

Here is my example:

http://live.datatables.net/yosigodi/1/edit

does anyone know how to alter the script so more than 2 rowgroups can be used for collapse/expand?

Body:
I tried to apply the following script:

http://live.datatables.net/migixiqi/1/edit

And just added an additional third row for you:

$(document).ready(function() {
    var collapsedGroups = {};
    var top = '';
    var table = $('#example').DataTable({
        order: [
            [1, 'asc'],
            [2, 'asc']
        ],
        rowGroup: {
            dataSrc: [3, 2, 1],
            startRender: function(rows, group, level) {
                var all;

                if (level === 0) {
                    top = group;
                    all = group;
                } else {
                    // if parent collapsed, nothing to do
                    if (!!collapsedGroups[top]) {
                        return;
                    }
                    all = top + group;
                }

                var collapsed = !!collapsedGroups[all];

                rows.nodes().each(function(r) {
                    r.style.display = collapsed ? 'none' : '';
                });

                // Add category name to the <tr>. NOTE: Hardcoded colspan
                return $('<tr/>')
                    .append('<td colspan="8">' + group + ' (' + rows.count() + ')</td>')
                    .attr('data-name', all)
                    .toggleClass('collapsed', collapsed);
            }
        }

    });

    $('#example tbody').on('click', 'tr.dtrg-start', function() {
        var name = $(this).data('name');

        collapsedGroups[name] = !collapsedGroups[name];
        table.draw(false);
    });

});

But it does not work for more than 2 columns :-/


问:
Sending Azure App Service HTTP Logs from Diagnostics Settings to Azure Monitor Log Analytics Workspace
I'm struggling to get get my Azure App Service to send it's logs to Azure Log Analytics in Azure Monitor. It's an ASP.NET Core 3.1 web app hosted on Windows.

I have configured the "Disagnostics Settings (Preview)" blades options to have the category "AppServiceHTTPLogs" checked and to "Send to Log Analytics" with the relevant workspace selected. (As per this blog post https://azure.github.io/AppService/2019/11/01/App-Service-Integration-with-Azure-Monitor.html)

Once configured, I left it for 24 hours assuming that there could be some lag between setup and visibility of any logs. After waiting I have gone to the "Log Analytics Workspace" that was linked in the diagnostic settings, clicked the "Logs" blade and run a Kusto query for all "AppServiceHTTPLogs" in the last 24 hours. There are no results returned by the query.

I've read through many docs links (https://learn.microsoft.com/en-us/azure/azure-monitor/platform/diagnostic-settings and https://learn.microsoft.com/en-us/azure/app-service/troubleshoot-diagnostic-logs) and other SO questions (Sending logs from .net core application running in App Service to log analytics) but none of them seem to provide anything that points me in the right direction.

Has anyone managed to get this successfully working?
Are there any additional steps required to have this actually work?
Are there any common mistakes people make when trying to set this up that I could have made?

答:
The feedback from the support team:

This feature is still in preview, and it does work in the regions of US and east asia(it may take some time to show the logs). For other regions, it may not work.

Hope this can help others who encountered this issue.


问:
how to charge amount at beginning of billing cycle in paypal
Let say I have an Plan which has setup fee 0 and billing amount $10 per day.

I have created a suscription for that plan, i have configured a webhook for payment.sale.created , but when a user subscribe to that plan he is not paying any amount on the day of subsription. Ex. if he subscriber on june 1,2020 he is not charging when he subscribes. Amount is deducted from his account on next day i.e, June 2,2020.

How can I charge him on the day of subscription i.e, immediately when he subscribes to a plan he must be charged and setup fee should be 0.

according to documentation of paypal subscription :
For example, if a subscription is $10 USD a week and the subscriber signs up on Tuesday, December 23, the subscriber is billed as follows:

```<code>Tuesday, December 23 = $10.00 USD
Tuesday, December 30 = $10.00 USD
Tuesday, January 6 = $10.00 USD
</code>```

But this is not happening in sandbox testing.

答:
How can I charge him on the day of subscription i.e, immediately when he subscribes to a plan he must be charged and setup fee should be 0.

What you are describing is exactly what the setup_fee is for. If you want to charge anything on the day of creation, use setup_fee.

Otherwise, you have to wait for the billing engine to process the next cycle, which will not happen on that same day , that is not how subscription billing works.

It is, however, how setup_fee works -- so setup_fee is there if you need this feature of billing on the same day.

You can combine setup_fee with a one week free trial, for example, if you need to ensure an immediate billing at the moment of checkout.

Body:
Let say I have an Plan which has setup fee 0 and billing amount $10 per day.

I have created a suscription for that plan, i have configured a webhook for payment.sale.created , but when a user subscribe to that plan he is not paying any amount on the day of subsription. Ex. if he subscriber on june 1,2020 he is not charging when he subscribes. Amount is deducted from his account on next day i.e, June 2,2020.

How can I charge him on the day of subscription i.e, immediately when he subscribes to a plan he must be charged and setup fee should be 0.

according to documentation of paypal subscription :
For example, if a subscription is $10 USD a week and the subscriber signs up on Tuesday, December 23, the subscriber is billed as follows:

Tuesday, December 23 = $10.00 USD
Tuesday, December 30 = $10.00 USD
Tuesday, January 6 = $10.00 USD

But this is not happening in sandbox testing.


问:
Most Efficient Way Of Clearing Cache Using ASP.NET
I am building an ASP.NET/Umbraco powered website which is very custom data driven via  entity framework, we are having to cache quite a lot of the data queries (For example searches by keyword) as it's a busy site.

But when a user creates a new data entry, I need to clear all the cached queries (Searches etc..) so the new entry is available in the results.

So in my create, delete and update methods I am calling the following method:

```<code>public static void ClearCacheItems()
{
    var enumerator = HttpContext.Current.Cache.GetEnumerator();

    while (enumerator.MoveNext())
    {
        HttpContext.Current.Cache.Remove(enumerator.Key.ToString());
    }
}
</code>```

Is this really bad? I can't see how else I am supposed to clear the cached items?

答:
The method you use is actually the correct way to clear your cache, there is just one minor 'error' in your code. The enumerator only is valid as long as the original collection remains unchanged. So while the code might work most of the time, there might be small errors in certain situations. Best is to use the following code, which does essentially the same, but does not use the enumerator directly.

```<code>List<string> keys = new List<string>();
IDictionaryEnumerator enumerator = Cache.GetEnumerator();

while (enumerator.MoveNext())
  keys.Add(enumerator.Key.ToString());

for (int i = 0; i < keys.Count; i++)
  Cache.Remove(keys[i]);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am building an ASP.NET/Umbraco powered website which is very custom data driven via  entity framework, we are having to cache quite a lot of the data queries (For example searches by keyword) as it's a busy site.

But when a user creates a new data entry, I need to clear all the cached queries (Searches etc..) so the new entry is available in the results.

So in my create, delete and update methods I am calling the following method:

public static void ClearCacheItems()
{
    var enumerator = HttpContext.Current.Cache.GetEnumerator();

    while (enumerator.MoveNext())
    {
        HttpContext.Current.Cache.Remove(enumerator.Key.ToString());
    }
}

Is this really bad? I can't see how else I am supposed to clear the cached items?

Body:
The method you use is actually the correct way to clear your cache, there is just one minor 'error' in your code. The enumerator only is valid as long as the original collection remains unchanged. So while the code might work most of the time, there might be small errors in certain situations. Best is to use the following code, which does essentially the same, but does not use the enumerator directly.

List<string> keys = new List<string>();
IDictionaryEnumerator enumerator = Cache.GetEnumerator();

while (enumerator.MoveNext())
  keys.Add(enumerator.Key.ToString());

for (int i = 0; i < keys.Count; i++)
  Cache.Remove(keys[i]);


问:
How can I make a cross-OS sh script for Docker usage?
I'm using docker for my projects, mostly Laravel ones, which has the configurement of building a MySQL container and an app container.

The containers respectively is named "db" and "app".

The .env file is therefore configured after the hostname "db" in order to have the served webserver properly initialised

This enforces the developer to be inside the container in order to run appropiate commands that has anything to do with the database connection, otherwise giving error as the environment believes we are talking about a mysql instance at the computer. (right?)

Therefore, a script in the project root directory is made in order to ease this.

./cmd.sh artisan migrate (Works)

php artisan migrate (Does not) - unknown database

This concludes to the problem of mine, which I'm here for.

As you might see, this is oddly specific to MacOS environment and that would be true. Having the need of this script to work cross-os, meaning painlessly for Linux and Windows developers as well, is somewhat of a struggle of mine.

So, the issue in TLDR: How can I arrange this method of ease to work for all OS?

Using the current way has these issues:

Linux:

1000 is the default user, not 33. Simply changing 33 to 1000 kind of fixes it

changing to 1000 makes it not working for mac though

Windows:

Needs powershell for bash, otherwise (cannot find the tty input device)

Powershell cant read the sh syntax

I kind of want to try staying away from using multiplie files, one for each os, as solution.

So, what am I missing here, is this even doable and where could I read about making this doable?

Thank you so much in advance and so sorry about the wall of text.

TLDR: For docker projects, how can i make a script that can run the container command for all Operative systems?

答:
Using inspo from How to detect the OS from a Bash script?, (thanks Richard Barber for link), I managed to come around my problem using the OSTYPE variable to diff which OS that's in use.

For windows, simply use a bash terminal and the settings for either Linux or MacOS would work.

```<code>#!/bin/bash

if [[ "$OSTYPE" == "linux-gnu"* ]]; then
  USER="1000"
else
  USER="33"
fi

artisan() {
    docker-compose exec --user $USER app php artisan "$@"
}

"$@"
</code>```

Body:
Using inspo from How to detect the OS from a Bash script?, (thanks Richard Barber for link), I managed to come around my problem using the OSTYPE variable to diff which OS that's in use.

For windows, simply use a bash terminal and the settings for either Linux or MacOS would work.

#!/bin/bash

if [[ "$OSTYPE" == "linux-gnu"* ]]; then
  USER="1000"
else
  USER="33"
fi

artisan() {
    docker-compose exec --user $USER app php artisan "$@"
}

"$@"


问:
How to get only date (DD-MM-YYYY) format not time with date using moment.js?
I am using moment.js for formatting dates:

```<code>const dateFormat = 'DD/MM/YYYY';
setValue('startDate', moment(booking.startDate, dateFormat));
</code>```

I want the date to be 01-06-2020 instead of 2020-06-01T07:33:04.392Z. Any idea, because I don't know how to do this?

答:
Here's an example for how to format an instance of moment.js as DD-MM-YYYY:

const dateString = moment("2020-06-01T12:00:00").format("DD-MM-YYYY");
console.log({ dateString });
```

<p>This gives the following in the console:</p>

```{ dateString: '01-06-2020' }
```

It'd be good to read more about moment's format function and the standard W3C date and time formats.

Body:
I am using moment.js for formatting dates:

const dateFormat = 'DD/MM/YYYY';
setValue('startDate', moment(booking.startDate, dateFormat));

I want the date to be 01-06-2020 instead of 2020-06-01T07:33:04.392Z. Any idea, because I don't know how to do this?

Body:
Here's an example for how to format an instance of moment.js as DD-MM-YYYY:

const dateString = moment("2020-06-01T12:00:00").format("DD-MM-YYYY");
console.log({ dateString });

This gives the following in the console:

{ dateString: '01-06-2020' }

It'd be good to read more about moment's format function and the standard W3C date and time formats.


问:
electron webview get scrambled in a rare case
I got a bug report in my electron app. It looks like below~
We can't find a way to reproduce this.
I believe it's some kind of visual memory corruption, but I don't know how it happens...

答:
It turns out to be a bug in Apple's latest 16' MacBook pro. Likely to happen when the system is recovered from sleep mode.

It's also happening in chrome/chromium.

Here is the issue track link:
https://bugs.chromium.org/p/chromium/issues/detail?id=1068170


问:
Batch file error: "xcopy is not recognized as an internal or external command..."
I'm programming a batch file and after a long amount of code, I have:

```<code>:d1copy
xcopy /Y "C:\Users\Joseph\Desktop\JOKO_Sync\*.*" "F:\JOKO_Sync\*.*" /s /e /V /D
pause
</code>```

When I execute this, I get the error

xcopy is not recognized as an internal or external command, operable program or batch file.

Yet I copy and paste this same code into another batch file, and it works perfectly.

Any ideas?

答:
Rather than setting the PATH variable (which could then still break if you moved the script to another machine), you could simply specify the full path to xcopy:

```<code>%systemroot%\System32\xcopy ...
</code>```

so in your case:

```<code>%systemroot%\System32\xcopy /Y "C:\Users\Joseph\Desktop\JOKO_Sync\*.*" "F:\JOKO_Sync\*.*" /s /e /V /D
</code>```

Body:
I'm programming a batch file and after a long amount of code, I have:

:d1copy
xcopy /Y "C:\Users\Joseph\Desktop\JOKO_Sync\*.*" "F:\JOKO_Sync\*.*" /s /e /V /D
pause

When I execute this, I get the error

xcopy is not recognized as an internal or external command, operable program or batch file.

Yet I copy and paste this same code into another batch file, and it works perfectly.

Any ideas?

Body:
Rather than setting the PATH variable (which could then still break if you moved the script to another machine), you could simply specify the full path to xcopy:

%systemroot%\System32\xcopy ...

so in your case:

%systemroot%\System32\xcopy /Y "C:\Users\Joseph\Desktop\JOKO_Sync\*.*" "F:\JOKO_Sync\*.*" /s /e /V /D


问:
Cannot construct instance of `java.time.ZonedDateTime` (no Creators, like default construct, exist) using RabbitMQ
I have three spring applications that communicate with each other using spring amqp (rabbitmq): invoice-service, tracking-service and government-service. I already succeeded to send a message from invoice-service to tracking-service.

Below is the Receiver class from tracking-service. So I receive a message from invoice-service and after doing some things in the Handler class I send a TrackingMessage to government-service.

```<code>@Component
public class Receiver {

    @Autowired
    private Handler handler;

    @Autowired
    private AmqpTemplate rabbitTemplate;

    static final String exchange = "exchange-invoice";
    static final String routingKey = "key-government";

    @RabbitListener(queues = "queue-tracking")
    public void receive(CustomMessage message) {
        List<TrackingMessage> trackingMessages = handler.getCoordinatesByDates(message);
        rabbitTemplate.convertAndSend(exchange,routingKey, trackingMessages.get(0));
    }
}
</code>```

Below is the MessageBrokerConfiguration class. I'm using Jackson2Json to convert the a Java object to JSON.

```<code>@Configuration
public class MessageBrokerConfiguration {

    static final String queueName = "queue-tracking";
    static final String exchange =  "exchange-invoice";
    static final String routingKey = "key-tracking";

    @Bean
    public Queue queue() {
        return new Queue(queueName);
    }

    @Bean
    public DirectExchange exchange() {
        return new DirectExchange(exchange);
    }

    @Bean
    Binding binding(Queue queue, DirectExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(routingKey);
    }

    @Bean
    Handler handler(){ return new Handler();}

    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public AmqpTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(jsonMessageConverter());
        return rabbitTemplate;
    }
}
</code>```

Below is the TrackingMessage class from tracking-service.

```<code>@Entity
public class TrackingMessage {

    @Id
    @GeneratedValue
    @JsonProperty("id")
    private int id;
    @JsonProperty("carId")
    private int carId;
    @JsonProperty("longitude")
    private double longitude;
    @JsonProperty("latitude")
    private double latitude;
    @JsonProperty("recordedTime")
    private ZonedDateTime recordedTime;

    public TrackingMessage() {
    }

    public TrackingMessage(int carId, double latitude, double longitude) {
        this.carId = carId;
        this.latitude = latitude;
        this.longitude = longitude;
        this.recordedTime = getTimeNow();
    }

    public TrackingMessage(@JsonProperty("id") int carId, @JsonProperty("carId") double latitude, @JsonProperty("longitude") double longitude,
                           @JsonProperty("recordedTime") ZonedDateTime recordedTime) {
        this.carId = carId;
        this.latitude = latitude;
        this.longitude = longitude;
        this.recordedTime = recordedTime;
    }

    public int getCarId() {
        return carId;
    }

    public void setCarId(int carId) {
        this.carId = carId;
    }

    public double getLatitude() {
        return latitude;
    }

    public void setLatitude(double latitude) {
        this.latitude = latitude;
    }

    public double getLongitude() {
        return longitude;
    }

    public void setLongitude(double longitude) {
        this.longitude = longitude;
    }

    public ZonedDateTime getRecordedTime() {
        return recordedTime;
    }

    public void setRecordedTime(ZonedDateTime recordedTime) {
        this.recordedTime = recordedTime;
    }

    private ZonedDateTime getTimeNow() {
        return ZonedDateTime.now(ZoneOffset.UTC);
    }
}
</code>```

Below is the Receiver class from government-service. So when I receive the TrackingMessage in this receiver class I get the following error:

Cannot construct instance of java.time.ZonedDateTime (no Creators, like default construct, exist)

My MessageBrokerConfiguration and TrackingMessage classes from government-service looks the same as in the tracking-service. Somebody ideas?

```<code>@Component
public class Receiver {
    @RabbitListener(queues = "queue-government")
    public void receive(TrackingMessage message) {
        System.out.println(message);
    }
}
</code>```

答:
Just needed to configure an ObjectMapper for the Jackson2JsonMessageConverter and register modules including JavaTimeModule. Below is the code that solved my problem.</p>

```<code>    @Bean
    public MessageConverter jsonMessageConverter(ObjectMapper mapper) {
        return new Jackson2JsonMessageConverter(mapper);
    }

    @Bean
    public AmqpTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);

        ObjectMapper mapper =
                new ObjectMapper()
                        .registerModule(new ParameterNamesModule())
                        .registerModule(new Jdk8Module())
                        .registerModule(new JavaTimeModule());
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        mapper.setDateFormat(new StdDateFormat());

        rabbitTemplate.setMessageConverter(jsonMessageConverter(mapper));
        return rabbitTemplate;
    }
</code>```

Body:
I have three spring applications that communicate with each other using spring amqp (rabbitmq): invoice-service, tracking-service and government-service. I already succeeded to send a message from invoice-service to tracking-service.

Below is the Receiver class from tracking-service. So I receive a message from invoice-service and after doing some things in the Handler class I send a TrackingMessage to government-service.

@Component
public class Receiver {

    @Autowired
    private Handler handler;

    @Autowired
    private AmqpTemplate rabbitTemplate;

    static final String exchange = "exchange-invoice";
    static final String routingKey = "key-government";

    @RabbitListener(queues = "queue-tracking")
    public void receive(CustomMessage message) {
        List<TrackingMessage> trackingMessages = handler.getCoordinatesByDates(message);
        rabbitTemplate.convertAndSend(exchange,routingKey, trackingMessages.get(0));
    }
}

Below is the MessageBrokerConfiguration class. I'm using Jackson2Json to convert the a Java object to JSON.

@Configuration
public class MessageBrokerConfiguration {

    static final String queueName = "queue-tracking";
    static final String exchange =  "exchange-invoice";
    static final String routingKey = "key-tracking";

    @Bean
    public Queue queue() {
        return new Queue(queueName);
    }

    @Bean
    public DirectExchange exchange() {
        return new DirectExchange(exchange);
    }

    @Bean
    Binding binding(Queue queue, DirectExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(routingKey);
    }

    @Bean
    Handler handler(){ return new Handler();}

    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public AmqpTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(jsonMessageConverter());
        return rabbitTemplate;
    }
}

Below is the TrackingMessage class from tracking-service.

@Entity
public class TrackingMessage {

    @Id
    @GeneratedValue
    @JsonProperty("id")
    private int id;
    @JsonProperty("carId")
    private int carId;
    @JsonProperty("longitude")
    private double longitude;
    @JsonProperty("latitude")
    private double latitude;
    @JsonProperty("recordedTime")
    private ZonedDateTime recordedTime;

    public TrackingMessage() {
    }

    public TrackingMessage(int carId, double latitude, double longitude) {
        this.carId = carId;
        this.latitude = latitude;
        this.longitude = longitude;
        this.recordedTime = getTimeNow();
    }

    public TrackingMessage(@JsonProperty("id") int carId, @JsonProperty("carId") double latitude, @JsonProperty("longitude") double longitude,
                           @JsonProperty("recordedTime") ZonedDateTime recordedTime) {
        this.carId = carId;
        this.latitude = latitude;
        this.longitude = longitude;
        this.recordedTime = recordedTime;
    }

    public int getCarId() {
        return carId;
    }

    public void setCarId(int carId) {
        this.carId = carId;
    }

    public double getLatitude() {
        return latitude;
    }

    public void setLatitude(double latitude) {
        this.latitude = latitude;
    }

    public double getLongitude() {
        return longitude;
    }

    public void setLongitude(double longitude) {
        this.longitude = longitude;
    }

    public ZonedDateTime getRecordedTime() {
        return recordedTime;
    }

    public void setRecordedTime(ZonedDateTime recordedTime) {
        this.recordedTime = recordedTime;
    }

    private ZonedDateTime getTimeNow() {
        return ZonedDateTime.now(ZoneOffset.UTC);
    }
}

Below is the Receiver class from government-service. So when I receive the TrackingMessage in this receiver class I get the following error:

Cannot construct instance of java.time.ZonedDateTime (no Creators, like default construct, exist)

My MessageBrokerConfiguration and TrackingMessage classes from government-service looks the same as in the tracking-service. Somebody ideas?

@Component
public class Receiver {
    @RabbitListener(queues = "queue-government")
    public void receive(TrackingMessage message) {
        System.out.println(message);
    }
}

Body:
Just needed to configure an ObjectMapper for the Jackson2JsonMessageConverter and register modules including JavaTimeModule. Below is the code that solved my problem.

    @Bean
    public MessageConverter jsonMessageConverter(ObjectMapper mapper) {
        return new Jackson2JsonMessageConverter(mapper);
    }

    @Bean
    public AmqpTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);

        ObjectMapper mapper =
                new ObjectMapper()
                        .registerModule(new ParameterNamesModule())
                        .registerModule(new Jdk8Module())
                        .registerModule(new JavaTimeModule());
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        mapper.setDateFormat(new StdDateFormat());

        rabbitTemplate.setMessageConverter(jsonMessageConverter(mapper));
        return rabbitTemplate;
    }


问:
how to call restTemplate.postForEntity when entity is having different field name than expected
I am having a rest API which accept entity with field names as id,title. But when calling I am having different fields with same value as id,description.

How to modify the call so that I can make the request.

In the below code, Employee class is having two fields id, desc which are different from id,title.

```<code>public ResponseEntity<Employee> postForEntity(Employee newEmployee) {
  MultiValueMap<String, String> headers = new HttpHeaders();
  headers.add("User-Agent", "EmployeeRestClient demo class");
  headers.add("Accept-Language", "en-US");
  HttpEntity<Employee> entity = new HttpEntity<>(newEmployee, headers);
  return restTemplate.postForEntity(REQUEST_URI, entity, Employee.class);
}

</code>```

答:
First make sure that if the class Employee is correct on this place. If correct, then map Java properties to JSON as follows:

```<code>public class Employee {
    ... id; // name remains unchanged

    @JsonProperty("title")
    ... desc;

}
</code>```

If you cannot modify Employee class, create another one with needed property names and copy instance of Employee to your instance of your class, and then user this instance in the restTemplate.

Body:
I am having a rest API which accept entity with field names as id,title. But when calling I am having different fields with same value as id,description.

How to modify the call so that I can make the request.

In the below code, Employee class is having two fields id, desc which are different from id,title.

public ResponseEntity<Employee> postForEntity(Employee newEmployee) {
  MultiValueMap<String, String> headers = new HttpHeaders();
  headers.add("User-Agent", "EmployeeRestClient demo class");
  headers.add("Accept-Language", "en-US");
  HttpEntity<Employee> entity = new HttpEntity<>(newEmployee, headers);
  return restTemplate.postForEntity(REQUEST_URI, entity, Employee.class);
}

Body:
First make sure that if the class Employee is correct on this place. If correct, then map Java properties to JSON as follows:

public class Employee {
    ... id; // name remains unchanged

    @JsonProperty("title")
    ... desc;

}

If you cannot modify Employee class, create another one with needed property names and copy instance of Employee to your instance of your class, and then user this instance in the restTemplate.


问:
What is the way to make the tool-tip box visible as you scroll through the overflow area?
As you can see, the tooltip is covered and it's not showing properly.

How can I make the tooltip box look clear and scroll when the contents in the fixed area overflow and make the scrolling variable and when the tool chip box made with "Positive:Absolute" is incorrect? The layout I want is shown below.

* {
  margin: 0;
  padding: 0;
}

.header {
  width: 100%;
  height: 50px;
  background-color: lavender;
}

.test1 {
  width: 300px;
  height: calc(100vh - 50px);
  min-height: calc(100vh - 50px);
  background-color: pink;
  overflow-y: scroll;
  position: relative;
}

.contents1,
.contents3 {
  width: 230px;
  margin: auto;
  position: relative;
}

.contents2,
.contents4 {
  width: 144px;
  position: relative;
}

.tooltip {
  width: 20px;
  height: 20px;
  position: absolute;
  bottom: 3px;
  right: 3px;
  background-color: red;
}

.tooltip-contents {
  width: 300px;
  background-color: black;
  position: absolute;
  left: calc(100% + 20px);
  top: -5px;
  color: #fff;
  word-break: break-all
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="containter">
  <div class="header"></div>
  <div>
    <div class="test1">
      <div class="contents1">
        <p>contents header</p>
        <div class="contents2">
          <img src="https://via.placeholder.com/150" />
          <div class="tooltip">
            <span class="tooltip-icon"></span>
            <div class="tooltip-contents">
              abcdefgdfsafdasdfsadfsadfasdfsadf
            </div>
            <div>
              <div></div>
            </div>
            <div class="test2"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div></code>```

jQuery is not available. Only minimal JavaScript is possible.

this layout

答:
It is important that data-container='body'so that the tooltip can be displayed outside the scrollbar.

.scroll-wrap {
  width: 150px;
  height: 150px;
  overflow: auto;
  box-shadow: 0 0 3px orange;
}
.scroll-wrap button {
  margin-top:30px;
  margin-bottom: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
 <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
 <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>

  <div class="scroll-wrap">
    <button type="button" class="btn btn-default" data-container="body" data-toggle="tooltip" data-placement="right" data-html="true" title="<div style='color: red'>div demo</div>">Right Tooltip
  </button>
    <button type="button" class="btn btn-default" data-container="body" data-toggle="tooltip" data-placement="right" title="Right Tooltip">Right Tooltip
  </button>
    <button type="button" class="btn btn-default" data-container="body" data-toggle="tooltip" data-placement="right" title="Right Tooltip">Right Tooltip
  </button>
  </div>

<script>
$(function () {
  $("[data-toggle='tooltip']").tooltip();
  });
</script></code>```

This supports HTML fragments

Body:
As you can see, the tooltip is covered and it's not showing properly.

How can I make the tooltip box look clear and scroll when the contents in the fixed area overflow and make the scrolling variable and when the tool chip box made with "Positive:Absolute" is incorrect? The layout I want is shown below.

* {
  margin: 0;
  padding: 0;
}

.header {
  width: 100%;
  height: 50px;
  background-color: lavender;
}

.test1 {
  width: 300px;
  height: calc(100vh - 50px);
  min-height: calc(100vh - 50px);
  background-color: pink;
  overflow-y: scroll;
  position: relative;
}

.contents1,
.contents3 {
  width: 230px;
  margin: auto;
  position: relative;
}

.contents2,
.contents4 {
  width: 144px;
  position: relative;
}

.tooltip {
  width: 20px;
  height: 20px;
  position: absolute;
  bottom: 3px;
  right: 3px;
  background-color: red;
}

.tooltip-contents {
  width: 300px;
  background-color: black;
  position: absolute;
  left: calc(100% + 20px);
  top: -5px;
  color: #fff;
  word-break: break-all
}

contents header

              abcdefgdfsafdasdfsadfsadfasdfsadf

jQuery is not available. Only minimal JavaScript is possible.

this layout

Body:
It is important that data-container='body'so that the tooltip can be displayed outside the scrollbar.

.scroll-wrap {
  width: 150px;
  height: 150px;
  overflow: auto;
  box-shadow: 0 0 3px orange;
}
.scroll-wrap button {
  margin-top:30px;
  margin-bottom: 20px;
}

<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
 <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
 <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>

  <div class="scroll-wrap">
    <button type="button" class="btn btn-default" data-container="body" data-toggle="tooltip" data-placement="right" data-html="true" title="<div style='color: red'>div demo</div>">Right Tooltip
  </button>
    <button type="button" class="btn btn-default" data-container="body" data-toggle="tooltip" data-placement="right" title="Right Tooltip">Right Tooltip
  </button>
    <button type="button" class="btn btn-default" data-container="body" data-toggle="tooltip" data-placement="right" title="Right Tooltip">Right Tooltip
  </button>
  </div>

<script>
$(function () {
  $("[data-toggle='tooltip']").tooltip();
  });
</script>

This supports HTML fragments


问:
Beautiful Soup how to decode html json data in
```

Can anyone identify this encoding format? How can I decode it with Python / Beautiful Soup?

答:
This content seems to be custom encoded. You can try simple str.replace:

```<code>txt = r'''<script id="ng-agritown-state" type="application/json">

{&q;G.{{api_endpoint}}/api/v12/pages?parameters=newsId%3D343436565656&a;path=news-article&q;:{&q;body&q;:{&q;id&q;:&q;8&q;,&q;layout&q;:&q;onecol&q;,&q;info&q;:{&q;title&q;:&q;News article&q;

    ...

    &q;&g;&l;span class=\&q;z\&q;&g;Record harvest 2020&l;/span&g;&l;/p&g;\n&l;p class=\&q;a\&q;&g;&l;span class=\&q;z\&q;&g;We are pleased to announce a record harvest in this current

    ...

    &q;isDataComponentAndIsAvailable&q;:true,&q;status&q;:{&q;refreshedTime&q;:1590993288947,&q;childComponents&q;:[],&q;params&q;:{&q;updates&q;:null,&q;cloneFrom&q;:null,&q;encoder&q;:{},&q;map&q;:null}}}]}}

</script>'''

from bs4 import BeautifulSoup

soup = BeautifulSoup(txt, 'html.parser')

print( soup.script.contents[0].replace('&l;', '<').replace('&g;', '>').replace('&q;', '"') )
</code>```

Prints:

```<code>{"G.{{api_endpoint}}/api/v12/pages?parameters=newsId%3D343436565656&a;path=news-article":{"body":{"id":"8","layout":"onecol","info":{"title":"News article"

    ...

    "><span class=\"z\">Record harvest 2020</span></p>\n<p class=\"a\"><span class=\"z\">We are pleased to announce a record harvest in this current

    ...

    "isDataComponentAndIsAvailable":true,"status":{"refreshedTime":1590993288947,"childComponents":[],"params":{"updates":null,"cloneFrom":null,"encoder":{},"map":null}}}]}}
</code>```

Then json/re module to decode the information.

Title: Beautiful Soup how to decode html json data in <script> object

Body:
I collect text from a website which publishes short news updates. Recently the site's front-end was upgraded and now uses Angular. The historical documents load within a  element within a new Angular "news" page.

The data within this script element is html stored as JSON. It is encoded in a format that I am unfamiliar with. I have not been able to decode it. However, a Chrome Browser interprets the elements within the  element.

Extracts from the  element storing each old document is shown below:

Can anyone identify this encoding format? How can I decode it with Python / Beautiful Soup?

Body:
This content seems to be custom encoded. You can try simple str.replace:

txt = r'''<script id="ng-agritown-state" type="application/json">

{&q;G.{{api_endpoint}}/api/v12/pages?parameters=newsId%3D343436565656&a;path=news-article&q;:{&q;body&q;:{&q;id&q;:&q;8&q;,&q;layout&q;:&q;onecol&q;,&q;info&q;:{&q;title&q;:&q;News article&q;

    ...

    &q;&g;&l;span class=\&q;z\&q;&g;Record harvest 2020&l;/span&g;&l;/p&g;\n&l;p class=\&q;a\&q;&g;&l;span class=\&q;z\&q;&g;We are pleased to announce a record harvest in this current

    ...

    &q;isDataComponentAndIsAvailable&q;:true,&q;status&q;:{&q;refreshedTime&q;:1590993288947,&q;childComponents&q;:[],&q;params&q;:{&q;updates&q;:null,&q;cloneFrom&q;:null,&q;encoder&q;:{},&q;map&q;:null}}}]}}

</script>'''

from bs4 import BeautifulSoup

soup = BeautifulSoup(txt, 'html.parser')

print( soup.script.contents[0].replace('&l;', '<').replace('&g;', '>').replace('&q;', '"') )

Prints:

{"G.{{api_endpoint}}/api/v12/pages?parameters=newsId%3D343436565656&a;path=news-article":{"body":{"id":"8","layout":"onecol","info":{"title":"News article"

    ...

    "><span class=\"z\">Record harvest 2020</span></p>\n<p class=\"a\"><span class=\"z\">We are pleased to announce a record harvest in this current

    ...

    "isDataComponentAndIsAvailable":true,"status":{"refreshedTime":1590993288947,"childComponents":[],"params":{"updates":null,"cloneFrom":null,"encoder":{},"map":null}}}]}}

Then json/re module to decode the information.


问:
Matplotlib DataFrame boxplot with given max,min and quaritles
I want to plot a box plot with my DataFrame:

```<code>     A     B     C
max  10    11    14
min  3     4     10
q1   5     6     12
q3   9     7     13
</code>```

how can I plot a box plot with these fixed values?

答:
You can use the Axes.bxp method in matplotlib, based on this helpful answer. The input is a list of dictionaries containing the relevant values, but the median is a required key in these dictionaries. Since the data you provided does not include medians, I have made up medians in the code below (but you will need to calculate them from your actual data).

```<code>import matplotlib.pyplot as plt
import pandas as pd

# reproducing your data
df = pd.DataFrame({'A':[10,3,5,9],'B':[11,4,6,7],'C':[14,10,12,13]})

# add a row for median, you need median values!
sample_medians = {'A':7, 'B':6.5, 'C':12.5}
df = df.append(sample_medians, ignore_index=True)
df.index = ['max','min','q1','q3','med']
</code>```

Here is the modified df with medians included:

```<code>>>> df
        A     B     C
max  10.0  11.0  14.0
min   3.0   4.0  10.0
q1    5.0   6.0  12.0
q3    9.0   7.0  13.0
med   7.0   6.5  12.5
</code>```

Now we transform the df into a list of dictionaries:

```<code>labels = list(df.columns)

# create dictionaries for each column as items of a list
bxp_stats = df.apply(lambda x: {'med':x.med, 'q1':x.q1, 'q3':x.q3, 'whislo':x['min'], 'whishi':x['max']}, axis=0).tolist()

# add the column names as labels to each dictionary entry
for index, item in enumerate(bxp_stats):
    item.update({'label':labels[index]})

_, ax = plt.subplots()
ax.bxp(bxp_stats, showfliers=False);
plt.show()
</code>```

Unfortunately the median line is a required parameter so it must be specified for every box. Therefore we just make it as thin as possible to be virtually unseeable.

If you want each box to be drawn with different specifications, they will have to be in different subplots. I understand if this looks kind of ugly, so you can play around with the spacing between subplots or consider removing some of the y-axes.

```<code>fig, axes = plt.subplots(nrows=1, ncols=3, sharey=True)

# specify list of background colors, median line colors same as background with as thin of a width as possible
colors = ['LightCoral', '#FEF1B5', '#EEAEEE']
medianprops = [dict(linewidth = 0.1, color='LightCoral'), dict(linewidth = 0.1, color='#FEF1B5'), dict(linewidth = 0.1, color='#EEAEEE')]
# create a list of boxplots of length 3
bplots = [axes[i].bxp([bxp_stats[i]], medianprops=medianprops[i], patch_artist=True, showfliers=False) for i in range(len(df.columns))]
# set each boxplot a different color
for i, bplot in enumerate(bplots):
    for patch in bplot['boxes']:
        patch.set_facecolor(colors[i])
plt.show()
</code>```

Body:
I want to plot a box plot with my DataFrame:

     A     B     C
max  10    11    14
min  3     4     10
q1   5     6     12
q3   9     7     13

how can I plot a box plot with these fixed values?

Body:
You can use the Axes.bxp method in matplotlib, based on this helpful answer. The input is a list of dictionaries containing the relevant values, but the median is a required key in these dictionaries. Since the data you provided does not include medians, I have made up medians in the code below (but you will need to calculate them from your actual data).

import matplotlib.pyplot as plt
import pandas as pd

# reproducing your data
df = pd.DataFrame({'A':[10,3,5,9],'B':[11,4,6,7],'C':[14,10,12,13]})

# add a row for median, you need median values!
sample_medians = {'A':7, 'B':6.5, 'C':12.5}
df = df.append(sample_medians, ignore_index=True)
df.index = ['max','min','q1','q3','med']

Here is the modified df with medians included:

>>> df
        A     B     C
max  10.0  11.0  14.0
min   3.0   4.0  10.0
q1    5.0   6.0  12.0
q3    9.0   7.0  13.0
med   7.0   6.5  12.5

Now we transform the df into a list of dictionaries:

labels = list(df.columns)

# create dictionaries for each column as items of a list
bxp_stats = df.apply(lambda x: {'med':x.med, 'q1':x.q1, 'q3':x.q3, 'whislo':x['min'], 'whishi':x['max']}, axis=0).tolist()

# add the column names as labels to each dictionary entry
for index, item in enumerate(bxp_stats):
    item.update({'label':labels[index]})

_, ax = plt.subplots()
ax.bxp(bxp_stats, showfliers=False);
plt.show()

Unfortunately the median line is a required parameter so it must be specified for every box. Therefore we just make it as thin as possible to be virtually unseeable.

If you want each box to be drawn with different specifications, they will have to be in different subplots. I understand if this looks kind of ugly, so you can play around with the spacing between subplots or consider removing some of the y-axes.

fig, axes = plt.subplots(nrows=1, ncols=3, sharey=True)

# specify list of background colors, median line colors same as background with as thin of a width as possible
colors = ['LightCoral', '#FEF1B5', '#EEAEEE']
medianprops = [dict(linewidth = 0.1, color='LightCoral'), dict(linewidth = 0.1, color='#FEF1B5'), dict(linewidth = 0.1, color='#EEAEEE')]
# create a list of boxplots of length 3
bplots = [axes[i].bxp([bxp_stats[i]], medianprops=medianprops[i], patch_artist=True, showfliers=False) for i in range(len(df.columns))]
# set each boxplot a different color
for i, bplot in enumerate(bplots):
    for patch in bplot['boxes']:
        patch.set_facecolor(colors[i])
plt.show()


问:
synchronising / maintaining ant and eclipse classpaths
I'd be interested to find out about any automated processes that people have for ensuring that the project classpaths for the ant and eclipse configurations are in synch. In my case, I want the classpath defined in the ant build file to be the master configuration, since its used for our production builds. As part of the build i'd like to add an ant target that will verify that the eclipse classpath is up to date, or at least indicate differences between the two classpaths.

I'm aware of ant4eclipse but its focus is in the opposite direction, ensuring that the eclipse classpath is master and that the ant build reuses the eclipse path. I like the idea behind AntAndEclipse but am wondering are their ant other tools in this space that i'm not aware of.

答:
You solution at a previous company was to have ant invoke Eclipse to do the compiles as described here:

http://www.eclipse.org/articles/Article-PDE-Automation/automation.html

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Jeffrey Fredrick


问:
Is there any way to add namespaces to all html tags using ASP?
Is there any way to add namespace xmlns="http://www.w3.org/1999/xhtml" to all html tags either using ASP function / RegExp / javascript? (this is something like adding a attribute to the html tags)

For Example:

Below is the body of textarea:

```<code><p>Welcome to the StackOverFlow site.</p>
<p xmlns="http://www.w3.org/1999/xhtml">Please <a href="http://stackoverflow.com">click here</a> for more info.</p>
</code>```

The body contains two html tags,
 & .

Here one
 tag already has namespace xmlns="http://www.w3.org/1999/xhtml"

Now I need to add namespace to other tags.

I tried a lot to resolve this on ASP page but no luck.

Please help me on this.

答:
Based on Alan inputs, I have build my solution on ASP</p>

```<code>Function ReplaceAllByExpression(str)
    Dim objRegExp, sHtml
    sHtml = str
    Set objRegExp = New RegExp

    objRegExp.IgnoreCase = True
    objRegExp.Global = True
    objRegExp.MultiLine = True

    objRegExp.Pattern = "(<(?!tr|td|thead|tbody)\w+)((?:\s+(?!xmlns\b)\w+\s*=\s*(?:""[^""]*""|'[^']*'|[^\s>]+))*\s*\/?>)"

    sHtml = objRegExp.Replace(sHtml, "$1 xmlns=""http://www.w3.org/1999/xhtml""$2")

    ReplaceAllByExpression = sHtml

End Function
</code>```

Body:
Is there any way to add namespace xmlns="http://www.w3.org/1999/xhtml" to all html tags either using ASP function / RegExp / javascript? (this is something like adding a attribute to the html tags)

For Example:

Below is the body of textarea:

Welcome to the StackOverFlow site.

Please click here for more info.

The body contains two html tags,
 & .

Here one
 tag already has namespace xmlns="http://www.w3.org/1999/xhtml"

Now I need to add namespace to other tags.

I tried a lot to resolve this on ASP page but no luck.

Please help me on this.

Body:
Based on Alan inputs, I have build my solution on ASP

Function ReplaceAllByExpression(str)
    Dim objRegExp, sHtml
    sHtml = str
    Set objRegExp = New RegExp

    objRegExp.IgnoreCase = True
    objRegExp.Global = True
    objRegExp.MultiLine = True

    objRegExp.Pattern = "(<(?!tr|td|thead|tbody)\w+)((?:\s+(?!xmlns\b)\w+\s*=\s*(?:""[^""]*""|'[^']*'|[^\s>]+))*\s*\/?>)"

    sHtml = objRegExp.Replace(sHtml, "$1 xmlns=""http://www.w3.org/1999/xhtml""$2")

    ReplaceAllByExpression = sHtml

End Function


问:
Where should i start to live stream hololens to python server with webrtc?
Recently i have been working on a project to stream Hololens video and audio to python server.
That is sending hololens video frame to python server and use python to do image processing.

On the Hololens i use unity as development platform, and i want to use webrtc (base on this repo Mixed-reality webrtc).
I think i just know the concept of how webrtc working. But to the code, i just don't have idea where to start implementing this technique.
Hope anyone can give me come hint.

答:
I am not familiar with Python, but your Python server as a video receiver it should follow WebRTC specification. I believe there are reliable Python libraries related to WebRTC in Github.
For HoloLens side, since you mentioned that you are using the Unity for development, This step-by-step guidance shows you how to implement Mixed-Reality WebRtc in Unity.

In short, we should add a PeerConnection component to a new GameObject in your scene. Then add the NodeDssSignaler component and configure it to connect to a Node-DSS server. Next, create a new game object and add a WebcamSource component, this component can generate video frames from a local video capture device (webcam), we need to config it. Finally, assign the Video Sender property of the PeerConnection component to the WebcanSource component created previously.


问:
An efficient way to Base64 encode a byte array?
I have a byte[] and I'm looking for the most efficient way to base64 encode it.

The problem is that the built in .Net method Convert.FromBase64CharArray requires a char[] as an input, and converting my byte[] to a char[] just to convert it again to a base64 encoded array seems pretty stupid.

Is there any more direct way to do it?

[[EDIT:]] I'll expaling what I want to acheive better - I have a byte[] and I need to  return a new base64 encoded byte[]

答:
To retrieve your image from byte to base64 string....

Model property:

```<code>    public byte[] NomineePhoto { get; set; }

    public string NomineePhoneInBase64Str
    {
        get {
            if (NomineePhoto == null)
                return "";

            return $"data:image/png;base64,{Convert.ToBase64String(NomineePhoto)}";
        }
    }
</code>```

IN view:

```<code>   <img style="height:50px;width:50px" src="@item.NomineePhoneInBase64Str" />
</code>```

Body:
To retrieve your image from byte to base64 string....

Model property:

    public byte[] NomineePhoto { get; set; }

    public string NomineePhoneInBase64Str
    {
        get {
            if (NomineePhoto == null)
                return "";

            return $"data:image/png;base64,{Convert.ToBase64String(NomineePhoto)}";
        }
    }

IN view:

   <img style="height:50px;width:50px" src="@item.NomineePhoneInBase64Str" />


问:
When I manipulate the dom, v-for no longer stays in sync with a reactive array
It's very confusing - and I would even think there's a bug here.

https://jsbin.com/qadunor/edit?html,js,output

```<code>updateList(containerDom) {
  return () => {
    Array.from(containerDom.querySelectorAll(".list-group-item")).forEach((domItem, idx) => {
      let listItemIndex = this.list.findIndex(listItem => listItem.name === domItem.innerText)
      let listItem = this.list[listItemIndex]
      listItem.pos = idx
      this.list.splice(listItemIndex, 1, listItem)
    })
  }
}
</code>```

If you drag the first list-item ("animal") to the last list-item ("armband") to essentially do a swap (using Sortable.js), you'll see that the list is reactive - you can see it in the output - it updated its position, but the "v-for" loop didn't react properly.

It reacts in some way - but not correctly as you'll see (it incorrectly drops armband into the second position). Now, if I were to just use Sortable.js straight up the swap works fine (ie if I don't handle the onUpdate event - just comment it out). I know I could use VUE.draggable (or whatever it is called, where it maintains an internal list, but for a variety of more complicated reasons I can't use that library). My use-case where I want to use the above technique is irrelevant here - I just want to know why this very particular way fails for "v-for".

I know it has something to do with the fact that Sortable.js does it's own DOM manipulation, but I would expect that once the list array is mutated, that the v-for loop should react appropriately - but it's as if gets confused by what is currently in the DOM.

答:
I think the reason for this not working is quite simply because I manipulate the dom directly (via Sortable.js), but when it comes to updating the virtual dom that vue manages, it doesn't know about the dom manipulations that have happened, and doesn't properly update the virtual dom (and thereby the real dom) when the reactive list changes.

It could be seen as a bug on vue's side - I expect the "v-for" loop to reflect the reactive list. But it could also be seen as a limitation. It's a tradeoff - vuejs can't inspect the real dom as well as the virtual dom for performance reasons?

So to deal with this I'd probably need

to let the drag and drop happen and let the dom be manipulated directly (via Sortable.js),

then inspect the new order in the dom and make notes on the new order,

then reverse the dom manipulations,

and then use the notes I took and update the reactive list,

which will then in turn update the virtual dom.

So the step that is missing in my sample code, is the code that reverses the dom manipulations.

Anyway - that's just my understanding of why the code above doesn't work.

Body:
It's very confusing - and I would even think there's a bug here.

https://jsbin.com/qadunor/edit?html,js,output

updateList(containerDom) {
  return () => {
    Array.from(containerDom.querySelectorAll(".list-group-item")).forEach((domItem, idx) => {
      let listItemIndex = this.list.findIndex(listItem => listItem.name === domItem.innerText)
      let listItem = this.list[listItemIndex]
      listItem.pos = idx
      this.list.splice(listItemIndex, 1, listItem)
    })
  }
}

If you drag the first list-item ("animal") to the last list-item ("armband") to essentially do a swap (using Sortable.js), you'll see that the list is reactive - you can see it in the output - it updated its position, but the "v-for" loop didn't react properly.

It reacts in some way - but not correctly as you'll see (it incorrectly drops armband into the second position). Now, if I were to just use Sortable.js straight up the swap works fine (ie if I don't handle the onUpdate event - just comment it out). I know I could use VUE.draggable (or whatever it is called, where it maintains an internal list, but for a variety of more complicated reasons I can't use that library). My use-case where I want to use the above technique is irrelevant here - I just want to know why this very particular way fails for "v-for".

I know it has something to do with the fact that Sortable.js does it's own DOM manipulation, but I would expect that once the list array is mutated, that the v-for loop should react appropriately - but it's as if gets confused by what is currently in the DOM.


问:
How to use an outer query variable in a nested sub query using update
I am using an update query in which I use an outer variable in a nested sub query, but I find an error:

SQL Error: ORA-00904: "FS"."GR_NUMBER": invalid identifier

```<code>update table fs set fs.branch_id=
(select branch_id
from
    (select  branch_id,row_number() over(PARTITION by gr_number order by updated_ts desc) as Sno
from admission_log
where gr_number=fs.gr_number )
where sno=1) ;
</code>```

答:
The issue with your query is that you're trying to access the fs.gr_number column in a subquery that's two levels down. You can only access the top level column in a subquery one level down.

Your statement should be:

```<code>UPDATE fs
SET    fs.branch_id = (SELECT branch_id
                       FROM   (SELECT branch_id,
                                      gr_number,
                                      row_number() OVER (PARTITION BY gr_number ORDER BY updated_ts DESC) AS sno
                               FROM   admission_log) x
                       WHERE  x.gr_number = fs.gr_number
                       AND    sno = 1);
</code>```

That moves the correlation to one level down. Note how I've also aliased the nested subquery.

The performance shouldn't be terrible, since the x.gr_number = fs.gr_number predicate involves the same column in the subquery which the analytic function is being partitioned on. That should allow Oracle to filter the subquery appropriately.

ETA: you could also use a MERGE statement instead:

```<code>MERGE INTO fs tgt
  USING (SELECT branch_id,
                row_number() OVER (PARTITION BY gr_number ORDER BY updated_ts DESC) AS sno
         FROM   admission_log) src
    ON (tgt.gr_number = src.gr_number AND src.sno = 1)
WHEN MATCHED THEN
  UPDATE tgt.branch_id = src.branch_id;
</code>```

Body:
I am using an update query in which I use an outer variable in a nested sub query, but I find an error:

SQL Error: ORA-00904: "FS"."GR_NUMBER": invalid identifier

update table fs set fs.branch_id=
(select branch_id
from
    (select  branch_id,row_number() over(PARTITION by gr_number order by updated_ts desc) as Sno
from admission_log
where gr_number=fs.gr_number )
where sno=1) ;

Body:
The issue with your query is that you're trying to access the fs.gr_number column in a subquery that's two levels down. You can only access the top level column in a subquery one level down.

Your statement should be:

UPDATE fs
SET    fs.branch_id = (SELECT branch_id
                       FROM   (SELECT branch_id,
                                      gr_number,
                                      row_number() OVER (PARTITION BY gr_number ORDER BY updated_ts DESC) AS sno
                               FROM   admission_log) x
                       WHERE  x.gr_number = fs.gr_number
                       AND    sno = 1);

That moves the correlation to one level down. Note how I've also aliased the nested subquery.

The performance shouldn't be terrible, since the x.gr_number = fs.gr_number predicate involves the same column in the subquery which the analytic function is being partitioned on. That should allow Oracle to filter the subquery appropriately.

ETA: you could also use a MERGE statement instead:

MERGE INTO fs tgt
  USING (SELECT branch_id,
                row_number() OVER (PARTITION BY gr_number ORDER BY updated_ts DESC) AS sno
         FROM   admission_log) src
    ON (tgt.gr_number = src.gr_number AND src.sno = 1)
WHEN MATCHED THEN
  UPDATE tgt.branch_id = src.branch_id;


问:
Can I use a collection initializer with LINQ to return a fully populated collection?
I would like to rewrite the following code in one line, using LINQ. Is it possible?

```<code>var to = new MailAddressCollection();

foreach(string recipient in recipients)
{
    to.Add(new MailAddress(recipient));
}
</code>```

Something like the following would be ideal. As written it returns multiple MailAddressCollections:

```<code>var to = recipients.Select(r => new MailAddressCollection() {new MailAddress(r)});
</code>```

Note that these are framework classes, so I cannot rewrite MailAddressCollection to include a constructor argument.

答:
There is a 1 line alternative that doesn't use linq which I provide for completeness. Personally I couldn't recommend it due to the unnecessary string manipulation.

It does however provide a terse solution.

```<code>var to = new MailAddressCollection() { string.join(",", recipients) };
</code>```

Body:
I would like to rewrite the following code in one line, using LINQ. Is it possible?

var to = new MailAddressCollection();

foreach(string recipient in recipients)
{
    to.Add(new MailAddress(recipient));
}

Something like the following would be ideal. As written it returns multiple MailAddressCollections:

var to = recipients.Select(r => new MailAddressCollection() {new MailAddress(r)});

Note that these are framework classes, so I cannot rewrite MailAddressCollection to include a constructor argument.

Body:
There is a 1 line alternative that doesn't use linq which I provide for completeness. Personally I couldn't recommend it due to the unnecessary string manipulation.

It does however provide a terse solution.

var to = new MailAddressCollection() { string.join(",", recipients) };


问:
Unit testing on STM32
I am looking for advice on how to do unit testing on my STM32F7 platform. What have people done in the past? What horror stories do you have? What would you do differently? What is problematic with my current plan?

My Setup

STM32 Nucleo-144 with a custom carrier PCB

arm-atollic-eabi-gcc compiler (no C++, for now)

Using Atollic TrueStudio as an IDE

Development done from Ubuntu 16.04

Running FreeRTOS on the board

My Testing Plan

There are different levels of testing; I am specifically talking about unit testing a library / set of functionality that does NOT depend on external hardware. Things like "does my ring buffer implementation correctly handle rolling over without memory leaks" and "does this bit-shift operation result in the correct endianness in the resulting variable"? So I am focused on those kinds of tests.

Convert my project to compile with C++ (and all the associated extern C required)

Refactor my code into a "library" portion and an "application" portion.

Build googletest (this is what we use for other parts of our system) and link my library into it for testing.

Run the unit tests on the device while running a debug session through Atollic.

答:
You should revisit the question if you really have to do the unit testing on an embedded target at all as you wrote that unit tests are planned (as usual) in order to test

a set of functionality that does NOT depend on external hardware.

Things like "does my ring buffer implementation correctly handle rolling over without memory leaks?" and "does this bit-shift operation result in the correct endianness in the resulting variable?"

These are (potential) errors will happen on a PC architecture (x86, ...) in virtually the same way as on STM32.

At the same time, you should ask yourself how many errors will occur accidentally while you

Convert [the] project to compile with C++ (and all the associated extern C required)

Refactor my code into a "library" portion and an "application" portion.

Don't get me wrong - the latter point may improve the quality of the software considerably if it is done well (and in the ideal phase of the project).

I've been developing software with functional-safety relevance (IEC61508, SIL3) for many years now - and while there might be some special cases when you cannot move all unit testing to a different HW platform (your PC), I have never encountered such an example myself.
Instead, we could always perform our unit tests on some PC and complement these unit tests by some sort of integration tests on the original hardware.
Please note that in such (complementary) integration tests, you don't have to focus on library-internal logic errors any more, but mostly on HW/SW integration and system integration.

Title: Unit testing on STM32


问:
How to open remote files in sublime text 3
I am connecting to remote server using "mRemoteNG" and want to open remote server files in my local sublime text editor. During my research, I found this relevant blog https://wrgms.com/editing-files-remotely-via-ssh-on-sublimetext-3/ and followed the instructions but it is not working for me.
Does, anybody know how can I open remote files in my Sublime?</p>

答:
Base on this.

Step by step:

On your local workstation: On Sublime Text 3, open Package Manager (Ctrl-Shift-P on Linux/Win, Cmd-Shift-P on Mac, Install Package), and search for rsub

On your local workstation: Add RemoteForward 52698 127.0.0.1:52698 to your .ssh/config file, or -R 52698:localhost:52698 if you prefer command line

On your remote server:

```<code>sudo wget -O /usr/local/bin/rsub https://raw.github.com/aurora/rmate/master/rmate
sudo chmod a+x /usr/local/bin/rsub
</code>```

Just keep your ST3 editor open, and you can easily edit remote files with

```<code>rsub myfile.txt
</code>```

EDIT: if you get "no such file or directory", it's because your /usr/local/bin is not in your PATH. Just add the directory to your path:

```<code>echo "export PATH=\"$PATH:/usr/local/bin\"" >> $HOME/.bashrc
</code>```

Now just log off, log back in, and you'll be all set.

Body:
Base on this.

Step by step:

On your local workstation: On Sublime Text 3, open Package Manager (Ctrl-Shift-P on Linux/Win, Cmd-Shift-P on Mac, Install Package), and search for rsub

On your local workstation: Add RemoteForward 52698 127.0.0.1:52698 to your .ssh/config file, or -R 52698:localhost:52698 if you prefer command line

On your remote server:

sudo wget -O /usr/local/bin/rsub https://raw.github.com/aurora/rmate/master/rmate
sudo chmod a+x /usr/local/bin/rsub

Just keep your ST3 editor open, and you can easily edit remote files with

rsub myfile.txt

EDIT: if you get "no such file or directory", it's because your /usr/local/bin is not in your PATH. Just add the directory to your path:

echo "export PATH=\"$PATH:/usr/local/bin\"" >> $HOME/.bashrc

Now just log off, log back in, and you'll be all set.


问:
Using QtConcurrent::map() function on QList yields segmentation fault
I am familiarizing myself with QtConcurrent library. I have a UI (MainWindow) where I run my functions to simulate a real world example of multithreading.

The QtConcurrent::map() function I am using requires some:

Iterator or a Sequence, in my case I am using a QList.

Further, it requires a MapFunctor (which supports lambdas*) but for this purpose, I am choosing to stick to a static method for testing.

What I have tried

I attempted using both map() functions (the first is left uncommented)

QtConcurrent::map(Sequence &sequence, MapFunctor function

QtConcurrent::map(Iterator begin, Iterator end, MapFunctor function)

I tried searching for a Sequence and a MapFunctor, but I could only find it in templates which did not help alot, thus I had to try and use my intuition to make sense of it.

The Code:

Somewhere inside my MainWindow.cpp

```<code>// counter variable stored in MainWindow
int i = 0;

// MapFunctor
void mapSumToQString(QPair<int, int> pair)
{
    i++;
    qDebug() << "Execute " << i << " = " << QString::number(pair.first, pair.second);;
}
</code>```

and the code to start it all

```<code>// UI class decl
MainWindow::MainWindow(QWidget* parent)
     : QMainWindow(parent)
     , ui(new Ui::MainWindow)
{
     ui->setupUi(this);

     // Create list of integers to perform map function on (here I don't write back to the original sequence i.e. list)
     QList<QPair<int, int>> intPairList = QList<QPair<int, int>>();
     for (int i = 0; i < 1000; i++) {
         int i1 = qrand();
         int i2 = qrand();
         intPairList.append(QPair<int, int>(i1, i2));
     }

     QFuture<void> future;
     future = QtConcurrent::map(intPairList, mapSumToQString);
     // future = QtConcurrent::map(intPairList.begin(), intPairList.end(), mapSumToQString);
}
</code>```

Problem:

Running this snippet of code results in a SEGV here

```<code>namespace QtConcurrent {
// map kernel, works with both parallel-for and parallel-while
template <typename Iterator, typename MapFunctor>
class MapKernel : public IterateKernel<Iterator, void>
{
    MapFunctor map;
public:
    typedef void ReturnType;
    MapKernel(Iterator begin, Iterator end, MapFunctor _map)
        : IterateKernel<Iterator, void>(begin, end), map(_map)
    { }
    bool runIteration(Iterator it, int, void *) override
    {
        map(*it);                       <--------SEGV line
        return false;
    }

    //...
}
</code>```

Stacktrace (copied from debugger)

```<code>1  QtConcurrent::MapKernel<QList<QPair<int, int>>::iterator, QtConcurrent::FunctionWrapper1<void, QPair<int, int>>>::runIteration  qtconcurrentmapkernel.h      68  0x404ee8
2  QtConcurrent::MapKernel<QList<QPair<int, int>>::iterator, QtConcurrent::FunctionWrapper1<void, QPair<int, int>>>::runIterations qtconcurrentmapkernel.h      77  0x404f82
3  QtConcurrent::IterateKernel<QList<QPair<int, int>>::iterator, void>::forThreadFunction                                          qtconcurrentiteratekernel.h  255 0x40466e
4  QtConcurrent::IterateKernel<QList<QPair<int, int>>::iterator, void>::threadFunction                                             qtconcurrentiteratekernel.h  217 0x404486
5  QtConcurrent::ThreadEngineBase::run                                                                                qtconcurrentthreadengine.cpp 302 0x6d881973
6  QThreadPoolThread::run                                                                                qthreadpool.cpp              99  0x111b36a
7  QThreadPrivate::start(void *) *4                                                                                qthread_win.cpp              403 0x11163eb
8  KERNEL32!BaseThreadInitThunk                                                                                0x74d56359
9  ntdll!RtlGetAppContainerNamedObjectPath                                                                                0x77467c24
10 ntdll!RtlGetAppContainerNamedObjectPath                                                                                0x77467bf4
11 ??
</code>```

For the record, there is another question related to this, but most certainly does not provide a usable solution.

Why do I get this SEGV, what is causing this access violation?

答:
Honestly, some parts of your question are not clear for me. However, please take into account the followings (although you may have considered some or all of them):

the functor is highly recommended to be a static function. From your code, it seems that you may have not declared the static function properly. Please put the following in your MainWindow.h:

```<code>static void mapSumToQString(QPair<int, int> pair);
</code>```

and modify the implementation as follows:

```<code>// MapFunctor
void MainWindow::mapSumToQString(QPair<int, int> pair)
{
    j++;
    qDebug() << "Execute " << j << " = " << QString::number(pair.first, pair.second);;
}
</code>```

mapSumToQString is static, hence you cannot use non-static members of the MainWindow inside it. Hence, the i must be static as well.

```<code>static int j; //in MainWindow.h ---> I changed i to j to make it differ from your For loop variable
int MainWindow::j = 0;//in MainWindow.cpp ----> static variables have to be initialized
</code>```

Modify MainWindow.cpp as follows:

```<code>    // counter variable stored in MainWindow
    j = 0;

    QFuture<void> future;
    future = QtConcurrent::map(intPairList, mapSumToQString);
    future.waitForFinished();
</code>```

One thing that I cannot understand is that you are converting an integer to a string with a random base?!

```<code>qDebug() << "Execute " << j << " = " << QString::number(pair.first, pair.second);
//Herein, pair.second is random, and hence QString::number's second input (base) is always a random number. Do you really want it?
</code>```

Body:
I am familiarizing myself with QtConcurrent library. I have a UI (MainWindow) where I run my functions to simulate a real world example of multithreading.

The QtConcurrent::map() function I am using requires some:

Iterator or a Sequence, in my case I am using a QList.

Further, it requires a MapFunctor (which supports lambdas*) but for this purpose, I am choosing to stick to a static method for testing.

What I have tried

I attempted using both map() functions (the first is left uncommented)

QtConcurrent::map(Sequence &sequence, MapFunctor function

QtConcurrent::map(Iterator begin, Iterator end, MapFunctor function)

I tried searching for a Sequence and a MapFunctor, but I could only find it in templates which did not help alot, thus I had to try and use my intuition to make sense of it.

The Code:

Somewhere inside my MainWindow.cpp

// counter variable stored in MainWindow
int i = 0;

// MapFunctor
void mapSumToQString(QPair<int, int> pair)
{
    i++;
    qDebug() << "Execute " << i << " = " << QString::number(pair.first, pair.second);;
}

and the code to start it all

// UI class decl
MainWindow::MainWindow(QWidget* parent)
     : QMainWindow(parent)
     , ui(new Ui::MainWindow)
{
     ui->setupUi(this);

     // Create list of integers to perform map function on (here I don't write back to the original sequence i.e. list)
     QList<QPair<int, int>> intPairList = QList<QPair<int, int>>();
     for (int i = 0; i < 1000; i++) {
         int i1 = qrand();
         int i2 = qrand();
         intPairList.append(QPair<int, int>(i1, i2));
     }

     QFuture<void> future;
     future = QtConcurrent::map(intPairList, mapSumToQString);
     // future = QtConcurrent::map(intPairList.begin(), intPairList.end(), mapSumToQString);
}

Problem:

Running this snippet of code results in a SEGV here

namespace QtConcurrent {
// map kernel, works with both parallel-for and parallel-while
template <typename Iterator, typename MapFunctor>
class MapKernel : public IterateKernel<Iterator, void>
{
    MapFunctor map;
public:
    typedef void ReturnType;
    MapKernel(Iterator begin, Iterator end, MapFunctor _map)
        : IterateKernel<Iterator, void>(begin, end), map(_map)
    { }
    bool runIteration(Iterator it, int, void *) override
    {
        map(*it);                       <--------SEGV line
        return false;
    }

    //...
}

Stacktrace (copied from debugger)

1  QtConcurrent::MapKernel<QList<QPair<int, int>>::iterator, QtConcurrent::FunctionWrapper1<void, QPair<int, int>>>::runIteration  qtconcurrentmapkernel.h      68  0x404ee8
2  QtConcurrent::MapKernel<QList<QPair<int, int>>::iterator, QtConcurrent::FunctionWrapper1<void, QPair<int, int>>>::runIterations qtconcurrentmapkernel.h      77  0x404f82
3  QtConcurrent::IterateKernel<QList<QPair<int, int>>::iterator, void>::forThreadFunction                                          qtconcurrentiteratekernel.h  255 0x40466e
4  QtConcurrent::IterateKernel<QList<QPair<int, int>>::iterator, void>::threadFunction                                             qtconcurrentiteratekernel.h  217 0x404486
5  QtConcurrent::ThreadEngineBase::run                                                                                qtconcurrentthreadengine.cpp 302 0x6d881973
6  QThreadPoolThread::run                                                                                qthreadpool.cpp              99  0x111b36a
7  QThreadPrivate::start(void *) *4                                                                                qthread_win.cpp              403 0x11163eb
8  KERNEL32!BaseThreadInitThunk                                                                                0x74d56359
9  ntdll!RtlGetAppContainerNamedObjectPath                                                                                0x77467c24
10 ntdll!RtlGetAppContainerNamedObjectPath                                                                                0x77467bf4
11 ??

For the record, there is another question related to this, but most certainly does not provide a usable solution.

Why do I get this SEGV, what is causing this access violation?

Body:
Honestly, some parts of your question are not clear for me. However, please take into account the followings (although you may have considered some or all of them):

the functor is highly recommended to be a static function. From your code, it seems that you may have not declared the static function properly. Please put the following in your MainWindow.h:

static void mapSumToQString(QPair<int, int> pair);

and modify the implementation as follows:

// MapFunctor
void MainWindow::mapSumToQString(QPair<int, int> pair)
{
    j++;
    qDebug() << "Execute " << j << " = " << QString::number(pair.first, pair.second);;
}

mapSumToQString is static, hence you cannot use non-static members of the MainWindow inside it. Hence, the i must be static as well.

static int j; //in MainWindow.h ---> I changed i to j to make it differ from your For loop variable
int MainWindow::j = 0;//in MainWindow.cpp ----> static variables have to be initialized

Modify MainWindow.cpp as follows:

    // counter variable stored in MainWindow
    j = 0;

    QFuture<void> future;
    future = QtConcurrent::map(intPairList, mapSumToQString);
    future.waitForFinished();

One thing that I cannot understand is that you are converting an integer to a string with a random base?!

qDebug() << "Execute " << j << " = " << QString::number(pair.first, pair.second);
//Herein, pair.second is random, and hence QString::number's second input (base) is always a random number. Do you really want it?


问:
Sharepoint 2010 designer Approval workflow for document
I am having below requirement using sharepoint 2010 designer workflow.
Once anyone reject the request the workflow must be assigned back to User who is initiating.
Please guide me how can i achive this. I am new to sharepoint workflows.

答:
OOB SharePoint 2010 designer workflow can't achieve this, you would consider to use third-party solution/product for this.

Or develop your state machine workflow.

https://www.codeproject.com/Articles/193520/SharePoint-2010-State-Machine-Workflows-with-Custo

https://learn.microsoft.com/en-us/previous-versions/office/developer/sharepoint-2010/gg508985(v%3Doffice.14)


问:
UseStatusCodePagesWithReExecute() not working on .NET Core 3.1
I use UseStatusCodePagesWithReExecute to redirect the user to an error page if there is a problem with the application.

If an Error occurs in my application for example Code 500, I am not redirected to "/Home/Error".
If I call it manually "/Home/Error" is ok!

Here is my code, where is the error?

        public IActionResult Error(string code)
        {
            return View(new ErrorModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier, ErrorStatusCode = code });
        }

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseSiteOfflineMiddleware();

            app.UseStatusCodePagesWithReExecute("/Home/Error", "?code={0}");

            app.UseStaticFiles();
            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();
            app.UseSession(); // Aggiungi Supporto Sessioni

            // Dependency Injection Option per leggere Localizzazione File Resources delle lingue
            var localizationOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>().Value;
            app.UseRequestLocalization(localizationOptions);

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "products",
                    pattern: "{codLanguage}/shop/{id}/{nameProduct}",
                    new { controller = "Catalog", action = "Detail" });

                endpoints.MapControllerRoute(
                    name: "catalog",
                    pattern: "/shop",
                    new { controller = "Catalog", action = "Index" });

                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });

            app.Run(async (context) =>
            {
                await Task.CompletedTask;
            });

        }
```

答:
In the issue, as Tratcher mentioned,UseStatusCodePagesWithReExecute is for status code responses without bodies (e.g empty 404).And for the code like 500,you can use  UseExceptionHandler.

If you want to redirect to the url "/Home/Error" when the status code is 500, you can do like this:

```<code>public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
           app.UseExceptionHandler("/Home/Error");
            app.UseStatusCodePagesWithReExecute("/Home/Error", "?code={0}");
</code>```

Body:
In the issue, as Tratcher mentioned,UseStatusCodePagesWithReExecute is for status code responses without bodies (e.g empty 404).And for the code like 500,you can use  UseExceptionHandler.

If you want to redirect to the url "/Home/Error" when the status code is 500, you can do like this:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
           app.UseExceptionHandler("/Home/Error");
            app.UseStatusCodePagesWithReExecute("/Home/Error", "?code={0}");


问:
Azure HTTP Function -- Encountering issues when creating trigger with OneDrive file input-binding
So I have a requirement to process a file when it is uploaded to a particular folder in OneDrive. An Azure Function would be nice to use for this purpose.

Here's what I see when trying to set this up in the Azure portal:

Is it even possible to do this in the portal either v3 or v2 of the Azure Functions runtime? I tried to follow the steps documented here but I find them a little less-explicit and difficult to interpret/follow.

If anyone has any better examples to follow, please be so kind to share. I'm confused as to what approach to take (e.g. portal, VS Code, VS)

答:
Currently it is recommended that we use the classic function UI in azure portal as there are some issues in the new UI.

And I found that Microsoft Graph bindings are currently in preview for Azure Functions version 2.x and higher. For preview version, we don't recommend that you use them in your production apps.

The workaround is that you use Azure Logic Apps instead.

Reference:

Access and manage files in OneDrive connector by using Azure Logic Apps