问:
ReactJS - JavaScript: How to zoom on customized marker after click on it
Usig google-map-react, how do I zoom on a customized marker after I click on it?
I am able to click on the marker but it is not zooming after the click.

Below a snippet of code for the most important parts:

GoogleMap.js

```<code>import React, { Component } from 'react';
import GoogleMapReact from 'google-map-react';

const markerStyle = {
    position: 'absolute'
};

function CustomMarker({ lat, lng, onMarkerClick }) {
    return (
        <div onClick={onMarkerClick} lat={lat} lng={lng}>
            <img style={markerStyle} src={icon} alt="icon" />
        </div>
    );
}
function MapClick({ center, zoom, data }) {
    function handleMarkerClick() {
        console.log('Click');
    }
}

class BoatMap extends Component {
    constructor(props) {
        super(props);
        this.state = {
            buttonEnabled: true,
            buttonClickedAt: null,
            progress: 0,
            ships: [],
            type: 'All'
        };
    }

// Operations.......

render() {
    return (
        <div className="google-map">
            <GoogleMapReact
                bootstrapURLKeys={{ key: 'My_KEY' }}
                center={{
                    lat: 42.4,
                    lng: -71.1
                }}
                zoom={8}
                defaultZoom={zoom}
                defaultCenter={center}
            >
                {/* Rendering all the markers here */}
                {this.state.ships.map((ship) => (
                    <Ship ship={ship} key={ship.CALLSIGN} lat={ship.LATITUDE} lng={ship.LONGITUDE} />
                ))}

                {/* Trying to focus on the marker after clicking on it */}
                {data.map((item, idx) => {
                return <CustomMarker  onMarkerClick={handleMarkerClick} key={idx} lat={item.lat} lng={item.lng} />
                })}

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

ShipTracker.js is where I detect the correct click event:

```<code>const Ship = ({ ship }) => {
    const shipName = ship.NAME;
    const company = shipCompanyMap[shipName];

    function handleMarkerClick() {
        console.log('marker clicked');
    }

    const shipImage = companyImageMap[company];
    return (
        <div onClick={handleMarkerClick}>
            {/* Render shipImage image */}
            <img src={shipImage} alt="Logo" />
        </div>
    );
};
export { Ship };
</code>```

What I have done so far:

what I tried so far:

1) I came across this source and that was useful to understand how to create a marker but unfortunately I was not able to solve the problem.

2) In my case I use google-map-react instead of google-map. I know that the procedure is similar, but for some reasons I might be missing something.

3) After digging more into the problem I came across this source and it was very useful but still I could not fix the problem.

答:
I'm not sure but you can try to get instance of map throw ref
like </p>

```<code><GoogleMapReact ref={this.map}
</code>```

<p>and then use it in handler </p>

```<code>function handleMarkerClick(marker) {
    this.map.panTo(marker.coordinates);
}
</code>```

Body:
Usig google-map-react, how do I zoom on a customized marker after I click on it?
I am able to click on the marker but it is not zooming after the click.

Below a snippet of code for the most important parts:

GoogleMap.js

import React, { Component } from 'react';
import GoogleMapReact from 'google-map-react';

const markerStyle = {
    position: 'absolute'
};

function CustomMarker({ lat, lng, onMarkerClick }) {
    return (

    );
}
function MapClick({ center, zoom, data }) {
    function handleMarkerClick() {
        console.log('Click');
    }
}

class BoatMap extends Component {
    constructor(props) {
        super(props);
        this.state = {
            buttonEnabled: true,
            buttonClickedAt: null,
            progress: 0,
            ships: [],
            type: 'All'
        };
    }

// Operations.......

render() {
    return (

            <GoogleMapReact
                bootstrapURLKeys={{ key: 'My_KEY' }}
                center={{
                    lat: 42.4,
                    lng: -71.1
                }}
                zoom={8}
                defaultZoom={zoom}
                defaultCenter={center}
            >
                {/* Rendering all the markers here */}
                {this.state.ships.map((ship) => (
                    <Ship ship={ship} key={ship.CALLSIGN} lat={ship.LATITUDE} lng={ship.LONGITUDE} />
                ))}

                {/* Trying to focus on the marker after clicking on it */}
                {data.map((item, idx) => {
                return <CustomMarker  onMarkerClick={handleMarkerClick} key={idx} lat={item.lat} lng={item.lng} />
                })}

            </GoogleMapReact>

    );
}
}

ShipTracker.js is where I detect the correct click event:

const Ship = ({ ship }) => {
    const shipName = ship.NAME;
    const company = shipCompanyMap[shipName];

    function handleMarkerClick() {
        console.log('marker clicked');
    }

    const shipImage = companyImageMap[company];
    return (

            {/* Render shipImage image */}

    );
};
export { Ship };

What I have done so far:

what I tried so far:

1) I came across this source and that was useful to understand how to create a marker but unfortunately I was not able to solve the problem.

2) In my case I use google-map-react instead of google-map. I know that the procedure is similar, but for some reasons I might be missing something.

3) After digging more into the problem I came across this source and it was very useful but still I could not fix the problem.

Body:
I'm not sure but you can try to get instance of map throw ref
like

<GoogleMapReact ref={this.map}

and then use it in handler

function handleMarkerClick(marker) {
    this.map.panTo(marker.coordinates);
}


来源: stackexchange

问:
Blazor databinding to a javascript web component with complex object from C#
I've got a Blazor app that is referencing a custom web component (<omnibar-navigation>).

This component has an items property that should be a json object that looks something like this:

```<code>[{'title':'Home','icon':'places-home-1','url':'/','metadata':null,'items':null}, ...]
</code>```

I'm wondering how to bind a C# complex object to that items property.

var options = new List { new Nav { Title = "Home", Icon = "places-home-1", Url = "/" } };
```

<p>Then the binding would be something like this (doesn't work):</p>

```<omnibar-navigation items="@options">...</omnibar-navigation>
```

A code repo for this problem is here:  https://github.com/dahlsailrunner/blazor-oidc.

The page with the exact problem is here: https://github.com/dahlsailrunner/blazor-oidc/blob/master/Sample.Blazor/Pages/Stencil.razor

The component is imported on the Pages/_Host.cshtml file.

答:
Great question. I noticed also some issues with binding a web component directly via Blazor data binding, especially with the connectedCallback of the web component which is a kwown issue.

But the great thing is:

If something in Blazor doesn't work, you can always use JavaScript Interop to make it work!

I've created here a blog post for you that shows how to integrate a web component via JS Interop that has such a property/attribute that takes a complex object: https://www.thomasclaudiushuber.com/2020/02/14/initializing-web-components-in-blazor-via-js-interop/

It also shows how to wrap the web component with a native Blazor component, so that you can bind it just with C#. :-)

Here is a git repo with all the code: https://github.com/thomasclaudiushuber/Blazor-Using-Custom-Web-Component

Happy coding,
Thomas

ContentLicense: CC BY-SA 4.0

Body:
I've got a Blazor app that is referencing a custom web component (<omnibar-navigation>).

This component has an items property that should be a json object that looks something like this:

[{'title':'Home','icon':'places-home-1','url':'/','metadata':null,'items':null}, ...]

I'm wondering how to bind a C# complex object to that items property.

var options = new List { new Nav { Title = "Home", Icon = "places-home-1", Url = "/" } };

Then the binding would be something like this (doesn't work):

<omnibar-navigation items="@options">...</omnibar-navigation>

A code repo for this problem is here:  https://github.com/dahlsailrunner/blazor-oidc.

The page with the exact problem is here: https://github.com/dahlsailrunner/blazor-oidc/blob/master/Sample.Blazor/Pages/Stencil.razor

The component is imported on the Pages/_Host.cshtml file.


问:
Python 3 unit test fails when running at directory level
I have two python unit test files in a folder

```<code>test/folder1/test_file1.py
test/folder2/test_file2.py
</code>```

When I run the tests individually they pass, but when I run at the directory level the first test file passes but the second test file fails. Why would this happen? Both test files import some of the same modules. One file uses MagicMock the other doesn't

```<code>Pass commands
python3 -m pytest test/folder1/test_file1.py
python3 -m pytest test/folder1/test_file2.py

Fail command
python3 -m pytest test/folder1/
</code>```

import commands in test_file1

```<code>import os
import shutil
import tempfile
import xlrd
from unittest import TestCase

from example.folder1 import module1
from example.folder4 import module4
</code>```

Import commands in test_file2

```<code>import xlrd
from unittest import TestCase
from unittest.mock import MagicMock

from example.folder1 import module1 (same as test_file1)
from example.folder2 import module2
from example.folder3 import module3
import pkg_resources
</code>```

答:
Found the issue.

We were using a local CACHE variable. The first test was setting up the cache, the second test ended up using the cache from the first test.

Clearing the cache in setupClass() before running the second test solved the issue

Body:
I have two python unit test files in a folder

test/folder1/test_file1.py
test/folder2/test_file2.py

When I run the tests individually they pass, but when I run at the directory level the first test file passes but the second test file fails. Why would this happen? Both test files import some of the same modules. One file uses MagicMock the other doesn't

Pass commands
python3 -m pytest test/folder1/test_file1.py
python3 -m pytest test/folder1/test_file2.py

Fail command
python3 -m pytest test/folder1/

import commands in test_file1

import os
import shutil
import tempfile
import xlrd
from unittest import TestCase

from example.folder1 import module1
from example.folder4 import module4

Import commands in test_file2

import xlrd
from unittest import TestCase
from unittest.mock import MagicMock

from example.folder1 import module1 (same as test_file1)
from example.folder2 import module2
from example.folder3 import module3
import pkg_resources


问:
Get hive and hadoop version from within pyspark session
I'm using pyspark upon a hadoop cluster with hive. I know its possible to get the spark, hive & hadoop versions from the command-line (spark-submit --version, hive --version, hadoop version) but how do I do the same from within pyspark?

getting the spark version is easy enough:

```<code>print("Spark version = ".format(spark._sc.version))
</code>```

I can't figure out how to get the hive & hadoop version though. Anyone know? TIA

答:
ok, I solved it by doing this:

```<code>from sh import hive, hadoop
print("Hive version = {0}".format(hive("--version")))
print("Hadoop version = {0}".format(hadoop("version")))
</code>```

Would be nice if there were a way to get it from the spark object without having to shell out. If anyone knows a way please let me know.

Body:
I'm using pyspark upon a hadoop cluster with hive. I know its possible to get the spark, hive & hadoop versions from the command-line (spark-submit --version, hive --version, hadoop version) but how do I do the same from within pyspark?

getting the spark version is easy enough:

print("Spark version = ".format(spark._sc.version))

I can't figure out how to get the hive & hadoop version though. Anyone know? TIA

Body:
ok, I solved it by doing this:

from sh import hive, hadoop
print("Hive version = {0}".format(hive("--version")))
print("Hadoop version = {0}".format(hadoop("version")))

Would be nice if there were a way to get it from the spark object without having to shell out. If anyone knows a way please let me know.


问:
Using sed to replace <? with <?php
I'm trying to programmatically replace <? with <?php in a bunch of file, but my sed regex isn't behaving like I expected. Can you tell me what's wrong with it?

I'm testing it on the command line here:

```<code>$ sed -e 's/<\?/<\?php/g'
<?
<?php?<?php
d
<?phpd<?php
</code>```

答:
You don't need to escape the back reference in the replacement.

```<code>sed 's#<\?#<?php#'
</code>```

In a pipe, to correct for doubling the php:

```<code>sed 's#<\?#<?php#g' | sed 's#phpphp#php#g'
</code>```

ContentLicense: CC BY-SA 3.0

Title: Using sed to replace <? with <?php

Body:
I'm trying to programmatically replace <? with <?php in a bunch of file, but my sed regex isn't behaving like I expected. Can you tell me what's wrong with it?

I'm testing it on the command line here:

$ sed -e 's/<\?/<\?php/g'
<?
<?php?<?php
d
<?phpd<?php

Body:
You don't need to escape the back reference in the replacement.

sed 's#<\?#<?php#'

In a pipe, to correct for doubling the php:

sed 's#<\?#<?php#g' | sed 's#phpphp#php#g'


问:
php Api hosted on AWS s3 bucket
I wanna host a php file that retrieve data from a mysql DB how ever aws is not authorizing POST method.
I need to know how can I add the code in PHP knowing I already configured the Bucket policy and CORS</p>

答:
You can only serve static content from an S3 - PHP will not be processed.

If you want to set up a dynamic PHP website on AWS have a look at LightSail and its LAMP stack.

Title: php Api hosted on AWS s3 bucket


问:
How to arrange JComboBox item
I have a JComboBox contain 9 image items. How can I arrange them to 3*3?

I want my items arrange like this

I've tried google it for several days, but I don't know what is the keyword for this question. Any advice is appreciated. Thanks for reading my question.

Edit:

Thanks for everyone's feedback.
I am making a map editor where I can put map element together.
The editor.
It is more intuitive to arrange the stone road 3*3. The user can easily know which elements match each other.

I am not necessarily using combo box. I've also consider using buttons, but I think that buttons will waste a lat of space. Because I will have more map elements in the future.

答:
The popup for the combo box uses a JList component to display the items.

You can access and change the orientation of the JList to wrap items:

```<code>Object child = comboBox.getAccessibleContext().getAccessibleChild(0);
BasicComboPopup popup = (BasicComboPopup)child;
JList list = popup.getList();
list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
list.setVisibleRowCount(3);
</code>```

This will allow you to navigate through the items using the up/down keys.

To support navigation using the left/right keys you need to add additional Key Bindings to the combo box:

```<code>InputMap im = comboBox.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
im.put(KeyStroke.getKeyStroke("LEFT"), "selectPrevious");
im.put(KeyStroke.getKeyStroke("RIGHT"), "selectNext");
</code>```

However, the popup is based on the width of the largest item added to the combo box. This will be a problem as you won't see all the items. The items will scroll as you use the keys to navigate, but you won't see all 9 items at one time.

To solve this problem you check out Combo Box Popup. It has features that allow you to control the size/behaviour of the popup. You would use:

```<code>BoundsPopupMenuListener listener = new BoundsPopupMenuListener(true, false);
comboBox.addPopupMenuListener( listener );
</code>```

Title: How to arrange JComboBox item

Body:
The popup for the combo box uses a JList component to display the items.

You can access and change the orientation of the JList to wrap items:

Object child = comboBox.getAccessibleContext().getAccessibleChild(0);
BasicComboPopup popup = (BasicComboPopup)child;
JList list = popup.getList();
list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
list.setVisibleRowCount(3);

This will allow you to navigate through the items using the up/down keys.

To support navigation using the left/right keys you need to add additional Key Bindings to the combo box:

InputMap im = comboBox.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
im.put(KeyStroke.getKeyStroke("LEFT"), "selectPrevious");
im.put(KeyStroke.getKeyStroke("RIGHT"), "selectNext");

However, the popup is based on the width of the largest item added to the combo box. This will be a problem as you won't see all the items. The items will scroll as you use the keys to navigate, but you won't see all 9 items at one time.

To solve this problem you check out Combo Box Popup. It has features that allow you to control the size/behaviour of the popup. You would use:

BoundsPopupMenuListener listener = new BoundsPopupMenuListener(true, false);
comboBox.addPopupMenuListener( listener );


问:
C# Converting mixed JSON into an object
Yo Guys,

I'm currently trying to pass some mixed JSON, and was wondering if it was possible to do anything like the following?

```<code>struct example_data
{
    public Dictionary<string, List<string>> information {get; set;}
}

class TestClass
{
    static void Main(string[] args)
    {
        string test_string = @"{'EventSpecificInformation':
                                   {
                                   'measure':''
                                   ,'Long name':'test_name'
                                   ,'Short name':'test_s_name'
                                   ,'Description':''
                                   ,'Status':'Real (Imported)'
                                   ,'Viewers':['Everyone']
                                   ,'Modifiers':['Supervisor only']
                                   ,'calculation':''
                                   }
                               }"

        example_data deserialized_entry = JsonConvert.DeserializeObject<example_data>(test_string)
    }
}
</code>```

As you would expect the above code snippet fails, but I was hoping I could avoid wrapping each JSON entry in a JSON array or having to create a custom JSON reader in C#.

Any advice on the matter would be greatly appreciated.

答:
Sounds like what you're looking for is to parse a JSON string into a dynamic object, like so:

```<code>dynamic myObject = JsonConvert.DeserializeObject(@"{'EventSpecificInformation':
                               {
                               'measure':''
                               ,'Long name':'test_name'
                               ,'Short name':'test_s_name'
                               ,'Description':''
                               ,'Status':'Real (Imported)'
                               ,'Viewers':['Everyone']
                               ,'Modifiers':['Supervisor only']
                               ,'calculation':''
                               }
                           }");

string desc = myObject.EventSpecificInformation.Description;
string longName = myObject.EventSpecificInformation["Long name"];
</code>```

This is likely your best option if you don't have an explicit static model for your JSON input. For properties without a space in their name you can reference them directly using member access syntax, for those with a space you can reference them using indexer access syntax.

Title: C# Converting mixed JSON into an object

Body:
Yo Guys,

I'm currently trying to pass some mixed JSON, and was wondering if it was possible to do anything like the following?

struct example_data
{
    public Dictionary<string, List<string>> information {get; set;}
}

class TestClass
{
    static void Main(string[] args)
    {
        string test_string = @"{'EventSpecificInformation':
                                   {
                                   'measure':''
                                   ,'Long name':'test_name'
                                   ,'Short name':'test_s_name'
                                   ,'Description':''
                                   ,'Status':'Real (Imported)'
                                   ,'Viewers':['Everyone']
                                   ,'Modifiers':['Supervisor only']
                                   ,'calculation':''
                                   }
                               }"

        example_data deserialized_entry = JsonConvert.DeserializeObject<example_data>(test_string)
    }
}

As you would expect the above code snippet fails, but I was hoping I could avoid wrapping each JSON entry in a JSON array or having to create a custom JSON reader in C#.

Any advice on the matter would be greatly appreciated.

Body:
Sounds like what you're looking for is to parse a JSON string into a dynamic object, like so:

dynamic myObject = JsonConvert.DeserializeObject(@"{'EventSpecificInformation':
                               {
                               'measure':''
                               ,'Long name':'test_name'
                               ,'Short name':'test_s_name'
                               ,'Description':''
                               ,'Status':'Real (Imported)'
                               ,'Viewers':['Everyone']
                               ,'Modifiers':['Supervisor only']
                               ,'calculation':''
                               }
                           }");

string desc = myObject.EventSpecificInformation.Description;
string longName = myObject.EventSpecificInformation["Long name"];

This is likely your best option if you don't have an explicit static model for your JSON input. For properties without a space in their name you can reference them directly using member access syntax, for those with a space you can reference them using indexer access syntax.


问:
Deploy Nuxt app to subdirectory on domain
We have a nuxt application which is deployed to a subdirectory on our main domain, lets call the directory 'app'.

But all routes and references to assets refer to the main domain (domain.com/page-1 instead of domain.com/app/page-1). We have tried to solve it with setting 'base' in the router setting. But this results in de app being 1 level deeper (so domain.com/app/app and domain.com/app/app/page-1). In this case all the links and assets refs are ok. How can this be solved?

答:
Referring to nuxt.js official documentation here:
https://nuxtjs.org/api/configuration-router

You have to set the custom path in the router config property object in nuxt.config.js. It's actually the exact answert to question:

The base URL of the app. For example, if the entire single page application is served under /app/, then base should use the value '/app/'.

:)


问:
Phabricator installation problem " FATAL ERROR: Unable to load the "Arcanist" library. Put "arcanist/" next to "phabricator/" on disk."
I'm trying to install Phabricator with that documentation: https://websiteforstudents.com/install-phabricator-platform-on-ubuntu-16-04-18-04-with-apache2-mariadb-and-php-7-2

When i use "sudo ./bin/config set mysql.host localhost" command there was a error:

```<code>FATAL ERROR: Unable to load the "Arcanist" library. Put "arcanist/" next to "phabricator/" on disk.
</code>```

Any solution?

答:
I've received the same fatal when tried to upgrade the Phabricator via update script.

I did manual update in the path in

```<code>./phabricator/scripts/init/lib.php
</code>```

from

```<code>"arcanist/scripts/init/init-script.php"
</code>```

to

```<code>"arcanist/support/init/init-script.php"
</code>```

after which the update script passed and storage upgrade was ok.

Maybe there was a typo and the "scripts" in the path should be "support".

Also reported here https://discourse.phabricator-community.org/t/the-phutil-library-phutil-has-not-been-loaded/3543/2

Body:
I'm trying to install Phabricator with that documentation: https://websiteforstudents.com/install-phabricator-platform-on-ubuntu-16-04-18-04-with-apache2-mariadb-and-php-7-2

When i use "sudo ./bin/config set mysql.host localhost" command there was a error:

FATAL ERROR: Unable to load the "Arcanist" library. Put "arcanist/" next to "phabricator/" on disk.

Any solution?

Body:
I've received the same fatal when tried to upgrade the Phabricator via update script.

I did manual update in the path in

./phabricator/scripts/init/lib.php

from

"arcanist/scripts/init/init-script.php"

to

"arcanist/support/init/init-script.php"

after which the update script passed and storage upgrade was ok.

Maybe there was a typo and the "scripts" in the path should be "support".

Also reported here https://discourse.phabricator-community.org/t/the-phutil-library-phutil-has-not-been-loaded/3543/2


问:
Animating CALayer [filters, compositionFilter, backFilters]
I need to animate one of [filters, compositionFilter, backFilters] on a CALayer in video composition I tried the following code on NSView layer to test if the code works in the first place

```<code>    view.wantsLayer = true
    view.layerUsesCoreImageFilters = true
    if let filter = CIFilter.init(name: "CIGaussianBlur", parameters: ["inputRadius": 50])  {
        let animation = CABasicAnimation.init(keyPath: "filters")

        animation.isRemovedOnCompletion = false
        animation.fillMode = .forwards

        animation.duration = 2 //for testing

        animation.autoreverses = false

        animation.fromValue = NSArray.init(array: [])
        animation.toValue = NSArray.init(array: [filter])

        view.layer.add(animation, forKey: "CIGaussianBlurAnimation")
    }
</code>```

but nothing happens, so I need to know what is the proper way to animate one/all of [filters, compositionFilter, backFilters] properties of CALayer, and whether or not it is supported on AVVideoComposition(on iOS 'I know it is not supported on iOS UIView CALayers')

答:
I found 1/2 the solution
BUT the main question remains: "is there any way to enable CIFilter on CALayer in video composition on iOS"

it is indicated in the documentation, to update any attribute of the filter after is applied to the layer, you should use

```<code>layer.setValue(1, forKeyPath: "backgroundFilters.myFilter.inputRadius")
</code>```

So it means to animate any filter, we should update the filter properties directly in the animation, so the following should be done

for compositingFilter property:

```<code>let animation = CABasicAnimation(keyPath: "compositingFilter.inputRadius")
</code>```

and for a filter in filters property:

```<code>filter.name = "filterName"
layer.filters = [someFilters, filter, otherFilters]
let animation = CABasicAnimation(keyPath: "filters.filterName.inputRadius")
</code>```

and for a filter in backgroundFilters property:

```<code>filter.name = "filterName"
layer.backgroundFilters = [someFilters, filter, otherFilters]
let animation = CABasicAnimation(keyPath: "backgroundFilters.filterName.inputRadius")
</code>```

and set the animation properties, then add it to the layer layer.add(animation, forKey: "animationKey")

NOTE: animationKey could be any value, even a nil value, but reusing the value will remove the previous animation; even when is running

Body:
I need to animate one of [filters, compositionFilter, backFilters] on a CALayer in video composition I tried the following code on NSView layer to test if the code works in the first place

    view.wantsLayer = true
    view.layerUsesCoreImageFilters = true
    if let filter = CIFilter.init(name: "CIGaussianBlur", parameters: ["inputRadius": 50])  {
        let animation = CABasicAnimation.init(keyPath: "filters")

        animation.isRemovedOnCompletion = false
        animation.fillMode = .forwards

        animation.duration = 2 //for testing

        animation.autoreverses = false

        animation.fromValue = NSArray.init(array: [])
        animation.toValue = NSArray.init(array: [filter])

        view.layer.add(animation, forKey: "CIGaussianBlurAnimation")
    }

but nothing happens, so I need to know what is the proper way to animate one/all of [filters, compositionFilter, backFilters] properties of CALayer, and whether or not it is supported on AVVideoComposition(on iOS 'I know it is not supported on iOS UIView CALayers')

Body:
I found 1/2 the solution
BUT the main question remains: "is there any way to enable CIFilter on CALayer in video composition on iOS"

it is indicated in the documentation, to update any attribute of the filter after is applied to the layer, you should use

layer.setValue(1, forKeyPath: "backgroundFilters.myFilter.inputRadius")

So it means to animate any filter, we should update the filter properties directly in the animation, so the following should be done

for compositingFilter property:

let animation = CABasicAnimation(keyPath: "compositingFilter.inputRadius")

and for a filter in filters property:

filter.name = "filterName"
layer.filters = [someFilters, filter, otherFilters]
let animation = CABasicAnimation(keyPath: "filters.filterName.inputRadius")

and for a filter in backgroundFilters property:

filter.name = "filterName"
layer.backgroundFilters = [someFilters, filter, otherFilters]
let animation = CABasicAnimation(keyPath: "backgroundFilters.filterName.inputRadius")

and set the animation properties, then add it to the layer layer.add(animation, forKey: "animationKey")

NOTE: animationKey could be any value, even a nil value, but reusing the value will remove the previous animation; even when is running


问:
Exchange data.table columns with most prevalent value of columns
I have data

```<code>test = data.table(
  a = c(1,1,3,4,5,6),
  b = c("a", "be", "a", "c", "d", "c"),
  c = rep(1, 6)
)
</code>```

I wish to take the unique values of column a, store it in another data.table, and afterwards fill in the remaining columns with the most prevalent values of those remaining columns, such that my resulting data.table would be:

```<code>test2 = data.table(a = c(1,3,4,5,6), b = "a", c = 1)
</code>```

Column be has equal amounts of "a" and "c", but it doesn't matter which is chosen in those cases.

Attempt so far:

```<code>test2 = unique(test, by = "a")
test2[, c("b", "c") := lapply(.SD, FUN = function(x){test2[, .N, by = x][order(-N)][1,1]}), .SDcols = c("b", "c")]
</code>```

EDIT: I would preferrably like a generic solution that is compatible with a function where I specify the column to be "uniqued", and the rest of the columns are with the single most prevalent value. Hence my use of lapply and .SD =)

EDIT2: as @MichaelChirico points out, how do we keep the class. With the following data.table some of the solutions does not work, although solution of @chinsoon12 does work:

```<code>test = data.table(a = c(1,1,3,4,5,6),
                  b = c("a", "be", "a", "c", "d", "c"),
                  c = rep(1, 6),
                  d = as.Date("2019-01-01"))
</code>```

答:
Not a clean way to do this but it works.

```<code>test = data.frame(a = c(1,1,3,4,5,6), b = c("a", "be", "a", "c", "d", "c"), c = rep(1, 6))

a = unique(test$a)
b = tail(names(sort(table(test$b))), 1)
c = tail(names(sort(table(test$c))), 1)

test2 = cbind(a,b,c)
</code>```

Output is like this:

```<code>> test2
     a   b   c
[1,] "1" "c" "1"
[2,] "3" "c" "1"
[3,] "4" "c" "1"
[4,] "5" "c" "1"
[5,] "6" "c" "1"
>
</code>```

Body:
I have data

test = data.table(
  a = c(1,1,3,4,5,6),
  b = c("a", "be", "a", "c", "d", "c"),
  c = rep(1, 6)
)

I wish to take the unique values of column a, store it in another data.table, and afterwards fill in the remaining columns with the most prevalent values of those remaining columns, such that my resulting data.table would be:

test2 = data.table(a = c(1,3,4,5,6), b = "a", c = 1)

Column be has equal amounts of "a" and "c", but it doesn't matter which is chosen in those cases.

Attempt so far:

test2 = unique(test, by = "a")
test2[, c("b", "c") := lapply(.SD, FUN = function(x){test2[, .N, by = x][order(-N)][1,1]}), .SDcols = c("b", "c")]

EDIT: I would preferrably like a generic solution that is compatible with a function where I specify the column to be "uniqued", and the rest of the columns are with the single most prevalent value. Hence my use of lapply and .SD =)

EDIT2: as @MichaelChirico points out, how do we keep the class. With the following data.table some of the solutions does not work, although solution of @chinsoon12 does work:

test = data.table(a = c(1,1,3,4,5,6),
                  b = c("a", "be", "a", "c", "d", "c"),
                  c = rep(1, 6),
                  d = as.Date("2019-01-01"))

Body:
Not a clean way to do this but it works.

test = data.frame(a = c(1,1,3,4,5,6), b = c("a", "be", "a", "c", "d", "c"), c = rep(1, 6))

a = unique(test$a)
b = tail(names(sort(table(test$b))), 1)
c = tail(names(sort(table(test$c))), 1)

test2 = cbind(a,b,c)

Output is like this:

> test2
     a   b   c
[1,] "1" "c" "1"
[2,] "3" "c" "1"
[3,] "4" "c" "1"
[4,] "5" "c" "1"
[5,] "6" "c" "1"
>


问:
Vulkan: Vertex Buffer doesn't get sent to vertex shader
I am learning Vulkan and started having a problem where no vertices would get displayed.
After analyzing my program with RenderDoc (https://renderdoc.org/builds),
I realized that the buffer containing the vertex and index information contained the rights values.

At the end of the same buffer, the indices data:

The problem is that when I check the data that is transmitted to the vertex shader, it is empty:

Here is the command buffer section where it is supposed to send the data to the shader:

```<code>VkDeviceSize indicesOffset = sizeof(Vertex) * this->nbVertices;
VkDeviceSize offsets[] = {0};

vkCmdBindVertexBuffers(commandBuffers[i], 0, 1, &this->vertexBuffer, offsets);
vkCmdBindIndexBuffer(commandBuffers[i], this->vertexBuffer, indicesOffset, VK_INDEX_TYPE_UINT32);

for(size_t j = 0 ; j < this->models.size() ; j++){
    Model *model = this->models[j];
    uint32_t modelDynamicOffset = j * static_cast<uint32_t>(this->uniformDynamicAlignment);

    VkDescriptorSet* modelDescriptorSet =  model->getDescriptorSet(i);
    vkCmdBindDescriptorSets(this->commandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, modelDescriptorSet, 1, &modelDynamicOffset);

    vkCmdDrawIndexed(commandBuffers[i], this->nbIndices, 1, 0, indicesOffset, 0);
}
</code>```

Also, here is how I create the vertex buffer:

```<code>void Application::createVertexBuffers() {
for(Model *model : this->models){
    for(Vertex vertex : model->getVertices()){
        vertices.push_back(vertex);
    }
    for(uint32_t index : model->getIndices()){
        indices.push_back(index);
    }
}

VkDeviceSize vertexBufferSize = sizeof(vertices[0]) * vertices.size();
VkDeviceSize indexBufferSize = sizeof(uint32_t) * indices.size();

this->nbVertices = vertices.size();
this->nbIndices = indices.size();

VkBuffer stagingBuffer;
VkDeviceMemory stagingBufferMemory;

//To CPU
this->createBuffer(vertexBufferSize + indexBufferSize,
                          VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
                          VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
                          stagingBuffer,
                          stagingBufferMemory);
void *data;
vkMapMemory(device, stagingBufferMemory, 0, vertexBufferSize, 0, &data);
memcpy(data, vertices.data(), (size_t)vertexBufferSize);
vkUnmapMemory(device, stagingBufferMemory);

//Add the index data after vertex data
vkMapMemory(device, stagingBufferMemory, vertexBufferSize, indexBufferSize, 0, &data);
memcpy(data, indices.data(), (size_t)indexBufferSize);
vkUnmapMemory(device, stagingBufferMemory);

//To GPU
this->createBuffer(vertexBufferSize + indexBufferSize,
                          VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT,
                          VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
                          this->vertexBuffer,
                          this->vertexBufferMemory);

this->copyBuffer(stagingBuffer, this->vertexBuffer, vertexBufferSize + indexBufferSize);

vkDestroyBuffer(device, stagingBuffer, nullptr);
vkFreeMemory(device, stagingBufferMemory, nullptr);
}
</code>```

If you need more information to help me solve my problem, please tell me.
Thank you.

答:
The indices that renderdoc reports for the render are a bit high.

You pass indicesOffset as vertexOffset in your draw command. Which is:

vertexOffset is the value added to the vertex index before indexing into the vertex buffer.

So replace that with 0 and you should get your proper vertices again.

Body:
I am learning Vulkan and started having a problem where no vertices would get displayed.
After analyzing my program with RenderDoc (https://renderdoc.org/builds),
I realized that the buffer containing the vertex and index information contained the rights values.

At the end of the same buffer, the indices data:

The problem is that when I check the data that is transmitted to the vertex shader, it is empty:

Here is the command buffer section where it is supposed to send the data to the shader:

VkDeviceSize indicesOffset = sizeof(Vertex) * this->nbVertices;
VkDeviceSize offsets[] = {0};

vkCmdBindVertexBuffers(commandBuffers[i], 0, 1, &this->vertexBuffer, offsets);
vkCmdBindIndexBuffer(commandBuffers[i], this->vertexBuffer, indicesOffset, VK_INDEX_TYPE_UINT32);

for(size_t j = 0 ; j < this->models.size() ; j++){
    Model *model = this->models[j];
    uint32_t modelDynamicOffset = j * static_cast<uint32_t>(this->uniformDynamicAlignment);

    VkDescriptorSet* modelDescriptorSet =  model->getDescriptorSet(i);
    vkCmdBindDescriptorSets(this->commandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, modelDescriptorSet, 1, &modelDynamicOffset);

    vkCmdDrawIndexed(commandBuffers[i], this->nbIndices, 1, 0, indicesOffset, 0);
}

Also, here is how I create the vertex buffer:

void Application::createVertexBuffers() {
for(Model *model : this->models){
    for(Vertex vertex : model->getVertices()){
        vertices.push_back(vertex);
    }
    for(uint32_t index : model->getIndices()){
        indices.push_back(index);
    }
}

VkDeviceSize vertexBufferSize = sizeof(vertices[0]) * vertices.size();
VkDeviceSize indexBufferSize = sizeof(uint32_t) * indices.size();

this->nbVertices = vertices.size();
this->nbIndices = indices.size();

VkBuffer stagingBuffer;
VkDeviceMemory stagingBufferMemory;

//To CPU
this->createBuffer(vertexBufferSize + indexBufferSize,
                          VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
                          VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
                          stagingBuffer,
                          stagingBufferMemory);
void *data;
vkMapMemory(device, stagingBufferMemory, 0, vertexBufferSize, 0, &data);
memcpy(data, vertices.data(), (size_t)vertexBufferSize);
vkUnmapMemory(device, stagingBufferMemory);

//Add the index data after vertex data
vkMapMemory(device, stagingBufferMemory, vertexBufferSize, indexBufferSize, 0, &data);
memcpy(data, indices.data(), (size_t)indexBufferSize);
vkUnmapMemory(device, stagingBufferMemory);

//To GPU
this->createBuffer(vertexBufferSize + indexBufferSize,
                          VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT,
                          VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
                          this->vertexBuffer,
                          this->vertexBufferMemory);

this->copyBuffer(stagingBuffer, this->vertexBuffer, vertexBufferSize + indexBufferSize);

vkDestroyBuffer(device, stagingBuffer, nullptr);
vkFreeMemory(device, stagingBufferMemory, nullptr);
}

If you need more information to help me solve my problem, please tell me.
Thank you.


问:
How do I get my for loop to include the last line in a user event script in NetSuite?
I have a user event script in NetSuite that loops through all sales orders line items and automatically adds deposits based on a few conditions. It works for all lines except the last line.

Almost Working code:

```<code>for(var i=0;i<=lineCount;i++){

  var sub_field2 = load_so.getSublistValue({
                                           sublistId: 'item',
                                           fieldId: 'item',
                                           line: i
                                       });
                                       log.debug({
                                         title:"Item ID",
                                         details: sub_field2
                                       });
   var sub_field1 = load_so.getSublistValue({
                                            sublistId: 'item',
                                            fieldId: 'custcol_vcc_deposit_item',
                                            line: i
                                        });
                                        log.debug({
                                          title:"Deposit Item?",
                                               details: sub_field1
                                        });
      var isclosed = load_so.getSublistValue({
                                             sublistId: 'item',
                                             fieldId: 'isclosed',
                                             line: i
                                         });

                                           if(sub_field1 == true && isclosed !== true){
                                             var linkeddepitem = load_so.getSublistValue({
                                                      sublistId: 'item',
                                                      fieldId: 'custcol_vcc_ldi',
                                                      line: i
                                            });
                                            log.debug({
                                              title:"Linked Item ID",
                                              details: linkeddepitem
                                            });

                                            var depqty = load_so.getSublistValue({
                                                     sublistId: 'item',
                                                     fieldId: 'quantity',
                                                     line: i
                                           });
                                           log.debug({
                                            title:"Qty",
                                                 details: depqty
                                           });

                                            load_so.insertLine({
                                              sublistId: 'item',
                                              line: i+1
                                            });
                                            load_so.setSublistValue({
                                              sublistId: 'item',
                                              fieldId:'item',
                                              line: i+1,
                                              value: linkeddepitem
                                            });
                                            load_so.setSublistValue({
                                              sublistId: 'item',
                                              fieldId:'quantity',
                                              line: i+1,
                                              value: depqty
                                            });
                                            var lineCountduringloop = load_so.getLineCount({ sublistId: 'item' });
                                            log.debug({
                                              title:"Line Count Before Return",
                                                   details: lineCountduringloop
                                            });

          };

};
</code>```

How do I make sure the loop is actually going through the last line? The logs indicate the script stops one line short of where it should be, i.e. the last line inserted is checked for conditions, which it correctly fails, and then the script exits the loop; it does not even run on the final line.

Thanks for any input!

答:
If lineCount is the total number of lines, the index for the last line (in SS 2.0) will be lineCount - 1.  So your for statement's first line should be:

```<code>for(var i=0;i<lineCount;i++){
</code>```

NOT

```<code>for(var i=0;i<=lineCount;i++){
</code>```

(Note the deleted "=")

It appears what's happening is that the script is attempting an operation on a line that doesn't exist; hence the error.  This is commonly known as an off by one error.

Body:
I have a user event script in NetSuite that loops through all sales orders line items and automatically adds deposits based on a few conditions. It works for all lines except the last line.

Almost Working code:

for(var i=0;i<=lineCount;i++){

  var sub_field2 = load_so.getSublistValue({
                                           sublistId: 'item',
                                           fieldId: 'item',
                                           line: i
                                       });
                                       log.debug({
                                         title:"Item ID",
                                         details: sub_field2
                                       });
   var sub_field1 = load_so.getSublistValue({
                                            sublistId: 'item',
                                            fieldId: 'custcol_vcc_deposit_item',
                                            line: i
                                        });
                                        log.debug({
                                          title:"Deposit Item?",
                                               details: sub_field1
                                        });
      var isclosed = load_so.getSublistValue({
                                             sublistId: 'item',
                                             fieldId: 'isclosed',
                                             line: i
                                         });

                                           if(sub_field1 == true && isclosed !== true){
                                             var linkeddepitem = load_so.getSublistValue({
                                                      sublistId: 'item',
                                                      fieldId: 'custcol_vcc_ldi',
                                                      line: i
                                            });
                                            log.debug({
                                              title:"Linked Item ID",
                                              details: linkeddepitem
                                            });

                                            var depqty = load_so.getSublistValue({
                                                     sublistId: 'item',
                                                     fieldId: 'quantity',
                                                     line: i
                                           });
                                           log.debug({
                                            title:"Qty",
                                                 details: depqty
                                           });

                                            load_so.insertLine({
                                              sublistId: 'item',
                                              line: i+1
                                            });
                                            load_so.setSublistValue({
                                              sublistId: 'item',
                                              fieldId:'item',
                                              line: i+1,
                                              value: linkeddepitem
                                            });
                                            load_so.setSublistValue({
                                              sublistId: 'item',
                                              fieldId:'quantity',
                                              line: i+1,
                                              value: depqty
                                            });
                                            var lineCountduringloop = load_so.getLineCount({ sublistId: 'item' });
                                            log.debug({
                                              title:"Line Count Before Return",
                                                   details: lineCountduringloop
                                            });

          };

};

How do I make sure the loop is actually going through the last line? The logs indicate the script stops one line short of where it should be, i.e. the last line inserted is checked for conditions, which it correctly fails, and then the script exits the loop; it does not even run on the final line.

Thanks for any input!

Body:
If lineCount is the total number of lines, the index for the last line (in SS 2.0) will be lineCount - 1.  So your for statement's first line should be:

for(var i=0;i<lineCount;i++){

NOT

for(var i=0;i<=lineCount;i++){

(Note the deleted "=")

It appears what's happening is that the script is attempting an operation on a line that doesn't exist; hence the error.  This is commonly known as an off by one error.


问:
why is the address of a c++ function always True?
well why would,

```<code>#include <iostream>

using namespace std;

int afunction () {return 0;};

int anotherfunction () {return 0;};

int main ()
{
    cout << &afunction << endl;
}
</code>```

give this,

1

why is every functions address true?

and how then can a function pointer work if all functions share (so it seems) the same addresss?

答:
Did you check anotherfunction() as well?

Anyway, C++ pointer addresses, like C pointer addresses, are usually virtual on most platforms and don't correspond directly to memory locations. Hence the value may be very small or unusual.

Also, they will always be true, as 0 is NULL, an invalid pointer, and anything that is over 0 is true

Body:
well why would,

#include <iostream>

using namespace std;

int afunction () {return 0;};

int anotherfunction () {return 0;};

int main ()
{
    cout << &afunction << endl;
}

give this,

1

why is every functions address true?

and how then can a function pointer work if all functions share (so it seems) the same addresss?


问:
How to pipe one FLWOR into another?
Simple FLWOR to get all the data (from what was a spreadsheet):

```<code>for $foo  in db:open("foo")
return $foo//text()
</code>```

gives this type of output:

```<code>...
Smallville, XX 12345-1234
Bob
(123) 456-7809
(123) 876-3468
Smallville, XX 12345-1234
Alice
Smallville, XX 12345-1234
Fred
(123) 654-5432
Smallville, XX 12345-1234
...
</code>```

and another which returns non-numeric data:

```<code>for $foo  in db:open("foo")
return $foo//text()[not(matches(., '[0-9]'))]
</code>```

Which seems to return only the names.  On that assumption, looking to trigger closing tags on a <person> and opening a new <person>, like:

```<code><person>
<name>a</name>
<data>123</data>
<data>345</data>
<data>123 main st</data>
</person>

<person>
...
</person>
</code>```

Or something like that.  Only really looking to seperate individuals on the assumption that there aren't numerals in their name, and then creating some sort of entity in XML.

Just so long as each time a "name" is found that triggers closing tags and then "starting" a new person.  Not at all sure of the standard lingo here.

答:
The following creates a temporary XML structure, then iterates through each of the name elements, creating a person with the name and it's following-sibling::data elements.

```<code>let $temp :=
  <doc>{
    for $foo in db:open("foo")
    return
      if (matches($foo, "[0-9]"))
      then <data>{$foo}</data>
      else <name>{$foo}</name>
  }</doc>

for $name in $temp/name
return
  <person>{
    $name,
    $name/following-sibling::data[preceding-sibling::name[1]= $name]
  }</person>
</code>```

Title: How to pipe one FLWOR into another?

Body:
Simple FLWOR to get all the data (from what was a spreadsheet):

for $foo  in db:open("foo")
return $foo//text()

gives this type of output:

...
Smallville, XX 12345-1234
Bob
(123) 456-7809
(123) 876-3468
Smallville, XX 12345-1234
Alice
Smallville, XX 12345-1234
Fred
(123) 654-5432
Smallville, XX 12345-1234
...

and another which returns non-numeric data:

for $foo  in db:open("foo")
return $foo//text()[not(matches(., '[0-9]'))]

Which seems to return only the names.  On that assumption, looking to trigger closing tags on a <person> and opening a new <person>, like:

<person>
<name>a</name>
<data>123</data>
<data>345</data>
<data>123 main st</data>
</person>

<person>
...
</person>

Or something like that.  Only really looking to seperate individuals on the assumption that there aren't numerals in their name, and then creating some sort of entity in XML.

Just so long as each time a "name" is found that triggers closing tags and then "starting" a new person.  Not at all sure of the standard lingo here.

Body:
The following creates a temporary XML structure, then iterates through each of the name elements, creating a person with the name and it's following-sibling::data elements.

let $temp :=
  <doc>{
    for $foo in db:open("foo")
    return
      if (matches($foo, "[0-9]"))
      then <data>{$foo}</data>
      else <name>{$foo}</name>
  }</doc>

for $name in $temp/name
return
  <person>{
    $name,
    $name/following-sibling::data[preceding-sibling::name[1]= $name]
  }</person>


问:
What is a Transaction in Spring Framework?
I have been reading about @EnableTransactionManagement and then @Transactional annotations which ensures that say if a transaction involves 3 DAO operations and the 3rd fails then the first 2 also rolls back. Also, it helps when concurrent threads are accessing the same method/class. However, I could not understand what exactly a Transaction is? </p>

<p>I have assumed from the numerous answers on StackOverflow and other places that it is an operation when data is manipulated in the Db from the Spring Boot application. Am I correct?
I could not find any question on STF that asks this question. </p>

答:
Yes you are correct. See this answer for a good explanation What is a database transaction?.

From the Spring point of view, the @Transactional annotation will create an AOP point cut around your method. What this essentially does, is makes sure that any DB related queries that are executed within your method, are wrapped into a Transaction and executed as a single unit of work.

Body:
I have been reading about @EnableTransactionManagement and then @Transactional annotations which ensures that say if a transaction involves 3 DAO operations and the 3rd fails then the first 2 also rolls back. Also, it helps when concurrent threads are accessing the same method/class. However, I could not understand what exactly a Transaction is?

I have assumed from the numerous answers on StackOverflow and other places that it is an operation when data is manipulated in the Db from the Spring Boot application. Am I correct?
I could not find any question on STF that asks this question.


问:
Trying to press CRTL+T with Watir
I am building a simple script to open up a browser window with 2 different tabs. Unfortunately, the 'send_keys' function is not working when I want to use CRTL+T.

Here is my script:

```<code>require 'watir'
require 'webdrivers'
browser = Watir::Browser.new
browser.goto("http://www.google.com")
sleep(5)
browser.send_keys ([:control, 't'])
sleep(10)
</code>```

Does anyone have an idea, how I can fix this?

答:
Chromedriver no longer supports opening tabs via Ctrl+T - see https://bugs.chromium.org/p/chromedriver/issues/detail?id=903.

You could open a new tab by executing JavaScript:

```<code>browser.execute_script('window.open();')
</code>```

Title: Trying to press CRTL+T with Watir

Body:
I am building a simple script to open up a browser window with 2 different tabs. Unfortunately, the 'send_keys' function is not working when I want to use CRTL+T.

Here is my script:

require 'watir'
require 'webdrivers'
browser = Watir::Browser.new
browser.goto("http://www.google.com")
sleep(5)
browser.send_keys ([:control, 't'])
sleep(10)

Does anyone have an idea, how I can fix this?

Body:
Chromedriver no longer supports opening tabs via Ctrl+T - see https://bugs.chromium.org/p/chromedriver/issues/detail?id=903.

You could open a new tab by executing JavaScript:

browser.execute_script('window.open();')


问:
How to display dead-letter messages in Azure CLI
Currently we use Service Bus Explorer to connect to our Service Bus Namespace and manage our dead letters. However as this is a third party tool it's been asked that we do not use this anymore as there is a lot of sensitive data being pulled from the dead letters.

We do not get many dead letter messages in the queues so we thought it would be great if we can view the payload of a dead letter directly in Azure CLI or Powershell. I have looked around online and can't seem to find anything in regards to viewing payloads in CLI. Everything seems to recommend using Service Bus Explorer for viewing payloads.

Any help on this would be greatly appreciated.

答:
Looking at both latest Azure PowerShell Cmdlets (v6.13.0) and Azure CLI, it seems that the functionality you're looking for is not available. The functionality available at both places are for managing Azure Service Bus control plane and not the data plane.

Regarding Service Bus Explorer, even though it's a 3rd party tool, it's an open source tool and you can see what exactly it does. Furthermore, it's a desktop tool so the tool directly communicates with your Service Bus.

However if using Service Bus Explorer is not an option, I guess you're left with writing code using any available SDKs.


问:
.Find() in VBA returns empty string every time I open the Excel file
I have a .Find() function in VBA that I use thought macro. Happends that every time I open the Excel File and run as first the macro with the .Find() function gives me

Run-time error 91: Object variable or With block variable not set

But the strange thing is that, if I open my Excel File and run the other Macros first, when I run this problematic Macro it just works!

This is my code:

```<code>Option Explicit

Sub findMyCode()

    Dim valore2 As String
    Dim cell2 As Range
    Dim cellAppoggio2 As Range
    Dim cellAppoggio3 As Range
    Dim valoreFinale As String
    Dim stringaConcatena As String
    Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("COMPOSIZIONE_AREE")

    Dim stringCodiceCella As String
    Dim stringDesignazioneCella As String

    valore2 = "T0" & Worksheets("CODICI").ComboBox3.Value

    Set cell2 = ws.Range("C3:EZ3").Find(valore2, Lookat:=xlPart) ' It just sets my **cell2** empty, meanwhile if I run the other Macro first, this like works!

    Set cellAppoggio2 = cell2.Offset(0, 1)

    ws.Range(cellAppoggio2.Address).EntireColumn.Insert

End sub()
</code>```

I hope I was clean as possible, if there is something missing or unclear I will update my question.

Thank you in advance.

答:
Since I found out what was the problem, I would like to post it, so maybe would be helpful also for future users.

This was the line of code that was wrong

```<code>Set cell2 = ws.Range("C3:EZ3").Find(valore2, Lookat:=xlPart))
</code>```

And this is the right one

```<code>Set cell2 = Worksheets("COMPOSIZIONE_AREE").Range("A3:GA3").Find(What:=Trim(valore2), LookIn:=xlValues, Lookat:=xlPart).
</code>```

All I did was to Trim() the value so I make sure that there are not spaces in the actual value and LookIn:=xlValues to make sure that .Find() is searching for values that are not formulas or other things.

Body:
I have a .Find() function in VBA that I use thought macro. Happends that every time I open the Excel File and run as first the macro with the .Find() function gives me

Run-time error 91: Object variable or With block variable not set

But the strange thing is that, if I open my Excel File and run the other Macros first, when I run this problematic Macro it just works!

This is my code:

Option Explicit

Sub findMyCode()

    Dim valore2 As String
    Dim cell2 As Range
    Dim cellAppoggio2 As Range
    Dim cellAppoggio3 As Range
    Dim valoreFinale As String
    Dim stringaConcatena As String
    Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("COMPOSIZIONE_AREE")

    Dim stringCodiceCella As String
    Dim stringDesignazioneCella As String

    valore2 = "T0" & Worksheets("CODICI").ComboBox3.Value

    Set cell2 = ws.Range("C3:EZ3").Find(valore2, Lookat:=xlPart) ' It just sets my **cell2** empty, meanwhile if I run the other Macro first, this like works!

    Set cellAppoggio2 = cell2.Offset(0, 1)

    ws.Range(cellAppoggio2.Address).EntireColumn.Insert

End sub()

I hope I was clean as possible, if there is something missing or unclear I will update my question.

Thank you in advance.

Body:
Since I found out what was the problem, I would like to post it, so maybe would be helpful also for future users.

This was the line of code that was wrong

Set cell2 = ws.Range("C3:EZ3").Find(valore2, Lookat:=xlPart))

And this is the right one

Set cell2 = Worksheets("COMPOSIZIONE_AREE").Range("A3:GA3").Find(What:=Trim(valore2), LookIn:=xlValues, Lookat:=xlPart).

All I did was to Trim() the value so I make sure that there are not spaces in the actual value and LookIn:=xlValues to make sure that .Find() is searching for values that are not formulas or other things.


问:
How to convert a string (json with scape chars) to dynamic object?
Good day everyone, I'm trying to convert a string that looks like this:

"{\"Estado\":true,\"Token\":\"3D16C8D8-058C-4FA7-AEA2-1A764A083B72\",\"Nombre\":\"Agente COV\"}"

If I do a quick inspection when the code is running, it looks like this:

After applying the following line of code:

```<code>var Datos = JsonConvert.DeserializeObject<dynamic>(Resultado);
</code>```

It returns the object with two curly braces

```<code>{{"Estado": true, "Token": "3D16C8D8-058C-4FA7-AEA2-1A764A083B72", "Nombre": "Agente COV"}}
</code>```

How can I avoid those two curly braces after converting the string to dynamic object?

I need to use it like this at the end:

```<code>var foo = Datos.Token.Value;
</code>```

Thank you very much for your help.

答:
You can first parse your json with

```<code>dynamic Datos = JObject.Parse(yourjson);
</code>```

and retrieve the value by

```<code>var foo = Datos.Token
</code>```

Note - JObject is from newtonsoft

Body:
Good day everyone, I'm trying to convert a string that looks like this:

"{\"Estado\":true,\"Token\":\"3D16C8D8-058C-4FA7-AEA2-1A764A083B72\",\"Nombre\":\"Agente COV\"}"

If I do a quick inspection when the code is running, it looks like this:

After applying the following line of code:

var Datos = JsonConvert.DeserializeObject<dynamic>(Resultado);

It returns the object with two curly braces

{{"Estado": true, "Token": "3D16C8D8-058C-4FA7-AEA2-1A764A083B72", "Nombre": "Agente COV"}}

How can I avoid those two curly braces after converting the string to dynamic object?

I need to use it like this at the end:

var foo = Datos.Token.Value;

Thank you very much for your help.

Body:
You can first parse your json with

dynamic Datos = JObject.Parse(yourjson);

and retrieve the value by

var foo = Datos.Token

Note - JObject is from newtonsoft


问:
Subset sum Problem
recently I became interested in the subset-sum problem which is finding a zero-sum subset in a superset. I found some solutions on SO, in addition, I came across a particular solution which uses the dynamic programming approach. I translated his solution in python based on his qualitative descriptions. I'm trying to optimize this for larger lists which eats up a lot of my memory. Can someone recommend optimizations or other techniques to solve this particular problem? Here's my attempt in python:</p>

```<code>import random
from time import time
from itertools import product

time0 = time()

# create a zero matrix of size a (row), b(col)
def create_zero_matrix(a,b):
    return [[0]*b for x in xrange(a)]

# generate a list of size num with random integers with an upper and lower bound
def random_ints(num, lower=-1000, upper=1000):
    return [random.randrange(lower,upper+1) for i in range(num)]

# split a list up into N and P where N be the sum of the negative values and P the sum of the positive values.
# 0 does not count because of additive identity
def split_sum(A):
    N_list = []
    P_list = []
    for x in A:
        if x < 0:
            N_list.append(x)
        elif x > 0:
            P_list.append(x)
    return [sum(N_list), sum(P_list)]

# since the column indexes are in the range from 0 to P - N
# we would like to retrieve them based on the index in the range N to P
# n := row, m := col
def get_element(table, n, m, N):
    if n < 0:
        return 0
    try:
        return table[n][m - N]
    except:
        return 0

# same definition as above
def set_element(table, n, m, N, value):
    table[n][m - N] = value

# input array
#A = [1, -3, 2, 4]
A = random_ints(200)

[N, P] = split_sum(A)

# create a zero matrix of size m (row) by n (col)
#
# m := the number of elements in A
# n := P - N + 1 (by definition N <= s <= P)
#
# each element in the matrix will be a value of either 0 (false) or 1 (true)
m = len(A)
n = P - N + 1;
table = create_zero_matrix(m, n)

# set first element in index (0, A[0]) to be true
# Definition: Q(1,s) := (x1 == s). Note that index starts at 0 instead of 1.
set_element(table, 0, A[0], N, 1)

# iterate through each table element
#for i in xrange(1, m): #row
#    for s in xrange(N, P + 1): #col
for i, s in product(xrange(1, m), xrange(N, P + 1)):
    if get_element(table, i - 1, s, N) or A[i] == s or get_element(table, i - 1, s - A[i], N):
        #set_element(table, i, s, N, 1)
        table[i][s - N] = 1

# find zero-sum subset solution
s = 0
solution = []
for i in reversed(xrange(0, m)):
    if get_element(table, i - 1, s, N) == 0 and get_element(table, i, s, N) == 1:
        s = s - A[i]
        solution.append(A[i])

print "Solution: ",solution

time1 = time()

print "Time execution: ", time1 - time0
</code>```

答:
, 1st eye catch

```<code>def split_sum(A):
  N_list = 0
  P_list = 0
  for x in A:
    if x < 0:
        N_list+=x
    elif x > 0:
        P_list+=x
  return [N_list, P_list]
</code>```

Some advices:

Try to use 1D list and use bitarray to reduce memory footprint at minimum (http://pypi.python.org/pypi/bitarray) so you will just change get / set functon. This should reduce your memory footprint by at lest 64 (integer in list is pointer to integer whit type so it can be factor 3*32)

Avoid using try - catch, but figure out proper ranges at beginning, you might found out that you will gain huge speed.

Title: Subset sum Problem

Body:
recently I became interested in the subset-sum problem which is finding a zero-sum subset in a superset. I found some solutions on SO, in addition, I came across a particular solution which uses the dynamic programming approach. I translated his solution in python based on his qualitative descriptions. I'm trying to optimize this for larger lists which eats up a lot of my memory. Can someone recommend optimizations or other techniques to solve this particular problem? Here's my attempt in python:

import random
from time import time
from itertools import product

time0 = time()

# create a zero matrix of size a (row), b(col)
def create_zero_matrix(a,b):
    return [[0]*b for x in xrange(a)]

# generate a list of size num with random integers with an upper and lower bound
def random_ints(num, lower=-1000, upper=1000):
    return [random.randrange(lower,upper+1) for i in range(num)]

# split a list up into N and P where N be the sum of the negative values and P the sum of the positive values.
# 0 does not count because of additive identity
def split_sum(A):
    N_list = []
    P_list = []
    for x in A:
        if x < 0:
            N_list.append(x)
        elif x > 0:
            P_list.append(x)
    return [sum(N_list), sum(P_list)]

# since the column indexes are in the range from 0 to P - N
# we would like to retrieve them based on the index in the range N to P
# n := row, m := col
def get_element(table, n, m, N):
    if n < 0:
        return 0
    try:
        return table[n][m - N]
    except:
        return 0

# same definition as above
def set_element(table, n, m, N, value):
    table[n][m - N] = value

# input array
#A = [1, -3, 2, 4]
A = random_ints(200)

[N, P] = split_sum(A)

# create a zero matrix of size m (row) by n (col)
#
# m := the number of elements in A
# n := P - N + 1 (by definition N <= s <= P)
#
# each element in the matrix will be a value of either 0 (false) or 1 (true)
m = len(A)
n = P - N + 1;
table = create_zero_matrix(m, n)

# set first element in index (0, A[0]) to be true
# Definition: Q(1,s) := (x1 == s). Note that index starts at 0 instead of 1.
set_element(table, 0, A[0], N, 1)

# iterate through each table element
#for i in xrange(1, m): #row
#    for s in xrange(N, P + 1): #col
for i, s in product(xrange(1, m), xrange(N, P + 1)):
    if get_element(table, i - 1, s, N) or A[i] == s or get_element(table, i - 1, s - A[i], N):
        #set_element(table, i, s, N, 1)
        table[i][s - N] = 1

# find zero-sum subset solution
s = 0
solution = []
for i in reversed(xrange(0, m)):
    if get_element(table, i - 1, s, N) == 0 and get_element(table, i, s, N) == 1:
        s = s - A[i]
        solution.append(A[i])

print "Solution: ",solution

time1 = time()

print "Time execution: ", time1 - time0

Body:
, 1st eye catch

def split_sum(A):
  N_list = 0
  P_list = 0
  for x in A:
    if x < 0:
        N_list+=x
    elif x > 0:
        P_list+=x
  return [N_list, P_list]

Some advices:

Try to use 1D list and use bitarray to reduce memory footprint at minimum (http://pypi.python.org/pypi/bitarray) so you will just change get / set functon. This should reduce your memory footprint by at lest 64 (integer in list is pointer to integer whit type so it can be factor 3*32)

Avoid using try - catch, but figure out proper ranges at beginning, you might found out that you will gain huge speed.


问:
PHPUnit Laravel : How to Unit Test custom Exception Handler?
I try to make unit test of a custom Exception Handler class (located in app/Exceptions/Handler.php), but i don't know how to do it ...

I don't know how to raise an exception with my mock Request.

Is someone can help me ?

Here is the "render" method :

```<code>/**
 * @param \Illuminate\Http\Request $request
 * @param Exception $e
 * @return \Illuminate\Http\RedirectResponse|\Symfony\Component\HttpFoundation\Response
 */
public function render($request, Exception $e)
{
    // This will replace our 404 response with
    // a JSON response.
    if ($e instanceof ModelNotFoundException &&
        $request->wantsJson()) {
        Log::error('render ModelNotFoundException');
        return response()->json([
            'error' => 'Resource not found'
        ], 404);
    }
    if ($e instanceof TokenMismatchException) {
        Log::error('render TokenMismatchException');
        return new RedirectResponse('login');
    }
    if ($e instanceof QueryException) {
        Log::error('render QueryException', ['exception' => $e]);
        return response()->view('errors.500', ['exception' => $e, 'QueryException' => true],500);
    }

    return parent::render($request, $e);
}
</code>```

And this is my test case :

```<code>/**
 * @test
 */
public function renderTokenMismatchException()
{
    $request = $this->createMock(Request::class);
    $request->expects($this->once())->willThrowException(new TokenMismatchException);
    $instance = new Handler($this->createMock(Application::class));
    $class    = new \ReflectionClass(Handler::class);
    $method   = $class->getMethod('render');
    $method->setAccessible(true);
    $expectedInstance = Response::class;
    $this->assertInstanceOf($expectedInstance, $method->invokeArgs($instance, [$request, $this->createMock(Exception::class)]));
}
</code>```

答:
It's not easier do something like </p>

```<code>$request = $this->createMock(Request::class);
$handler = new Handler($this->createMock(Container::class));
$this->assertInstanceOf(
     RedirectResponse::class,
     $handler->render(
           $request,
           $this->createMock(TokenMismatchException::class)
       )
    );
</code>```

Body:
I try to make unit test of a custom Exception Handler class (located in app/Exceptions/Handler.php), but i don't know how to do it ...

I don't know how to raise an exception with my mock Request.

Is someone can help me ?

Here is the "render" method :

/**
 * @param \Illuminate\Http\Request $request
 * @param Exception $e
 * @return \Illuminate\Http\RedirectResponse|\Symfony\Component\HttpFoundation\Response
 */
public function render($request, Exception $e)
{
    // This will replace our 404 response with
    // a JSON response.
    if ($e instanceof ModelNotFoundException &&
        $request->wantsJson()) {
        Log::error('render ModelNotFoundException');
        return response()->json([
            'error' => 'Resource not found'
        ], 404);
    }
    if ($e instanceof TokenMismatchException) {
        Log::error('render TokenMismatchException');
        return new RedirectResponse('login');
    }
    if ($e instanceof QueryException) {
        Log::error('render QueryException', ['exception' => $e]);
        return response()->view('errors.500', ['exception' => $e, 'QueryException' => true],500);
    }

    return parent::render($request, $e);
}

And this is my test case :

/**
 * @test
 */
public function renderTokenMismatchException()
{
    $request = $this->createMock(Request::class);
    $request->expects($this->once())->willThrowException(new TokenMismatchException);
    $instance = new Handler($this->createMock(Application::class));
    $class    = new \ReflectionClass(Handler::class);
    $method   = $class->getMethod('render');
    $method->setAccessible(true);
    $expectedInstance = Response::class;
    $this->assertInstanceOf($expectedInstance, $method->invokeArgs($instance, [$request, $this->createMock(Exception::class)]));
}

Body:
It's not easier do something like

$request = $this->createMock(Request::class);
$handler = new Handler($this->createMock(Container::class));
$this->assertInstanceOf(
     RedirectResponse::class,
     $handler->render(
           $request,
           $this->createMock(TokenMismatchException::class)
       )
    );


问:
Weird PostgreSQL null check behavior for custom types
I am trying to create a function which should map the table row to my custom type and return that as a result. If some column in that table is NULL, then IS NOT NULL check on my custom type does not work! Check the example:

I have a simple custom type:

```<code>CREATE TYPE my_custom_type AS (
  sender VARCHAR(30),
  destination VARCHAR(30),
  count INTEGER
);
</code>```

And a table:

```<code>CREATE TABLE messages (
  id INTEGER PRIMARY KEY,
  sender VARCHAR(30),
  destination VARCHAR(30),
  count INTEGER
);
</code>```

Insert single row for this example:

```<code>INSERT INTO messages VALUES (1, 'sender', 'destination', 100);
</code>```

And now I want to create a function which will return that row as a custom Postgres type:

```<code>CREATE OR REPLACE FUNCTION my_custom_function()
RETURNS my_custom_type AS
$$
DECLARE
    result my_custom_type;
BEGIN

    SELECT sender, destination, count
    FROM messages
    LIMIT 1
    INTO result;

    IF result IS NULL THEN
        RAISE EXCEPTION 'no data';
    END IF;

    RETURN result;

END; $$
    LANGUAGE plpgsql;
</code>```

I get good results when I use this function:

```<code>SELECT * from my_custom_function();
</code>```

But weird things starts to happen when some column is updated to NULL:

```<code>UPDATE messages SET destination = NULL;
</code>```

When I execute the function again, it still returns good results:

But if I change the IS NULL condition to IS NOT NULL condition:

```<code>CREATE OR REPLACE FUNCTION my_custom_function()
RETURNS my_custom_type AS
$$
DECLARE
    result my_custom_type;
BEGIN

    SELECT sender, destination, count
    FROM messages
    LIMIT 1
    INTO result;

    IF result IS NOT NULL THEN
        RETURN result;
    END IF;

    RAISE EXCEPTION 'no data';

END; $$
    LANGUAGE plpgsql;
</code>```

Then I got an error:
ERROR:  no data

Can someone please explain me why this does not work? It makes no sense to me...

答:
A composite type IS NULL if all its elements are NULL, and it IS NOT NULL if all elements are not NULL.

That is required by the SQL standard.

This has unpleasant consequences, for example is x IS NOT NULL not the same as NOT x IS NULL for composite types. Also, two values that both return TRUE for the IS NULL test can be distinct:

```<code>SELECT ROW(NULL, NULL) IS DISTINCT FROM NULL;

 ?column?
══════════
 t
(1 row)
</code>```

The SQL standard clearly didn't do a good job there. Read this thread from the pgsql-hackers list for further edificationconfusion.

Body:
I am trying to create a function which should map the table row to my custom type and return that as a result. If some column in that table is NULL, then IS NOT NULL check on my custom type does not work! Check the example:

I have a simple custom type:

CREATE TYPE my_custom_type AS (
  sender VARCHAR(30),
  destination VARCHAR(30),
  count INTEGER
);

And a table:

CREATE TABLE messages (
  id INTEGER PRIMARY KEY,
  sender VARCHAR(30),
  destination VARCHAR(30),
  count INTEGER
);

Insert single row for this example:

INSERT INTO messages VALUES (1, 'sender', 'destination', 100);

And now I want to create a function which will return that row as a custom Postgres type:

CREATE OR REPLACE FUNCTION my_custom_function()
RETURNS my_custom_type AS
$$
DECLARE
    result my_custom_type;
BEGIN

    SELECT sender, destination, count
    FROM messages
    LIMIT 1
    INTO result;

    IF result IS NULL THEN
        RAISE EXCEPTION 'no data';
    END IF;

    RETURN result;

END; $$
    LANGUAGE plpgsql;

I get good results when I use this function:

SELECT * from my_custom_function();

But weird things starts to happen when some column is updated to NULL:

UPDATE messages SET destination = NULL;

When I execute the function again, it still returns good results:

But if I change the IS NULL condition to IS NOT NULL condition:

CREATE OR REPLACE FUNCTION my_custom_function()
RETURNS my_custom_type AS
$$
DECLARE
    result my_custom_type;
BEGIN

    SELECT sender, destination, count
    FROM messages
    LIMIT 1
    INTO result;

    IF result IS NOT NULL THEN
        RETURN result;
    END IF;

    RAISE EXCEPTION 'no data';

END; $$
    LANGUAGE plpgsql;

Then I got an error:
ERROR:  no data

Can someone please explain me why this does not work? It makes no sense to me...

Body:
A composite type IS NULL if all its elements are NULL, and it IS NOT NULL if all elements are not NULL.

That is required by the SQL standard.

This has unpleasant consequences, for example is x IS NOT NULL not the same as NOT x IS NULL for composite types. Also, two values that both return TRUE for the IS NULL test can be distinct:

SELECT ROW(NULL, NULL) IS DISTINCT FROM NULL;

 ?column?
══════════
 t
(1 row)

The SQL standard clearly didn't do a good job there. Read this thread from the pgsql-hackers list for further edificationconfusion.


问:
C# Converting mixed JSON into an object
Yo Guys,

I'm currently trying to pass some mixed JSON, and was wondering if it was possible to do anything like the following?

```<code>struct example_data
{
    public Dictionary<string, List<string>> information {get; set;}
}

class TestClass
{
    static void Main(string[] args)
    {
        string test_string = @"{'EventSpecificInformation':
                                   {
                                   'measure':''
                                   ,'Long name':'test_name'
                                   ,'Short name':'test_s_name'
                                   ,'Description':''
                                   ,'Status':'Real (Imported)'
                                   ,'Viewers':['Everyone']
                                   ,'Modifiers':['Supervisor only']
                                   ,'calculation':''
                                   }
                               }"

        example_data deserialized_entry = JsonConvert.DeserializeObject<example_data>(test_string)
    }
}
</code>```

As you would expect the above code snippet fails, but I was hoping I could avoid wrapping each JSON entry in a JSON array or having to create a custom JSON reader in C#.

Any advice on the matter would be greatly appreciated.

答:
You can push the results to Dictionary

```<code>string test_string = @"{'EventSpecificInformation':
                        {
                        'measure':''
                        ,'Long name':'test_name'
                        ,'Short name':'test_s_name'
                        ,'Description':''
                        ,'Status':'Real (Imported)'
                        ,'Viewers':['Everyone']
                        ,'Modifiers':['Supervisor only']
                        ,'calculation':''
                        }
                    }".Replace("'", "\"");

var results = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, object>>>(test_string);
</code>```

Title: C# Converting mixed JSON into an object

Body:
Yo Guys,

I'm currently trying to pass some mixed JSON, and was wondering if it was possible to do anything like the following?

struct example_data
{
    public Dictionary<string, List<string>> information {get; set;}
}

class TestClass
{
    static void Main(string[] args)
    {
        string test_string = @"{'EventSpecificInformation':
                                   {
                                   'measure':''
                                   ,'Long name':'test_name'
                                   ,'Short name':'test_s_name'
                                   ,'Description':''
                                   ,'Status':'Real (Imported)'
                                   ,'Viewers':['Everyone']
                                   ,'Modifiers':['Supervisor only']
                                   ,'calculation':''
                                   }
                               }"

        example_data deserialized_entry = JsonConvert.DeserializeObject<example_data>(test_string)
    }
}

As you would expect the above code snippet fails, but I was hoping I could avoid wrapping each JSON entry in a JSON array or having to create a custom JSON reader in C#.

Any advice on the matter would be greatly appreciated.

Body:
You can push the results to Dictionary

string test_string = @"{'EventSpecificInformation':
                        {
                        'measure':''
                        ,'Long name':'test_name'
                        ,'Short name':'test_s_name'
                        ,'Description':''
                        ,'Status':'Real (Imported)'
                        ,'Viewers':['Everyone']
                        ,'Modifiers':['Supervisor only']
                        ,'calculation':''
                        }
                    }".Replace("'", "\"");

var results = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, object>>>(test_string);


问:
How can I select entries for a given weekday using SQL?
I could use this query to select all orders with a date on a monday:

```<code>SELECT * from orders WHERE strftime("%w", date)="1";
</code>```

But as far as I know, this can't be speed up using an index, as for every row strftime has to be calculated.

I could add an additional field with the weekday stored, but I want to avoid it. Is there a solution that makes use of an index or am I wrong and this query actually works fine? (That means it doesn't have to go through every row to calculate the result.)

答: If you want all Mondays ever, you'd need a field or sequential scan. What you could do, is calculate actual dates for example for all Mondays within a year. The condition WHERE date IN ('2009-03-02', '2009-02-23', ...) would use index

OwnerDisplayName: gs

ContentLicense: CC BY-SA 2.5

Body:
I could use this query to select all orders with a date on a monday:

SELECT * from orders WHERE strftime("%w", date)="1";

But as far as I know, this can't be speed up using an index, as for every row strftime has to be calculated.

I could add an additional field with the weekday stored, but I want to avoid it. Is there a solution that makes use of an index or am I wrong and this query actually works fine? (That means it doesn't have to go through every row to calculate the result.)


问:
Ideas to comments better with python
If you're a python coder you may encounter looking for a way to comments your code better on subcategory code. My meaning by the subcategory code is you may have blocks of codes and then again blocks of codes that relate to the previous block. Here is an example (pay  more attention to comments):

```<code># Drink some water to keep your body hydrated:
initialize some parameters

# Choice a glass:
pick up the glass number one
if the glass was dirty:
   wash the dishes  # this would be difficult.

# Pour the glass with water:
while the glass is not filled up:
   pour the glass
</code>```

All I'm saying we are looking for simplicity and when you are in the middle of a code, it's better to know where you are exactly. See the comments again but this time as headers:

```<code># h1
initialize some parameters

# h2:
pick up the glass number one
if the glass was dirty:
   wash the dishes

# h2:
while the glass is not filled up:
   pour the glass
</code>```

so when you see the comment h2s it would be convenient to know that this part of code is subcode of h1:

I used to make the first letter capital as h1 for comments, and the following code blocks that are related are not capital. Let's wipe out the codes and just focus on the comments:

```<code># Drink some water to keep your body hydrated:
... line of codes ...

# choice a glass:
... line of codes ...

# pour the glass with water:
... line of codes ...
</code>```

There are some pros and coins with that:

pros:

Easy to use.

coins:

It doesn't come to the mind right of way.

If you have more subcategory code this doesn't work.

So I was like "why don't I share this with others to see what they think and what they prefer or use", said it to myself.

答:
So I was checking something like

```<code># H1 comment
# h2 comment
 + easy
 + looks normal in the code.
 - maybe taken up as a mistake
 - only 2 category

# h1 comment
# -- h2 comment
# -- -- h3 comment

# h1 comment
#   h2 comment
#     h3 comment
- looks weird in the code.
</code>```

Note we usually use functions and classed. and this has quit rear use. But they would have a use.
I still prefer -- for the reasons (or no coins).

Title: Ideas to comments better with python

Body:
If you're a python coder you may encounter looking for a way to comments your code better on subcategory code. My meaning by the subcategory code is you may have blocks of codes and then again blocks of codes that relate to the previous block. Here is an example (pay  more attention to comments):

# Drink some water to keep your body hydrated:
initialize some parameters

# Choice a glass:
pick up the glass number one
if the glass was dirty:
   wash the dishes  # this would be difficult.

# Pour the glass with water:
while the glass is not filled up:
   pour the glass

All I'm saying we are looking for simplicity and when you are in the middle of a code, it's better to know where you are exactly. See the comments again but this time as headers:

# h1
initialize some parameters

# h2:
pick up the glass number one
if the glass was dirty:
   wash the dishes

# h2:
while the glass is not filled up:
   pour the glass

so when you see the comment h2s it would be convenient to know that this part of code is subcode of h1:

I used to make the first letter capital as h1 for comments, and the following code blocks that are related are not capital. Let's wipe out the codes and just focus on the comments:

# Drink some water to keep your body hydrated:
... line of codes ...

# choice a glass:
... line of codes ...

# pour the glass with water:
... line of codes ...

There are some pros and coins with that:

pros:

Easy to use.

coins:

It doesn't come to the mind right of way.

If you have more subcategory code this doesn't work.

So I was like "why don't I share this with others to see what they think and what they prefer or use", said it to myself.

Body:
So I was checking something like

# H1 comment
# h2 comment
 + easy
 + looks normal in the code.
 - maybe taken up as a mistake
 - only 2 category

# h1 comment
# -- h2 comment
# -- -- h3 comment

# h1 comment
#   h2 comment
#     h3 comment
- looks weird in the code.

Note we usually use functions and classed. and this has quit rear use. But they would have a use.
I still prefer -- for the reasons (or no coins).


问:
Get value from jsonelement's jsonarray with Java and Gson
I have this code:

```<code>try {
    URL url = new URL("My api url");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.addRequestProperty("User-Agent", "MyUserAgent");

    InputStream inputStream = connection.getInputStream();
    InputStreamReader reader = new InputStreamReader(inputStream);

    JsonElement element = new JsonParser().parse(reader);

    System.out.println(element);
} catch (IOException e) {
    e.printStackTrace();
}
</code>```

My api response:

```<code>[
  {
    "id": 12345,
    "name": "1.0"
  }
]
</code>```

I need to get the name parameter as a string, but I don't know how to do it.

答:
I think you are looking for :

```<code>JsonElement name = element.getAsJsonArray().get(0).getAsJsonObject().get("name");
</code>```

Output

```<code>"1.0"
</code>```

Or to get the value of name :

```<code>String name = element.getAsJsonArray().get(0).getAsJsonObject().get("name").getAsString();
</code>```

Output

```<code>1.0
</code>```

Body:
I have this code:

try {
    URL url = new URL("My api url");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.addRequestProperty("User-Agent", "MyUserAgent");

    InputStream inputStream = connection.getInputStream();
    InputStreamReader reader = new InputStreamReader(inputStream);

    JsonElement element = new JsonParser().parse(reader);

    System.out.println(element);
} catch (IOException e) {
    e.printStackTrace();
}

My api response:

[
  {
    "id": 12345,
    "name": "1.0"
  }
]

I need to get the name parameter as a string, but I don't know how to do it.

Body:
I think you are looking for :

JsonElement name = element.getAsJsonArray().get(0).getAsJsonObject().get("name");

Output

"1.0"

Or to get the value of name :

String name = element.getAsJsonArray().get(0).getAsJsonObject().get("name").getAsString();

Output

1.0


问:
Convert string to Array passed as Argument to AjaxManager
I am trying to post an array from jQuery on an .aspx page to a method in the codebehind using Telerik AjaxManager.  The problem I am having is converting the string to a list or even an array using C#.  The string (after using Json.stringify in jQuery) looks like this:

```<code>string zoneString = "[[1,[["Ticket Core.AFE"],["Ticket Core.CompanyName"]]],[2,[["Ticket Core.CompanyCity"],["Ticket Core.CompanyState"]]]]"
</code>```

I tried to Deserialize like this:

```<code>List<ZoneInfo> zones = JsonConvert.DeserializeObject<List<ZoneInfo>>(zonesString);
</code>```

But that produces the following error:

Message=Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'COGS.Web.Modules.Admin.ReportWizard+ZoneInfo' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
  To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
  Path '[0]', line 1, position 2.

Here is the client-side code:

```<code> var zones = [];

        for (var i = 1; i <= zoneCount; i++)
        {
            var o = $.data(listBox, i.toString());
            if(o != undefined)
            {
                var items = [];
                var a = o._array;
                //pull the key/value
                for (x = 0; x < a.length; x++)
                {
                    var item = a[x];
                    var value = item.get_value();

                    items.push([value]);

                }
            zones.push([i, items]);

            }
        }
        jsonZones = JSON.stringify(zones);
        var ajaxManager = $find("<%= ((RadAjaxManager)this.Page.Master.FindControl("RadAjaxManager1")).ClientID %>");
        ajaxManager.ajaxRequest('CREATEREPORT|' + jsonZones + '|' + tid);
</code>```

Here is the server-side code:

```<code>protected void AjaxMgr_AjaxRequest(object sender, AjaxRequestEventArgs e)
    {
        LoggerBA.Log(DB_Context, Path.GetFileName(Request.ServerVariables["SCRIPT_NAME"]), MethodBase.GetCurrentMethod().Name, UtilityBA.LoggerLevel.Info, "IsPostBack: " + IsPostBack.ToString());

        string[] args = e.Argument.Split('|');
        string sCommand = args[0];

        switch (sCommand.ToUpper())
        {
            case "CREATEREPORT":
                string zonesString = args[1];
                List<ZoneInfo> zones = JsonConvert.DeserializeObject<List<ZoneInfo>>(zonesString);
                var template = args[2];
                string[] zone = new string[zones.Count];

                break;
        }
        InitializeWizard();
    }
</code>```

Any assistance is greatly appreciated

答: May not be the answer but JSON.stringify accepts a second parameter where you can specify the keys in the key value pairs: JSON.stringify(data, ['key1', 'key2', 'key3']). Alternatively that second parameter could be a function but I think that is more useful for direct character replacement.

Body:
I am trying to post an array from jQuery on an .aspx page to a method in the codebehind using Telerik AjaxManager.  The problem I am having is converting the string to a list or even an array using C#.  The string (after using Json.stringify in jQuery) looks like this:

string zoneString = "[[1,[["Ticket Core.AFE"],["Ticket Core.CompanyName"]]],[2,[["Ticket Core.CompanyCity"],["Ticket Core.CompanyState"]]]]"

I tried to Deserialize like this:

List<ZoneInfo> zones = JsonConvert.DeserializeObject<List<ZoneInfo>>(zonesString);

But that produces the following error:

Message=Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'COGS.Web.Modules.Admin.ReportWizard+ZoneInfo' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
  To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
  Path '[0]', line 1, position 2.

Here is the client-side code:

 var zones = [];

        for (var i = 1; i <= zoneCount; i++)
        {
            var o = $.data(listBox, i.toString());
            if(o != undefined)
            {
                var items = [];
                var a = o._array;
                //pull the key/value
                for (x = 0; x < a.length; x++)
                {
                    var item = a[x];
                    var value = item.get_value();

                    items.push([value]);

                }
            zones.push([i, items]);

            }
        }
        jsonZones = JSON.stringify(zones);
        var ajaxManager = $find("<%= ((RadAjaxManager)this.Page.Master.FindControl("RadAjaxManager1")).ClientID %>");
        ajaxManager.ajaxRequest('CREATEREPORT|' + jsonZones + '|' + tid);

Here is the server-side code:

protected void AjaxMgr_AjaxRequest(object sender, AjaxRequestEventArgs e)
    {
        LoggerBA.Log(DB_Context, Path.GetFileName(Request.ServerVariables["SCRIPT_NAME"]), MethodBase.GetCurrentMethod().Name, UtilityBA.LoggerLevel.Info, "IsPostBack: " + IsPostBack.ToString());

        string[] args = e.Argument.Split('|');
        string sCommand = args[0];

        switch (sCommand.ToUpper())
        {
            case "CREATEREPORT":
                string zonesString = args[1];
                List<ZoneInfo> zones = JsonConvert.DeserializeObject<List<ZoneInfo>>(zonesString);
                var template = args[2];
                string[] zone = new string[zones.Count];

                break;
        }
        InitializeWizard();
    }

Any assistance is greatly appreciated