问:
Silverlight control view image with zoom in/out?
I wanna use an image viewer control in silverlight with feature zoom in/out the image, I found "MultiScaleImage" control that accept source as Xml file, which is can be created by "Deep Zoom Composer" program (install this program: import the images then expose and export: the program will generate the images and the "dzc_output.xml" file for you).

My Question is: I have a images(paths) that comes from the Database, how can I create the xml file at runtime without using the "Deep Zoom Composer" program!!!, I think this is impossible :(

Sooooooo anybody knows a silverlight control that I can use to view image with zoom in/out?????????

答:
In the Deep Zoom Composer program files directory, you will find DeepZoomTools.dll

Use that to generate your images and XML,


来源: stackexchange

问:
ITMS-90037 The Info.plist file is missing or could not be parsed while app store submittion
When I upload the app into app store, I got the mail from itunese connect with the following issue

We have discovered one or more issues with your recent delivery for "***". To process your delivery, the following issues must be corrected:
  This bundle is invalid - The Info.plist file is missing or could not be parsed. Please check it for embedded control characters.
  Once these issues have been corrected, you can then redeliver the corrected binary.

I have checked the info.plist file path, created the new plist , but I couldn't succeed. have any idea ?

答:
I encountered this issue and determined it was yet another xcode program bug that caused (or otherwise allowed) it.

The cause was that the Xcode editor allowed a control character to be included in the target > General > Build (a field you must update for each release). I probably typed a backspace or something there, or the Xcode UI stuck some random control character in there.

Option 1: Delete / Re-add Recent Changes

A quick thing to try (that would have worked for me) would  be to delete then re-add anything you've recently done that affected the Info.plist file.

Option 2: Use VI in your terminal on Info.plist

I went to launchpad > terminal then used the commands "cd documents", "li", and repeated that until I got into the directory containing the info.plist file. They I typed "vi Info.plist" and it was obvious the bad character because it was a different color.

Then I repeated the archive operation, and then repeated the validation operation, and this time, it worked.

Shame on Apple for yet another Xcode bug.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Jupyter Labs: "RuntimeError: npm dependencies failed to install" When Building
I'm new to using Anaconda and recently installed jupyter labs on my computer. However, any time I try to build on my local Jupyter Labs instance I get the following error:

Code run in jupyter labs terminal:

```<code>PS C:\Users\briakeit> jupyter lab build
</code>```

Output:

```<code>[LabBuildApp] JupyterLab 1.2.5
[LabBuildApp] Building in C:\Users\briakeit\AnacondaFiles\share\jupyter\lab
[LabBuildApp] Building jupyterlab assets (build:prod:minimize)
An error occured.
RuntimeError: npm dependencies failed to install
See the log file for details:  C:\Users\briakeit\AppData\Local\Temp\jupyterlab-debug-0b5ejkfm.log
</code>```

Log file:

```<code>[LabBuildApp] Building in C:\Users\briakeit\AnacondaFiles\share\jupyter\lab
[LabBuildApp] Yarn configuration loaded.
[LabBuildApp] Node v13.7.0

[LabBuildApp] Building jupyterlab assets (build:prod:minimize)
[LabBuildApp] > node C:\Users\briakeit\AnacondaFiles\lib\site-packages\jupyterlab\staging\yarn.js install --non-interactive
[LabBuildApp] yarn install v1.15.2
[1/5] Validating package.json...
[2/5] Resolving packages...
[3/5] Fetching packages...
info There appears to be trouble with your network connection. Retrying...
info There appears to be trouble with your network connection. Retrying...
info There appears to be trouble with your network connection. Retrying...
info There appears to be trouble with your network connection. Retrying...
error An unexpected error occurred: "https://registry.yarnpkg.com/@jupyterlab/application-extension/-/application-extension-1.2.1.tgz: read ECONNRESET".
info If you think this is a bug, please open a bug report with the information provided in "C:\\Users\\briakeit\\AnacondaFiles\\share\\jupyter\\lab\\staging\\yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.

[LabBuildApp] npm dependencies failed to install
[LabBuildApp] Traceback (most recent call last):

[LabBuildApp]   File "C:\Users\briakeit\AnacondaFiles\lib\site-packages\jupyterlab\debuglog.py", line 47, in debug_logging
    yield

[LabBuildApp]   File "C:\Users\briakeit\AnacondaFiles\lib\site-packages\jupyterlab\labapp.py", line 98, in start
    command=command, app_options=app_options)

[LabBuildApp]   File "C:\Users\briakeit\AnacondaFiles\lib\site-packages\jupyterlab\commands.py", line 459, in build
    command=command, clean_staging=clean_staging)

[LabBuildApp]   File "C:\Users\briakeit\AnacondaFiles\lib\site-packages\jupyterlab\commands.py", line 660, in build
    raise RuntimeError(msg)

[LabBuildApp] RuntimeError: npm dependencies failed to install

[LabBuildApp] Exiting application: JupyterLab
</code>```

This happens anytime I try using this command (e.g. after installing anew extension). I have npm v6.4.1, nodejs v10.13.0, and yarn v1.22.0 installed in this environment according to conda. I'm running Jupyter lab 1.2.6.

Any feedback, suggestions or help would be greatly appreciated.

答:
Not sure if you've fixed it, if not you may try the solutions below.

info There appears to be trouble with your network connection. Retrying...

This is a yarn related error that seems to suggest something wrong with your network. This can happen if the yarn was trying to connect via a proxy. You can try the following if this is the case.

```<code>npm config rm proxy
npm config rm https-proxy
</code>```

It can also happen if your network is too slow. You can try increasing Yarn timeout.

```<code>yarn add <yourPackage> --network-timeout 100000
</code>```

Source: https://github.com/yarnpkg/yarn/issues/4890

Body:
I'm new to using Anaconda and recently installed jupyter labs on my computer. However, any time I try to build on my local Jupyter Labs instance I get the following error:

Code run in jupyter labs terminal:

PS C:\Users\briakeit> jupyter lab build

Output:

[LabBuildApp] JupyterLab 1.2.5
[LabBuildApp] Building in C:\Users\briakeit\AnacondaFiles\share\jupyter\lab
[LabBuildApp] Building jupyterlab assets (build:prod:minimize)
An error occured.
RuntimeError: npm dependencies failed to install
See the log file for details:  C:\Users\briakeit\AppData\Local\Temp\jupyterlab-debug-0b5ejkfm.log

Log file:

[LabBuildApp] Building in C:\Users\briakeit\AnacondaFiles\share\jupyter\lab
[LabBuildApp] Yarn configuration loaded.
[LabBuildApp] Node v13.7.0

[LabBuildApp] Building jupyterlab assets (build:prod:minimize)
[LabBuildApp] > node C:\Users\briakeit\AnacondaFiles\lib\site-packages\jupyterlab\staging\yarn.js install --non-interactive
[LabBuildApp] yarn install v1.15.2
[1/5] Validating package.json...
[2/5] Resolving packages...
[3/5] Fetching packages...
info There appears to be trouble with your network connection. Retrying...
info There appears to be trouble with your network connection. Retrying...
info There appears to be trouble with your network connection. Retrying...
info There appears to be trouble with your network connection. Retrying...
error An unexpected error occurred: "https://registry.yarnpkg.com/@jupyterlab/application-extension/-/application-extension-1.2.1.tgz: read ECONNRESET".
info If you think this is a bug, please open a bug report with the information provided in "C:\\Users\\briakeit\\AnacondaFiles\\share\\jupyter\\lab\\staging\\yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.

[LabBuildApp] npm dependencies failed to install
[LabBuildApp] Traceback (most recent call last):

[LabBuildApp]   File "C:\Users\briakeit\AnacondaFiles\lib\site-packages\jupyterlab\debuglog.py", line 47, in debug_logging
    yield

[LabBuildApp]   File "C:\Users\briakeit\AnacondaFiles\lib\site-packages\jupyterlab\labapp.py", line 98, in start
    command=command, app_options=app_options)

[LabBuildApp]   File "C:\Users\briakeit\AnacondaFiles\lib\site-packages\jupyterlab\commands.py", line 459, in build
    command=command, clean_staging=clean_staging)

[LabBuildApp]   File "C:\Users\briakeit\AnacondaFiles\lib\site-packages\jupyterlab\commands.py", line 660, in build
    raise RuntimeError(msg)

[LabBuildApp] RuntimeError: npm dependencies failed to install

[LabBuildApp] Exiting application: JupyterLab

This happens anytime I try using this command (e.g. after installing anew extension). I have npm v6.4.1, nodejs v10.13.0, and yarn v1.22.0 installed in this environment according to conda. I'm running Jupyter lab 1.2.6.

Any feedback, suggestions or help would be greatly appreciated.

Body:
Not sure if you've fixed it, if not you may try the solutions below.

info There appears to be trouble with your network connection. Retrying...

This is a yarn related error that seems to suggest something wrong with your network. This can happen if the yarn was trying to connect via a proxy. You can try the following if this is the case.

npm config rm proxy
npm config rm https-proxy

It can also happen if your network is too slow. You can try increasing Yarn timeout.

yarn add <yourPackage> --network-timeout 100000

Source: https://github.com/yarnpkg/yarn/issues/4890


问:
Angular 2 filter/search list
I'm looking for the angular 2 way to do this.

I simply have a list of items, and I want to make an input whos job is to filter the list.

```<code><md-input placeholder="Item name..." [(ngModel)]="name"></md-input>

<div *ngFor="let item of items">
{{item.name}}
</div>
</code>```

What's the actual way of doing this in Angular 2? Does that requires a pipe?

答:
try this
html code

```<code><md-input #myInput placeholder="Item name..." [(ngModel)]="name"></md-input>

<div *ngFor="let item of filteredItems | search: name">
   {{item.name}}
</div>
</code>```

use search pipe

```<code>import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'search'
})
export class SearchPipe implements PipeTransform {

  transform(value: any, args?: any): any {

    if(!value)return null;
    if(!args)return value;

    args = args.toLowerCase();

    return value.filter(function(item){
        return JSON.stringify(item).toLowerCase().includes(args);
    });
}

}
</code>```

Title: Angular 2 filter/search list

Body:
I'm looking for the angular 2 way to do this.

I simply have a list of items, and I want to make an input whos job is to filter the list.

<md-input placeholder="Item name..." [(ngModel)]="name"></md-input>

{{item.name}}

What's the actual way of doing this in Angular 2? Does that requires a pipe?

Body:
try this
html code

<md-input #myInput placeholder="Item name..." [(ngModel)]="name"></md-input>

<div *ngFor="let item of filteredItems | search: name">
   {{item.name}}
</div>

use search pipe

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'search'
})
export class SearchPipe implements PipeTransform {

  transform(value: any, args?: any): any {

    if(!value)return null;
    if(!args)return value;

    args = args.toLowerCase();

    return value.filter(function(item){
        return JSON.stringify(item).toLowerCase().includes(args);
    });
}

}


问:
Swagger codegen to Java Spring generates incorrect file response entity from OpenAPI component of binary format
I am using swagger-codegen-maven-plugin to generate  Spring interface from OpenAPI file (OpenAPI 3.0.2)

```<code><groupId>io.swagger.codegen.v3</groupId>
<artifactId>swagger-codegen-maven-plugin</artifactId>
<version>3.0.14</version>
</code>```

The response of one rest API should be PDF file

```<code>components:
    schemas:
        contractFile:
            type: string
            format: binary
</code>```

Generated Java REST interface then contains the following method

```<code>default ResponseEntity<File> getContract(@ApiParam(value = "File to download",required=true) @PathVariable("uid") String uid) {
...
}
</code>```

File class represents the path to the filesystem, but I don't have the file on the filesystem, just bytes in java memory and I don't want to save them as the file to disk.

I want getContract to return some StreamResource or some other representation of file from Stream/bytes in memory. Is it possible this via swagger-codegen-maven-plugin or some other option?

答:
maybe you could try something like this

```<code>/myendpoint:
    get:
      tags: [myendpint]
      summary: my cool endpoint
      operationId: getStuff
      x-custom-return-type: 'java.something.stream.Stream'
</code>```

than use mustache and specify it in mustache file with vendor extensions

```<code>ResponseEntity<{{#responseWrapper}}{{
    .}}<{{/responseWrapper}}{{>returnTypes}}{{#vendorExtensions.x-custom-return-type}}
</code>```

I use that for interface API and maybe somehow you could use it in your case too

Body:
I am using swagger-codegen-maven-plugin to generate  Spring interface from OpenAPI file (OpenAPI 3.0.2)

<groupId>io.swagger.codegen.v3</groupId>
<artifactId>swagger-codegen-maven-plugin</artifactId>
<version>3.0.14</version>

The response of one rest API should be PDF file

components:
    schemas:
        contractFile:
            type: string
            format: binary

Generated Java REST interface then contains the following method

default ResponseEntity<File> getContract(@ApiParam(value = "File to download",required=true) @PathVariable("uid") String uid) {
...
}

File class represents the path to the filesystem, but I don't have the file on the filesystem, just bytes in java memory and I don't want to save them as the file to disk.

I want getContract to return some StreamResource or some other representation of file from Stream/bytes in memory. Is it possible this via swagger-codegen-maven-plugin or some other option?

Body:
maybe you could try something like this

/myendpoint:
    get:
      tags: [myendpint]
      summary: my cool endpoint
      operationId: getStuff
      x-custom-return-type: 'java.something.stream.Stream'

than use mustache and specify it in mustache file with vendor extensions

ResponseEntity<{{#responseWrapper}}{{
    .}}<{{/responseWrapper}}{{>returnTypes}}{{#vendorExtensions.x-custom-return-type}}

I use that for interface API and maybe somehow you could use it in your case too


问:
Listview TwoWay Binding With ObservableCollection
:::::::::: ObservableCollection ::::::::::

```<code>    ObservableCollection<Friend> Friends = new ObservableCollection<Friend> ( );
</code>```

:::::::::: InitializeFriends ::::::::::

```<code>        private void InitializeFriends ( )
        {
            JsonObject _JsonObject = Process . FacebookClient . Get ( "/me/friends" ) as JsonObject;

            if ( _JsonObject != null )
            {
                JsonArray _JsonArray = _JsonObject [ "data" ] as JsonArray;
                foreach ( JsonObject Friend in _JsonArray )
                {
                    Friends . Add ( new Friend ( ) { Name = Friend [ "name" ] . ToString ( ) } );
                }
            }
        }
</code>```

:::::::::: Friend ::::::::::

```<code>    public class Friend
    {
        public string Name { get; set; }
        public Conversation Chat { get; set; }
        public BitmapImage Image { get; set; }
    }
</code>```

:::::::::: ListView ::::::::::

```<code>        <ListView Name="Panel"
              Width="Auto"
              Margin="0,200,0,0"
              HorizontalAlignment="Stretch"
              VerticalAlignment="Stretch"
              Background="{x:Null}"
              BorderThickness="0"
              ItemsSource="{Binding Path=Friends,
                                    Mode=TwoWay}"
              ScrollViewer.HorizontalScrollBarVisibility="Disabled"
              SelectionMode="Single">
        <ListView.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </ListView.ItemsPanel>
        <ListView.View>
            <GridView ColumnHeaderContainerStyle="{StaticResource hiddenStyle}">
                <GridViewColumn Width="200" DisplayMemberBinding="{Binding Path=Name}" />
                <GridViewColumn Width="100">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <Image Width="30"
                                       Height="30"
                                       Source="{Binding Path=Image}" />
                            </StackPanel>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>
</code>```

List View Not Binding May Be Binding But Not Updating ?!!!

There is something WRONG

答:
Your Friends collection needs to be exposed as a public property, i.e.:

```<code>private readonly ObservableCollection<Friend> _friends = new ObservableCollection<Friend>();
public ObservableCollection<Friend> Friends { get { return _friends; } }
</code>```

Body:
:::::::::: ObservableCollection ::::::::::

    ObservableCollection<Friend> Friends = new ObservableCollection<Friend> ( );

:::::::::: InitializeFriends ::::::::::

        private void InitializeFriends ( )
        {
            JsonObject _JsonObject = Process . FacebookClient . Get ( "/me/friends" ) as JsonObject;

            if ( _JsonObject != null )
            {
                JsonArray _JsonArray = _JsonObject [ "data" ] as JsonArray;
                foreach ( JsonObject Friend in _JsonArray )
                {
                    Friends . Add ( new Friend ( ) { Name = Friend [ "name" ] . ToString ( ) } );
                }
            }
        }

:::::::::: Friend ::::::::::

    public class Friend
    {
        public string Name { get; set; }
        public Conversation Chat { get; set; }
        public BitmapImage Image { get; set; }
    }

:::::::::: ListView ::::::::::

        <ListView Name="Panel"
              Width="Auto"
              Margin="0,200,0,0"
              HorizontalAlignment="Stretch"
              VerticalAlignment="Stretch"
              Background="{x:Null}"
              BorderThickness="0"
              ItemsSource="{Binding Path=Friends,
                                    Mode=TwoWay}"
              ScrollViewer.HorizontalScrollBarVisibility="Disabled"
              SelectionMode="Single">
        <ListView.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </ListView.ItemsPanel>
        <ListView.View>
            <GridView ColumnHeaderContainerStyle="{StaticResource hiddenStyle}">
                <GridViewColumn Width="200" DisplayMemberBinding="{Binding Path=Name}" />
                <GridViewColumn Width="100">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <Image Width="30"
                                       Height="30"
                                       Source="{Binding Path=Image}" />
                            </StackPanel>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>

List View Not Binding May Be Binding But Not Updating ?!!!

There is something WRONG

Body:
Your Friends collection needs to be exposed as a public property, i.e.:

private readonly ObservableCollection<Friend> _friends = new ObservableCollection<Friend>();
public ObservableCollection<Friend> Friends { get { return _friends; } }


问:
Regex to match all groups between more than one space
I've got a string

198.21      543                   G110P0GHTT     SAW         GHA + DBA       11998

And I'd like to match all groups of the string between spaces. So far I've come up with (?<=\s)(.*?)(?=\s) which matches all but the first group. Additionally, this does not count the GHA + DBA as a group. What can I add to this to ensure it includes the first record as well as anything MORE than one space

答:
You don't need to use look arounds here. Just use this regex to match a non-whitespace string or substring separated by a single space:

```<code>\S+(?:\s\S+)*
</code>```

RegEx Demo

RegEx Details:

\S+: Match 1+ non-space characters

(?:\s\S+)*: Match 0 or more non-space substring separated by a single space.

Body:
You don't need to use look arounds here. Just use this regex to match a non-whitespace string or substring separated by a single space:

\S+(?:\s\S+)*

RegEx Demo

RegEx Details:

\S+: Match 1+ non-space characters

(?:\s\S+)*: Match 0 or more non-space substring separated by a single space.


问:
Does an Angular client UI run entirely in the browser
Encountered some Angular developers who were discussing Angular's server side code.
This surprised me.

Does Angular have server side code?

I was under the impression that all the code ( libraries, routing, components) all of it, is downloaded to the client.

My question is explicitly this :   As you navigate through different routes, controllers, etc. in an Angular application,  does the browser make repeated calls to the node web server.

Webapi calls are obviously calls to some server somewhere. That's not part of this question.

My impression from the limited amount of work I have done in angular(v8) is that it is entirely browser side.

This may be a simple question, but I have been unable to find a definitive answer.

答:
As you navigate through different routes, controllers, etc. in an Angular application, does the browser make repeated calls to the node web server.

The answer is in fact yes.
Try stopping the ng serve process and see what happens.
Take a look at DevControls network tab as you navigate the app.

My question was bolded, and is not ambiguously worded.  The angular front end in fact makes repeated calls to the web server to download components.

This is surprising to me, but seems fairly clear given my observations.

I believe that these are merely downloads. Angular does not download the entire app when you hit the homepage.
I still contest the conversation I overheard that there is server side code 'running'. I have encountered nothing to support that. But that's another question...


问:
Date Conversion from value in C#
Does anyone possibly recognize the following value "40195.315752" as a date?  I need to convert/format this value-based date to a System.DateTime object, but don't understand it's format.

Thanks.

答:
enjoy it:

```<code>DateTime.FromOADate(40195.315752).ToLongDateString()
</code>```

and to convert it to DateTime

```<code>DateTime MyDateTime = DateTime.FromOADate(40195.315752);
</code>```

It means Sunday,January 17 2010

Title: Date Conversion from value in C#

Body:
enjoy it:

DateTime.FromOADate(40195.315752).ToLongDateString()

and to convert it to DateTime

DateTime MyDateTime = DateTime.FromOADate(40195.315752);

It means Sunday,January 17 2010


问:
Get max of 2 objects
I am very new to C++. Is there a way I could compare 2 objects of the same class and return the bigger one?

This is some pseudo code to illustrate the idea

```<code>HashMap biggerObject = std::max( obj1, obj2,
                             []( HashMap &a, HashMap &b )
                             {
                                 return a.size() < b.size();
                             } );
</code>```

And how could I write HashMap in a way so that it knows how to compare itself?

答:
Just use:

```<code>HashMap biggerObject = std::max(obj1, obj2,
                                    [](const HashMap &a, const HashMap &b) {
                                        return a.size() < b.size();
                                    });
</code>```

You can also overload the operator of your own class: Here's a simple example:

```<code>#include<iostream>

struct HashMap {
    int value = 10;
    std::string whatever;

    bool operator<(const HashMap &rhs) const {
        // your logics..
        return value < rhs.value;
    }
};

int main() {

    HashMap map1, map2;
    map1.value = 100;
    map2.value = 10;

    const auto &val = std::max(map1, map2);

    std::cout << val.value << std::endl;

}
</code>```

Title: Get max of 2 objects

Body:
I am very new to C++. Is there a way I could compare 2 objects of the same class and return the bigger one?

This is some pseudo code to illustrate the idea

HashMap biggerObject = std::max( obj1, obj2,
                             []( HashMap &a, HashMap &b )
                             {
                                 return a.size() < b.size();
                             } );

And how could I write HashMap in a way so that it knows how to compare itself?

Body:
Just use:

HashMap biggerObject = std::max(obj1, obj2,
                                    [](const HashMap &a, const HashMap &b) {
                                        return a.size() < b.size();
                                    });

You can also overload the operator of your own class: Here's a simple example:

#include<iostream>

struct HashMap {
    int value = 10;
    std::string whatever;

    bool operator<(const HashMap &rhs) const {
        // your logics..
        return value < rhs.value;
    }
};

int main() {

    HashMap map1, map2;
    map1.value = 100;
    map2.value = 10;

    const auto &val = std::max(map1, map2);

    std::cout << val.value << std::endl;

}


问:
Powershell command to format the usb drive even though a file was opened
I need to format a USB drive even though the file was opened. Need to have a powershell command which need to execute using java program.

Currently, we are using, powershell.exe format /FS:FAT32 E: /Q /v:Volume Name

The above command works fine, but it does not format when any of files from USB drive oepned. I wanted to force format eventhough the files were opened.

Can anyone help if any powershell command exists which would force format?

答:
According to the Microsoft docs for the format command (Format | Microsoft Docs) what you want can be indirectly solved by using the /x parameter which

Causes the volume to dismount, if necessary, before it is formatted. Any open handles to the volume will no longer be valid.


问:
I get a "Specified method is not supported" error when i try to use ExcelDataReader to upload file to database
I've written a method, BulkCopy, to upload my Excel file to SQL Server database table. I am trying to unit test this and it fails each time with "System.NotSupportedException : Specified method is not supported".

If someone could have a look it would be much appreciated.

Kind regards,

Emmett

```<code>    public static void BulkCopy(string inputFilePath, string tableName)
    {

        System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
        var stream = File.Open(inputFilePath, FileMode.Open, FileAccess.Read);
        using (var reader = ExcelReaderFactory.CreateReader(stream))
        {
            using (var bulkCopy = new SqlBulkCopy(ConnectionString))
            {

                bulkCopy.EnableStreaming = true;
                bulkCopy.DestinationTableName = tableName;
                reader.Read();
                var cols = Enumerable.Range(0, reader.FieldCount).Select(i => reader.GetValue(i)).ToArray();
                foreach (var col in cols)
                {
                    var column = cols.GetValue(0).ToString();

                    if (column.Trim() == "Column 1")
                    {
                        bulkCopy.ColumnMappings.Add(column, "Column 1");
                    }

                    if (column.Trim() == "Column 2")
                    {
                        bulkCopy.ColumnMappings.Add(column, "Column 2");
                    }

                    if (column.Trim() == "Column 3")
                    {
                        bulkCopy.ColumnMappings.Add(column, "Column 3");
                    }

                //continued for column mappings...

                }

                bulkCopy.WriteToServer(reader);
            }
            Console.WriteLine("Copy data to database done (DataReader).");
        }
    }
</code>```

答:
You need to change the way it's setting the column mappings. If you delete them it will work. In the example link you posted they are using GetName to get the columns. I tried that and it doesn't work for some reason. I get a GetOrdinal error. That's the same error that is coming from your code: ExcelDataReader.ExcelDataReader`2.GetOrdinal(String name).

Not sure how pretty it is, but it works.

```<code>public static void BulkCopy(string inputFilePath, string tableName)
    {

        System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
        var stream = File.Open(inputFilePath, FileMode.Open, FileAccess.Read);
        using (var reader = ExcelReaderFactory.CreateReader(stream))
        {
            using (var bulkCopy = new SqlBulkCopy(ConnectionString))
            {

                bulkCopy.EnableStreaming = true;
                bulkCopy.DestinationTableName = tableName;
                reader.Read();
                var cols = Enumerable.Range(0, reader.FieldCount).Select(i => reader.GetValue(i)).ToArray();
                foreach (var col in cols)
                {
                     if (cols[i].ToString() == "Column 1")
                     {
                          bulkCopy.ColumnMappings.Add(i, "Column 1");
                     }

                     if (cols[i].ToString() == "Column 2")
                     {
                          bulkCopy.ColumnMappings.Add(i, "Column 2");
                     }

                     if (cols[i].ToString() == "Column 3")
                     {
                          bulkCopy.ColumnMappings.Add(i, "Column 3");
                     }

                    //continued for column mappings...

                }

                bulkCopy.WriteToServer(reader);
            }
            Console.WriteLine("Copy data to database done (DataReader).");
        }
    }
</code>```

Body:
I've written a method, BulkCopy, to upload my Excel file to SQL Server database table. I am trying to unit test this and it fails each time with "System.NotSupportedException : Specified method is not supported".

If someone could have a look it would be much appreciated.

Kind regards,

Emmett

    public static void BulkCopy(string inputFilePath, string tableName)
    {

        System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
        var stream = File.Open(inputFilePath, FileMode.Open, FileAccess.Read);
        using (var reader = ExcelReaderFactory.CreateReader(stream))
        {
            using (var bulkCopy = new SqlBulkCopy(ConnectionString))
            {

                bulkCopy.EnableStreaming = true;
                bulkCopy.DestinationTableName = tableName;
                reader.Read();
                var cols = Enumerable.Range(0, reader.FieldCount).Select(i => reader.GetValue(i)).ToArray();
                foreach (var col in cols)
                {
                    var column = cols.GetValue(0).ToString();

                    if (column.Trim() == "Column 1")
                    {
                        bulkCopy.ColumnMappings.Add(column, "Column 1");
                    }

                    if (column.Trim() == "Column 2")
                    {
                        bulkCopy.ColumnMappings.Add(column, "Column 2");
                    }

                    if (column.Trim() == "Column 3")
                    {
                        bulkCopy.ColumnMappings.Add(column, "Column 3");
                    }

                //continued for column mappings...

                }

                bulkCopy.WriteToServer(reader);
            }
            Console.WriteLine("Copy data to database done (DataReader).");
        }
    }

Body:
You need to change the way it's setting the column mappings. If you delete them it will work. In the example link you posted they are using GetName to get the columns. I tried that and it doesn't work for some reason. I get a GetOrdinal error. That's the same error that is coming from your code: ExcelDataReader.ExcelDataReader`2.GetOrdinal(String name).

Not sure how pretty it is, but it works.

public static void BulkCopy(string inputFilePath, string tableName)
    {

        System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
        var stream = File.Open(inputFilePath, FileMode.Open, FileAccess.Read);
        using (var reader = ExcelReaderFactory.CreateReader(stream))
        {
            using (var bulkCopy = new SqlBulkCopy(ConnectionString))
            {

                bulkCopy.EnableStreaming = true;
                bulkCopy.DestinationTableName = tableName;
                reader.Read();
                var cols = Enumerable.Range(0, reader.FieldCount).Select(i => reader.GetValue(i)).ToArray();
                foreach (var col in cols)
                {
                     if (cols[i].ToString() == "Column 1")
                     {
                          bulkCopy.ColumnMappings.Add(i, "Column 1");
                     }

                     if (cols[i].ToString() == "Column 2")
                     {
                          bulkCopy.ColumnMappings.Add(i, "Column 2");
                     }

                     if (cols[i].ToString() == "Column 3")
                     {
                          bulkCopy.ColumnMappings.Add(i, "Column 3");
                     }

                    //continued for column mappings...

                }

                bulkCopy.WriteToServer(reader);
            }
            Console.WriteLine("Copy data to database done (DataReader).");
        }
    }


问:
How to find best params of leader model in automl h2o python
I trained h2o automl and got a leader model with satisfying metrics. I want to retrain the model periodically but without using checkpoint. So, I guess all I need are the best parameters of the leader model to run it manually. I know automlmodels.leader.params but it gives a list of all parameters tried. How can I get the best ones as found in the leaderboard?</p>

答:
supporting DaveJay's answer.

As mentioned in the following URL, get_params helps https://0xdata.atlassian.net/browse/PUBDEV-6396

Unfortunately, it does not work for getting parameters for AutoML leader. I added comment on the board https://0xdata.atlassian.net/browse/PUBDEV-6396 and would re-open this issue if I do not get a response in some time.


问:
How to store dynamic input in maps
In Go, how should I put dynamic/user input in maps

func main() {
    mapp := make(map[int]string)
    for i := 0; i < 5; i++ {
        fmt.Scanf("%d %s", &mapp[i], &mapp[i])
    }
    fmt.Print(mapp)
}
```

答:
You can't create a key-value pair on a map like that.

What you can do, is store the input in variables, and then create a map key-value pair with the input. Like this:

```<code>for i := 0 ; i < 5 ; i++ {
    var num int
    var text string
    fmt.Scanf("%d %s",&num,&text)
    mapp[num] = text
}
</code>```

Title: How to store dynamic input in maps

Body:
You can't create a key-value pair on a map like that.

What you can do, is store the input in variables, and then create a map key-value pair with the input. Like this:

for i := 0 ; i < 5 ; i++ {
    var num int
    var text string
    fmt.Scanf("%d %s",&num,&text)
    mapp[num] = text
}


问:
How to read and edit the word file in laravel?
How do I read a Word file and be able to edit it in Laravel (phpWord)? I imagine a scenario where the user can open, modify and then save the file.</p>

答:
This is what you are looking for, I think: https://github.com/PHPOffice/PHPWord

Cheers,

Niklas


问:
php Curl clicked links
I need any link that has a "a href=" tag when clicked to be received via curl. I can't hard code these links as they are from a dynamic site so could be anything. How would I achieve this?

Thanks

Edit: Let me explain more. I have an app on my pc that uses a web front end. It catalogs files and gives yo options to rename delete etc. I want to add a public view however if I put it as is online then anyone can delete rename files. If I curl the pages I can remove the menu bars and editing options through the use of a different css. That part all works. The only part that isn't working is if I click on a link on the page it directs me back to the original link address and that defeats the point as the menu bars are back. I need it to curl the clicked links. Hope that makes more sense..

Here is my code that fetches the original link and curls that and changes the css to point to my own css. It points the java script to the original as I dont need to change that. I now need to make the "a href" links on the page when clicked be called by curl and not go to the original destination

```<code><?php

$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, 'http://192.168.0.14:8081/home/');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$curl_response = curl_exec($ch);
curl_close($ch);

//Change link url

$link = $curl_response;

$linkgo = '/sickbeard_public';
$linkfind = 'href="';
$linkreplace = 'href="' . $linkgo ;

$link = str_replace($linkfind, $linkreplace, $link);

//Change js url
$js = $link;

$jsgo = 'http://192.168.0.14:8081';
$jsfind = 'src="';
$jsreplace = 'src="' . $jsgo ;

$js = str_replace($jsfind, $jsreplace, $js);

//Fix on page link errors
$alink = $js;
$alinkgo = 'http://192.168.0.14:8081/';
$alinkfind = 'a href="/sickbeard_public/';
$alinkreplace = 'a href="' . $alinkgo ;

$alink = str_replace($alinkfind, $alinkreplace, $alink);

//Echo page back
echo $alink;

?>
</code>```

答:
You could grab all the URLs using a regular expression</p>

```<code>// insert general warning about how parsing HTML using regex is evil :-)
preg_match('/href="([^"]+)"/', $html, $matches);
$urls = array_slice($matches, 1);

// Now just loop through the array and fetch the URLs with cUrl...
</code>```

Title: php Curl clicked links

Body:
I need any link that has a "a href=" tag when clicked to be received via curl. I can't hard code these links as they are from a dynamic site so could be anything. How would I achieve this?

Thanks

Edit: Let me explain more. I have an app on my pc that uses a web front end. It catalogs files and gives yo options to rename delete etc. I want to add a public view however if I put it as is online then anyone can delete rename files. If I curl the pages I can remove the menu bars and editing options through the use of a different css. That part all works. The only part that isn't working is if I click on a link on the page it directs me back to the original link address and that defeats the point as the menu bars are back. I need it to curl the clicked links. Hope that makes more sense..

Here is my code that fetches the original link and curls that and changes the css to point to my own css. It points the java script to the original as I dont need to change that. I now need to make the "a href" links on the page when clicked be called by curl and not go to the original destination

<?php

$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, 'http://192.168.0.14:8081/home/');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$curl_response = curl_exec($ch);
curl_close($ch);

//Change link url

$link = $curl_response;

$linkgo = '/sickbeard_public';
$linkfind = 'href="';
$linkreplace = 'href="' . $linkgo ;

$link = str_replace($linkfind, $linkreplace, $link);

//Change js url
$js = $link;

$jsgo = 'http://192.168.0.14:8081';
$jsfind = 'src="';
$jsreplace = 'src="' . $jsgo ;

$js = str_replace($jsfind, $jsreplace, $js);

//Fix on page link errors
$alink = $js;
$alinkgo = 'http://192.168.0.14:8081/';
$alinkfind = 'a href="/sickbeard_public/';
$alinkreplace = 'a href="' . $alinkgo ;

$alink = str_replace($alinkfind, $alinkreplace, $alink);

//Echo page back
echo $alink;

?>

Body:
You could grab all the URLs using a regular expression

// insert general warning about how parsing HTML using regex is evil :-)
preg_match('/href="([^"]+)"/', $html, $matches);
$urls = array_slice($matches, 1);

// Now just loop through the array and fetch the URLs with cUrl...


问:
how to map an array in an object map to another array
i have an object

```<code>{
    "parent_entity_id": 394,
    "display_name": "Test POI",
    "event_code_prefix": "TEST",
    "address": null,
    "logo_url": "https://storage.png",
    "is_active": true,
    "identifier": [
        {
            "model_id": 10,
            "entity_id": 575,
            "is_active": true,
            "valid_value": [
                {
                    "type": "MACID",
                    "value": "AC:23:3F:23:8D:A1"
                }
            ],
            "display_name": "Test BLE Beacon 1",
            "is_mandatory": true,
            "entity_type_key": "BTBACID"
        },
        {
            "model_id": null,
            "entity_id": 576,
            "is_active": true,
            "valid_value": [
                {
                    "type": "GEOFENCE_CIRCLE",
                    "value": {
                        "latitude": 24.155678,
                        "longitude": 54.425175,
                        "radius_in_meters": 500
                    }
                }
            ],
            "display_name": "Test tower gate 1",
            "is_mandatory": true,
            "entity_type_key": "GIS"
        }
    ]
}
</code>```

I need to map the array valid values from the object to another array with condition.
if Ble the map to valid_value_BLE array and if GIS to valid_values_GIS

答:
try this

```<code>arr1=Obj.identifier.map(z => {
  if(z.entity_type_key=='GIS'){z['valid_value_GIS']=z.valid_value;
  }else{z['valid_value_BLE']=z.valid_value;}
  delete z.valid_value;  return z;
});
</code>```

https://codepen.io/vkv88/pen/LYVZdwz?editors=0010

Body:
i have an object

{
    "parent_entity_id": 394,
    "display_name": "Test POI",
    "event_code_prefix": "TEST",
    "address": null,
    "logo_url": "https://storage.png",
    "is_active": true,
    "identifier": [
        {
            "model_id": 10,
            "entity_id": 575,
            "is_active": true,
            "valid_value": [
                {
                    "type": "MACID",
                    "value": "AC:23:3F:23:8D:A1"
                }
            ],
            "display_name": "Test BLE Beacon 1",
            "is_mandatory": true,
            "entity_type_key": "BTBACID"
        },
        {
            "model_id": null,
            "entity_id": 576,
            "is_active": true,
            "valid_value": [
                {
                    "type": "GEOFENCE_CIRCLE",
                    "value": {
                        "latitude": 24.155678,
                        "longitude": 54.425175,
                        "radius_in_meters": 500
                    }
                }
            ],
            "display_name": "Test tower gate 1",
            "is_mandatory": true,
            "entity_type_key": "GIS"
        }
    ]
}

I need to map the array valid values from the object to another array with condition.
if Ble the map to valid_value_BLE array and if GIS to valid_values_GIS

Body:
try this

arr1=Obj.identifier.map(z => {
  if(z.entity_type_key=='GIS'){z['valid_value_GIS']=z.valid_value;
  }else{z['valid_value_BLE']=z.valid_value;}
  delete z.valid_value;  return z;
});

https://codepen.io/vkv88/pen/LYVZdwz?editors=0010


问:
Entity Framework and ASP.NET Core UOW Repository pattern
I have an ASP.NET Core application, which is structured in three layers i.e.:

Data access layer (Entity Framework)

Business logic layer (Unit of work, repository pattern)

ASP.NET MVC web application

Until now, I have been used to developing applications in .NET Framework, however, moving to Core I notice that there are significant differences.

To start off, I used a database first approach to initialize my entity framework. Here I used the scaffolding method, and it worked just fine.

However, I noticed that app.config is no longer present in any of my libraries and that my connectionstring has been moved to a method in my source code, i.e.:

```<code>protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//connection stuff here
}
</code>```

Compared to using EF in .net framework, I would normally utilize the connectionstring, which resides in my app.config i.e.:

```<code>public EFClass(string connString)
        : base(connString)
    {
</code>```

This can no longer be done, and i'm forced to utilize the appsettings.json in my MVC web application, which sort of mess up the idea of loosely coupling my application.

Optimally, how would I get to my connectionstring in my dataaccess layer, when I don't have my app.config anymore?

Additionally, I've read several places that the UOW repository pattern is sort of redundant, as DbContext in .NET Core applications can be used for DI as well? Should I get rid of my UOW and just inject my DbContext directly into my repositories?

My question may be wrong, in the sense that I probably miss some major fundamentals here, but you are welcome to point me in a better direction.

答:
The interface and class of your UoW class need to receive the connection string on constructor.
On ConfigureServices method, inside of your Startup class, you get the connection string of appsettings.json.  </p>

```<code> public void ConfigureServices(IServiceCollection services)
 {
     services.AddScoped<IUnitOfWork>(x => new UnitOfWork(strConnection));
 }
</code>```

Body:
I have an ASP.NET Core application, which is structured in three layers i.e.:

Data access layer (Entity Framework)

Business logic layer (Unit of work, repository pattern)

ASP.NET MVC web application

Until now, I have been used to developing applications in .NET Framework, however, moving to Core I notice that there are significant differences.

To start off, I used a database first approach to initialize my entity framework. Here I used the scaffolding method, and it worked just fine.

However, I noticed that app.config is no longer present in any of my libraries and that my connectionstring has been moved to a method in my source code, i.e.:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//connection stuff here
}

Compared to using EF in .net framework, I would normally utilize the connectionstring, which resides in my app.config i.e.:

public EFClass(string connString)
        : base(connString)
    {

This can no longer be done, and i'm forced to utilize the appsettings.json in my MVC web application, which sort of mess up the idea of loosely coupling my application.

Optimally, how would I get to my connectionstring in my dataaccess layer, when I don't have my app.config anymore?

Additionally, I've read several places that the UOW repository pattern is sort of redundant, as DbContext in .NET Core applications can be used for DI as well? Should I get rid of my UOW and just inject my DbContext directly into my repositories?

My question may be wrong, in the sense that I probably miss some major fundamentals here, but you are welcome to point me in a better direction.

Body:
The interface and class of your UoW class need to receive the connection string on constructor.
On ConfigureServices method, inside of your Startup class, you get the connection string of appsettings.json.

 public void ConfigureServices(IServiceCollection services)
 {
     services.AddScoped<IUnitOfWork>(x => new UnitOfWork(strConnection));
 }


问:
Correct way to catch errors with async/await
I have application where I need to wait for each HTTP response. So the calls need to be executed in specific order and some of them require response of another service. I thought that it will be possible to catch error in one place - root/main method where error will be propagated. But it seems to be not working like that... Is it even possible? Or does it mean that I need to use try/catch block in each method where I'm using await?? Let's assume this pseudo code:

user.wrapper.service.ts

```<code>// Class which wraps real UserService with HTTP calls
export class UserWrapperService {
   async getUserById(id: number): Promise<UserResponse> {
      return await this.userService.getUser(id).toPromise() as UserResponse;
   }

   async getUserDetails(userName: string): Promise<UserDetailsResponse> {
      return await this.userService.getUserDetails(userName).toPromise() as UserDetailsResponse;
   }
}
</code>```

main-component.ts

```<code>export class MainComponent implements OnInit {

   async ngOnInit() {
      try {
         await this.retrieveDetailsForEachUser();
      } catch (e) {
        this.router.navigate(['/error']);
      }
   }

   private async retrieveDetailsForEachUser(): Promise<any> {
      for (let counter = 0; counter < 10; counter++) {
         const user = await this.userWrapperService.getUserById(counter);
         console.log(user);
         const details = await this.userWrapperService.getUserDetails(user.name);
         // use this details in another service with bigger method, where is present more async/await
      }
   }
}
</code>```

I was hoping that if something will go wrong in methods of UserWrapperService the error will be propagated and catched in MainComponent. Or at least that it is somehow possible to achieve. But it seems that I need to throw exception and try/catch to all async methods which are awaiting for something. Am I right? Is there any prettier way to accomplish this?

答:
You have to use the try-catch block when using async-await to handle errors and you are doing it correctly. The only thing which seems wrong to me is that you are awaiting in the service method while returning the result of async call, which will return you a Promise<Promise<UserResponse>, which is not the expected behavior.

Modify your code to remove the await keyword in service class as below and await only in the component class.

user.wrapper.service.ts

```<code>export class UserWrapperService {
   async getUserById(id: number): Promise<UserResponse> {
      return this.userService.getUser(id).toPromise();
   }

   async getUserDetails(userName: string): Promise<UserDetailsResponse> {
      return this.userService.getUserDetails(userName).toPromise();
   }
}
</code>```

Now you will be able to catch errors, handle them and navigate to error page as required in the main-component class.

Body:
I have application where I need to wait for each HTTP response. So the calls need to be executed in specific order and some of them require response of another service. I thought that it will be possible to catch error in one place - root/main method where error will be propagated. But it seems to be not working like that... Is it even possible? Or does it mean that I need to use try/catch block in each method where I'm using await?? Let's assume this pseudo code:

user.wrapper.service.ts

// Class which wraps real UserService with HTTP calls
export class UserWrapperService {
   async getUserById(id: number): Promise<UserResponse> {
      return await this.userService.getUser(id).toPromise() as UserResponse;
   }

   async getUserDetails(userName: string): Promise<UserDetailsResponse> {
      return await this.userService.getUserDetails(userName).toPromise() as UserDetailsResponse;
   }
}

main-component.ts

export class MainComponent implements OnInit {

   async ngOnInit() {
      try {
         await this.retrieveDetailsForEachUser();
      } catch (e) {
        this.router.navigate(['/error']);
      }
   }

   private async retrieveDetailsForEachUser(): Promise<any> {
      for (let counter = 0; counter < 10; counter++) {
         const user = await this.userWrapperService.getUserById(counter);
         console.log(user);
         const details = await this.userWrapperService.getUserDetails(user.name);
         // use this details in another service with bigger method, where is present more async/await
      }
   }
}

I was hoping that if something will go wrong in methods of UserWrapperService the error will be propagated and catched in MainComponent. Or at least that it is somehow possible to achieve. But it seems that I need to throw exception and try/catch to all async methods which are awaiting for something. Am I right? Is there any prettier way to accomplish this?

Body:
You have to use the try-catch block when using async-await to handle errors and you are doing it correctly. The only thing which seems wrong to me is that you are awaiting in the service method while returning the result of async call, which will return you a Promise<Promise<UserResponse>, which is not the expected behavior.

Modify your code to remove the await keyword in service class as below and await only in the component class.

user.wrapper.service.ts

export class UserWrapperService {
   async getUserById(id: number): Promise<UserResponse> {
      return this.userService.getUser(id).toPromise();
   }

   async getUserDetails(userName: string): Promise<UserDetailsResponse> {
      return this.userService.getUserDetails(userName).toPromise();
   }
}

Now you will be able to catch errors, handle them and navigate to error page as required in the main-component class.


问:
Group views in ConstraintLayout to treat them as a single view
I need to apply some constraints to a group of views in ConstraintLayout. I want to group these views and continue editing while the layout designer in Android studio treats them as a single view. Is there a way to do so without actually wrapping the views with a ViewGroup (another layout)? If such a wrapper is necessary, maybe there is a wrapper layout that comes with ConstraintLayout and allows to group objects without creating heavy layouts like RelativeLayout?

答:
You can use height 0dp and organize views vertically.

in relative layout we can use layout below and above like

```<code><FrameLayout
        android:id="@+id/frame_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/bottom_nav"
        android:layout_below="@+id/toolbar"
        />
</code>```

In constraint layout giving height is compulsory so you can give 0 height.
and then you can set your view below other views like this

```<code><android.support.v4.view.ViewPager
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/tablayout" />
</code>```

you can use constraintTop_toBottomOf and constraintBottom_toTopOf  properties to adjust your view to above or below of other.
thanks

Body:
You can use height 0dp and organize views vertically.

in relative layout we can use layout below and above like

<FrameLayout
        android:id="@+id/frame_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/bottom_nav"
        android:layout_below="@+id/toolbar"
        />

In constraint layout giving height is compulsory so you can give 0 height.
and then you can set your view below other views like this

<android.support.v4.view.ViewPager
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/tablayout" />

you can use constraintTop_toBottomOf and constraintBottom_toTopOf  properties to adjust your view to above or below of other.
thanks


问:
Need plots of two line graphs on same chart in R
Using R, I have two line graphs each in their own chart. I need them both on the same chart. I have looked at other stackoverflow inquiries but did not find one that matches my need.

In my two-line chart I need graphs for BA and careerBA on the vertical axis and the G field as the horizontal axis. Each G value (e.g., 1) has a matching BA and careerBA.

```<code>BA <- c(0.317, 0.298, 0.273, 0.280, 0.252, 0.204, 0.181, 0.241, 0.227, 0.233, 0.080, 0.285)

careerBA <- c(0.279, 0.280, 0.245, 0.253, 0.276, 0.247, 0.265, 0.243, 0.274, 0.255, 0.236, 0.287)

G <- c(1,2,3,4,5,6,7,8,9,10,11,12)

df <- data.frame(BA, careerBA, G)
df

library(ggplot2)
p1 <- ggplot() + geom_line(aes(y = BA, x = G, color = "red"), data = df) + labs(title = "All Mets Age 37 Season", x = "Games", y = "Batting Average", caption = "Age 37 Mets") + scale_x_continuous(breaks=seq(0,160,20))
p1

p2 <- ggplot() + geom_line(aes(y = BAcareer, x = G), data = age37mets, color = "blue") + labs(title = "All Mets Age 37 Career", x = "Games", y = "Career Batting Average", caption = "Age 37 Mets") + scale_x_continuous(breaks=seq(0,160,20))
p2
</code>```

Here is my dput:

```<code>structure(list(BA = c(0.317, 0.298, 0.273, 0.28, 0.252, 0.204,
0.181, 0.241, 0.227, 0.233, 0.08, 0.285), careerBA = c(0.279,
0.28, 0.245, 0.253, 0.276, 0.247, 0.265, 0.243, 0.274, 0.255,
0.236, 0.287), G = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)), class = "data.frame", row.names = c(NA,
-12L))
</code>```

答:
One solution is to reshape your data into a longer format (here I'm using pivot_longer function from tidyr package):

library(dplyr)
library(tidyr)

df %>% pivot_longer(-G, names_to = "var",values_to = "val")

# A tibble: 24 x 3
       G var        val
   <dbl> <chr>    <dbl>
 1     1 BA       0.317
 2     1 careerBA 0.279
 3     2 BA       0.298
 4     2 careerBA 0.28
 5     3 BA       0.273
 6     3 careerBA 0.245
 7     4 BA       0.28
 8     4 careerBA 0.253
 9     5 BA       0.252
10     5 careerBA 0.276
# … with 14 more rows
```

<p>If you want to add the plotting part, you can wrote:</p>

<pre class="lang-r prettyprint-override"><code>library(dplyr)
library(tidyr)
library(ggplot2)
library(scales)

df %>% pivot_longer(-G, names_to = "var",values_to = "val") %>%
  ggplot(aes(x = G, y = val, color = var))+
  geom_line()+
  scale_y_continuous(labels = function(x){format(x, nsmall = 3)})
</code>```

Is it what you are looking for ?

Body:
Using R, I have two line graphs each in their own chart. I need them both on the same chart. I have looked at other stackoverflow inquiries but did not find one that matches my need.

In my two-line chart I need graphs for BA and careerBA on the vertical axis and the G field as the horizontal axis. Each G value (e.g., 1) has a matching BA and careerBA.

BA <- c(0.317, 0.298, 0.273, 0.280, 0.252, 0.204, 0.181, 0.241, 0.227, 0.233, 0.080, 0.285)

careerBA <- c(0.279, 0.280, 0.245, 0.253, 0.276, 0.247, 0.265, 0.243, 0.274, 0.255, 0.236, 0.287)

G <- c(1,2,3,4,5,6,7,8,9,10,11,12)

df <- data.frame(BA, careerBA, G)
df

library(ggplot2)
p1 <- ggplot() + geom_line(aes(y = BA, x = G, color = "red"), data = df) + labs(title = "All Mets Age 37 Season", x = "Games", y = "Batting Average", caption = "Age 37 Mets") + scale_x_continuous(breaks=seq(0,160,20))
p1

p2 <- ggplot() + geom_line(aes(y = BAcareer, x = G), data = age37mets, color = "blue") + labs(title = "All Mets Age 37 Career", x = "Games", y = "Career Batting Average", caption = "Age 37 Mets") + scale_x_continuous(breaks=seq(0,160,20))
p2

Here is my dput:

structure(list(BA = c(0.317, 0.298, 0.273, 0.28, 0.252, 0.204,
0.181, 0.241, 0.227, 0.233, 0.08, 0.285), careerBA = c(0.279,
0.28, 0.245, 0.253, 0.276, 0.247, 0.265, 0.243, 0.274, 0.255,
0.236, 0.287), G = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)), class = "data.frame", row.names = c(NA,
-12L))

Body:
One solution is to reshape your data into a longer format (here I'm using pivot_longer function from tidyr package):

library(dplyr)
library(tidyr)

df %>% pivot_longer(-G, names_to = "var",values_to = "val")

# A tibble: 24 x 3
       G var        val
   <dbl> <chr>    <dbl>
 1     1 BA       0.317
 2     1 careerBA 0.279
 3     2 BA       0.298
 4     2 careerBA 0.28
 5     3 BA       0.273
 6     3 careerBA 0.245
 7     4 BA       0.28
 8     4 careerBA 0.253
 9     5 BA       0.252
10     5 careerBA 0.276
# … with 14 more rows

If you want to add the plotting part, you can wrote:

library(dplyr)
library(tidyr)
library(ggplot2)
library(scales)

df %>% pivot_longer(-G, names_to = "var",values_to = "val") %>%
  ggplot(aes(x = G, y = val, color = var))+
  geom_line()+
  scale_y_continuous(labels = function(x){format(x, nsmall = 3)})

Is it what you are looking for ?


问:
How can I convert '+' character to a regular expression for REGEXMATCH in Google Sheets?
```<code>=IF(OR(REGEXMATCH(C3,"A"),REGEXMATCH(C3,"+"),REGEXMATCH(C3,"G")),1,0)
</code>```

In Google Sheets, I'm using the above formula to output 1 if either A, + or G characters are present in cell C3. Some example values for C3 are AG+, ABCDKHN$%, GHXV, etc, those will lead the formula to output 1.

The + character ends up with this error:

How can I convert the + character for the REGEXMATCH formula to look for it in a string successfully?

Body:
=IF(OR(REGEXMATCH(C3,"A"),REGEXMATCH(C3,"+"),REGEXMATCH(C3,"G")),1,0)

In Google Sheets, I'm using the above formula to output 1 if either A, + or G characters are present in cell C3. Some example values for C3 are AG+, ABCDKHN$%, GHXV, etc, those will lead the formula to output 1.

The + character ends up with this error:

How can I convert the + character for the REGEXMATCH formula to look for it in a string successfully?

Body:
try just:

=IF(REGEXMATCH(C3, "A|G|\+"), 1, 0)


问:
How to get the placeholder and the text to begin from the start of the textarea?
How do I get the placeholder/text at the start top-left of the textarea? It is at the centre right now.

.input-textarea {
  width: 100%;
  min-height: 100px;
  resize: vertical;
  padding: 1em;
  border-radius: 3px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label class="comment-label" for="comments">Comments</label>
<input type="textarea" name="comments" id="comments" class="input-textarea" placeholder="Enter your comments here..." required></code>```

OUTPUT

答:
if you want to vertical-align your placeholder and the carret to type  your comment, you may use a contenteditable div + flex.

here is an example of the idea :

label {
  display: block;
}

.flxbx {
  display: flex;
  align-items: center;
  min-height: 100px;
  border: solid;
  background: white;
  color: black;
}

.flxbx,
label {
  padding: 0.5em;
  margin: 0.5em;
}

.flxbx:empty::before {
  content: attr(data-placeholder);
}

body {
  background: #222;
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label>Comments</label>
<div class="flxbx" data-placeholder="Enter your comment here.." contenteditable></div></code>```

Body:
How do I get the placeholder/text at the start top-left of the textarea? It is at the centre right now.

.input-textarea {
  width: 100%;
  min-height: 100px;
  resize: vertical;
  padding: 1em;
  border-radius: 3px;
}

Comments
<input type="textarea" name="comments" id="comments" class="input-textarea" placeholder="Enter your comments here..." required>

OUTPUT

Body:
if you want to vertical-align your placeholder and the carret to type  your comment, you may use a contenteditable div + flex.

here is an example of the idea :

label {
  display: block;
}

.flxbx {
  display: flex;
  align-items: center;
  min-height: 100px;
  border: solid;
  background: white;
  color: black;
}

.flxbx,
label {
  padding: 0.5em;
  margin: 0.5em;
}

.flxbx:empty::before {
  content: attr(data-placeholder);
}

body {
  background: #222;
  color: white;
}

<label>Comments</label>
<div class="flxbx" data-placeholder="Enter your comment here.." contenteditable></div>


问:
How to stop bokeh server?
I do use bokeh to plot sensor data live on the local LAN. Bokeh is started from within my python application using popen: Popen("bokeh serve --host=localhost:5006 --host=192.168.8.100:5006", shell=True)

I would like to close bokeh server from within the application. However, I cannot find anything in the documentation. Also bokeh serve --help does not give any hint how to do that.

EDIT: based on the accepted answer I came up with following solution:

```<code>        self.bokeh_serve = subprocess.Popen(shlex.split(command),
                             shell=False, stdout=subprocess.PIPE)
</code>```

I used self.bokeh_serve.kill() for ending the process. Maybe .terminate() would be better. I will try it.

答:
There is a very simple way that I use in my Python 3.7 with Bokeh server programming to stop the server, with no explicit Tornado or Server imports. My OS is Windows 7 and I use Python 3.7 because Python 3.8 is not compatible with Bokeh server

I start a bokeh server from outside with

```<code>bokeh serve --show myprogr.py
</code>```

The content of  myprog.py:

```<code>import numpy as np
from bokeh.plotting import figure, curdoc
from bokeh.models.widgets import Button
from bokeh.layouts import column, widgetbox
import sys

def button_callback():
    sys.exit()  # Stop the server

def add_circles():
    # 10 more circles
    sample_plot.circle(x=np.random.normal(size=(10,)),
                       y=np.random.normal(size=(10,)))

bokeh_doc = curdoc()
sample_plot = figure(plot_height=400, plot_width=400) # figure frame

# Button to stop the server
button = Button(label="Stop", button_type="success")
button.on_click(button_callback)

bokeh_doc.add_root(column([sample_plot, widgetbox(button, align="center")]))
bokeh_doc.add_periodic_callback(add_circles, 1000)
bokeh_doc.title = "More and more circles with a button to stop"
</code>```

One can see in your default web browser. It adds a new tab and shows a graph with a growing number of small circles until press stop and see that the party is over.

Title: How to stop bokeh server?

Body:
I do use bokeh to plot sensor data live on the local LAN. Bokeh is started from within my python application using popen: Popen("bokeh serve --host=localhost:5006 --host=192.168.8.100:5006", shell=True)

I would like to close bokeh server from within the application. However, I cannot find anything in the documentation. Also bokeh serve --help does not give any hint how to do that.

EDIT: based on the accepted answer I came up with following solution:

        self.bokeh_serve = subprocess.Popen(shlex.split(command),
                             shell=False, stdout=subprocess.PIPE)

I used self.bokeh_serve.kill() for ending the process. Maybe .terminate() would be better. I will try it.

Body:
There is a very simple way that I use in my Python 3.7 with Bokeh server programming to stop the server, with no explicit Tornado or Server imports. My OS is Windows 7 and I use Python 3.7 because Python 3.8 is not compatible with Bokeh server

I start a bokeh server from outside with

bokeh serve --show myprogr.py

The content of  myprog.py:

import numpy as np
from bokeh.plotting import figure, curdoc
from bokeh.models.widgets import Button
from bokeh.layouts import column, widgetbox
import sys

def button_callback():
    sys.exit()  # Stop the server

def add_circles():
    # 10 more circles
    sample_plot.circle(x=np.random.normal(size=(10,)),
                       y=np.random.normal(size=(10,)))

bokeh_doc = curdoc()
sample_plot = figure(plot_height=400, plot_width=400) # figure frame

# Button to stop the server
button = Button(label="Stop", button_type="success")
button.on_click(button_callback)

bokeh_doc.add_root(column([sample_plot, widgetbox(button, align="center")]))
bokeh_doc.add_periodic_callback(add_circles, 1000)
bokeh_doc.title = "More and more circles with a button to stop"

One can see in your default web browser. It adds a new tab and shows a graph with a growing number of small circles until press stop and see that the party is over.


问:
NumPy - Selecting a submatrix from another 2d array
This is my original 2d array A

```<code>[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 2, 2, 2, 2, 2, 2, 0, 0, 0],
 [0, 2, 2, 2, 2, 2, 2, 0, 0, 0],
 [0, 2, 2, 2, 2, 2, 2, 0, 0, 0],
 [0, 2, 2, 2, 2, 2, 2, 0, 0, 0],
 [0, 2, 2, 8, 8, 8, 2, 0, 0, 0],
 [0, 2, 2, 8, 8, 8, 2, 0, 0, 0],
 [0, 0, 0, 8, 8, 8, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
</code>```

Let's say I want to return a 3x3 submatrix of 8's at the middle. I made a boolean mask with this expression A == 8 and it looks like this.

```<code>array([[False, False, False, False, False, False, False, False, False,
        False],
       [False, False, False, False, False, False, False, False, False,
        False],
       [False, False, False, False, False, False, False, False, False,
        False],
       [False, False, False, False, False, False, False, False, False,
        False],
       [False, False, False, False, False, False, False, False, False,
        False],
       [False, False, False,  True,  True,  True, False, False, False,
        False],
       [False, False, False,  True,  True,  True, False, False, False,
        False],
       [False, False, False,  True,  True,  True, False, False, False,
        False],
       [False, False, False, False, False, False, False, False, False,
        False],
       [False, False, False, False, False, False, False, False, False,
        False]])
</code>```

This is the point where I'm stuck. How can I return the submatrix with that boolean mask? If I do A[A == 8], it returns a flat array of 8s like this

```<code>array([8, 8, 8, 8, 8, 8, 8, 8, 8])
</code>```

Another way is getting the row and column numbers with np.where(A == 8) which returns (array([5, 5, 5, 6, 6, 6, 7, 7, 7]), array([3, 4, 5, 3, 4, 5, 3, 4, 5])). How can I return the matrix using them?

Is there any better approach for this problem?

Body:
This is my original 2d array A

[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 2, 2, 2, 2, 2, 2, 0, 0, 0],
 [0, 2, 2, 2, 2, 2, 2, 0, 0, 0],
 [0, 2, 2, 2, 2, 2, 2, 0, 0, 0],
 [0, 2, 2, 2, 2, 2, 2, 0, 0, 0],
 [0, 2, 2, 8, 8, 8, 2, 0, 0, 0],
 [0, 2, 2, 8, 8, 8, 2, 0, 0, 0],
 [0, 0, 0, 8, 8, 8, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

Let's say I want to return a 3x3 submatrix of 8's at the middle. I made a boolean mask with this expression A == 8 and it looks like this.

array([[False, False, False, False, False, False, False, False, False,
        False],
       [False, False, False, False, False, False, False, False, False,
        False],
       [False, False, False, False, False, False, False, False, False,
        False],
       [False, False, False, False, False, False, False, False, False,
        False],
       [False, False, False, False, False, False, False, False, False,
        False],
       [False, False, False,  True,  True,  True, False, False, False,
        False],
       [False, False, False,  True,  True,  True, False, False, False,
        False],
       [False, False, False,  True,  True,  True, False, False, False,
        False],
       [False, False, False, False, False, False, False, False, False,
        False],
       [False, False, False, False, False, False, False, False, False,
        False]])

This is the point where I'm stuck. How can I return the submatrix with that boolean mask? If I do A[A == 8], it returns a flat array of 8s like this

array([8, 8, 8, 8, 8, 8, 8, 8, 8])

Another way is getting the row and column numbers with np.where(A == 8) which returns (array([5, 5, 5, 6, 6, 6, 7, 7, 7]), array([3, 4, 5, 3, 4, 5, 3, 4, 5])). How can I return the matrix using them?

Is there any better approach for this problem?

Body:
You can capture row and column indexes and after that return submatrix from these indexes only using np.ix_ method:

x, y = np.where(A==8) #[5 5 5 6 6 6 7 7 7], [3 4 5 3 4 5 3 4 5]
x, y = np.unique(x), np.unique(y) # [5,6,7], [3,4,5]
print(A[np.ix_(x, y)]) #prints [[8 8 8], [8 8 8], [8 8 8]]

This should work even in more general cases, although not always as expected:

def submatrix(A):
    x, y = np.where(A==8)
    x, y = np.unique(x), np.unique(y)
    return A[np.ix_(x, y)]

>>> A = np.array([
[8, 2, 8, 2, 8, 0],
[2, 8, 8, 8, 2, 0],
[2, 8, 4, 8, 3, 0],
[0, 8, 8, 8, 0, 0],
[8, 0, 8, 0, 8, 0],
[0, 0, 0, 0, 0, 0]])
>>> submatrix(A)
array([[8, 2, 8, 2, 8],
       [2, 8, 8, 8, 2],
       [2, 8, 4, 8, 3],
       [0, 8, 8, 8, 0],
       [8, 0, 8, 0, 8]])
>>> A = np.array([
[8, 2, 8, 2, 8, 0],
[2, 2, 8, 8, 2, 0],
[2, 2, 4, 3, 3, 0],
[0, 2, 8, 8, 0, 0],
[8, 0, 8, 0, 8, 0],
[0, 0, 0, 0, 0, 0]])
>>> submatrix(A) # skipping empty rows and columns
array([[8, 8, 2, 8],
       [2, 8, 8, 2],
       [0, 8, 8, 0],
       [8, 8, 0, 8]])

Since np.unique returns sorted arrays, you can fill the gaps constucting x, y like so:

def submatrix(A):
    x, y = np.where(A==8)
    x, y = np.unique(x), np.unique(y)
    x, y = np.arange(x[0], x[-1]+1), np.arange(y[0], y[-1]+1)
    return A[np.ix_(x, y)]


答:
While I can't imagine why you would do that I think you should use ajax.
Attach an event on every a tag and send them to a script on your server where the magic of curl would happen.
Anyway you should explain why you need to fetch data with curl.</p>

Title: php Curl clicked links

Body:
I need any link that has a "a href=" tag when clicked to be received via curl. I can't hard code these links as they are from a dynamic site so could be anything. How would I achieve this?

Thanks

Edit: Let me explain more. I have an app on my pc that uses a web front end. It catalogs files and gives yo options to rename delete etc. I want to add a public view however if I put it as is online then anyone can delete rename files. If I curl the pages I can remove the menu bars and editing options through the use of a different css. That part all works. The only part that isn't working is if I click on a link on the page it directs me back to the original link address and that defeats the point as the menu bars are back. I need it to curl the clicked links. Hope that makes more sense..

Here is my code that fetches the original link and curls that and changes the css to point to my own css. It points the java script to the original as I dont need to change that. I now need to make the "a href" links on the page when clicked be called by curl and not go to the original destination

<?php

$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, 'http://192.168.0.14:8081/home/');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$curl_response = curl_exec($ch);
curl_close($ch);

//Change link url

$link = $curl_response;

$linkgo = '/sickbeard_public';
$linkfind = 'href="';
$linkreplace = 'href="' . $linkgo ;

$link = str_replace($linkfind, $linkreplace, $link);

//Change js url
$js = $link;

$jsgo = 'http://192.168.0.14:8081';
$jsfind = 'src="';
$jsreplace = 'src="' . $jsgo ;

$js = str_replace($jsfind, $jsreplace, $js);

//Fix on page link errors
$alink = $js;
$alinkgo = 'http://192.168.0.14:8081/';
$alinkfind = 'a href="/sickbeard_public/';
$alinkreplace = 'a href="' . $alinkgo ;

$alink = str_replace($alinkfind, $alinkreplace, $alink);

//Echo page back
echo $alink;

?>


问:
$project: Is it possible to access a property of an expression result in just one single stage?
Is there any way to carry out the following operation in just one $project stage?

```<code>db.getCollection('users').aggregate([
    {
        $project : {
            firstEmail : { $arrayElemAt : ["$emails", 0] }
        }
    },
    {
        $project : {
            domain : "$firstEmail.domain"
        }
    }
])
</code>```

答:
You need $let operator:

```<code>db.getCollection('users').aggregate([
    {
        $project : {
            domain : {
                $let: {
                    vars: { firstEmail: { $arrayElemAt : ["$emails", 0] } },
                    in: "$$firstEmail.domain"
                }
            }
        }
    }
])
</code>```

Mongo Playground

Body:
Is there any way to carry out the following operation in just one $project stage?

db.getCollection('users').aggregate([
    {
        $project : {
            firstEmail : { $arrayElemAt : ["$emails", 0] }
        }
    },
    {
        $project : {
            domain : "$firstEmail.domain"
        }
    }
])

Body:
You need $let operator:

db.getCollection('users').aggregate([
    {
        $project : {
            domain : {
                $let: {
                    vars: { firstEmail: { $arrayElemAt : ["$emails", 0] } },
                    in: "$$firstEmail.domain"
                }
            }
        }
    }
])

Mongo Playground


问:
How to update multiple rows with values of two arrays in Postgres?
I need to update a set of records in the x table with values stored in arrays. Anyone know how I could do it?

```<code>IDS_NEW_SPONSORS INTEGER[] := ARRAY[]::INTEGER[]; --possible values [1,2,3,4,5,6]
IDS_DEBTORS  INTEGER[] := ARRAY[]::INTEGER[]; --possible values [20,21,22,23,24,25]
-- the arrays will be the same size--
UPDATE x
SET id_sponsor = [IDS_NEW_SPONSORS],-- HOW ADD
id_sponsor_historial = [IDS_DEBTORS], -- HOW ADD
id_patron = 5 -- ALWAYS SAME
WHERE id_sponsor = ANY(IDS_DEBTORS); -- this line working!!! loop each row
</code>```

I'm working with postgres 11...

After update. the table would look like this:

```<code>id_sponsor | id_sponsor_historial | id_patron
1            20                     5
2            21                     5
3            22                     5
4            23                     5
5            24                     5
6            25                     5
</code>```

答:
What I was trying to do is update the records as follows
A: Replacing the old sponsors (old_sponsor) with the new ones (new_sponsor)
B: Updating the historical_sponsor_id with the values of old_sponsor
C: Adding all of them the same id_patron

I could do it this way based on the @clamp response..

```<code>DECLARE
   new_sponsor INTEGER[] := array[2300,2034,2032];
   old_sponsor INTEGER[] := array[1500,1501,1502];
BEGIN
   FOR i IN array_lower(new_sponsor, 1) .. array_upper(new_sponsor, 1)
   LOOP
    UPDATE x SET id_sponsor = new_sponsor[i],
        id_sponsor_historial = old_sponsor[i], id_patron = 5
    WHERE id_sponsor = old_sponsor[i];

   END LOOP;
END
</code>```

I would like to know if it is useful for processing more than 10,000 records or if there is a better way to do it efficiently.

Body:
I need to update a set of records in the x table with values stored in arrays. Anyone know how I could do it?

IDS_NEW_SPONSORS INTEGER[] := ARRAY[]::INTEGER[]; --possible values [1,2,3,4,5,6]
IDS_DEBTORS  INTEGER[] := ARRAY[]::INTEGER[]; --possible values [20,21,22,23,24,25]
-- the arrays will be the same size--
UPDATE x
SET id_sponsor = [IDS_NEW_SPONSORS],-- HOW ADD
id_sponsor_historial = [IDS_DEBTORS], -- HOW ADD
id_patron = 5 -- ALWAYS SAME
WHERE id_sponsor = ANY(IDS_DEBTORS); -- this line working!!! loop each row

I'm working with postgres 11...

After update. the table would look like this:

id_sponsor | id_sponsor_historial | id_patron
1            20                     5
2            21                     5
3            22                     5
4            23                     5
5            24                     5
6            25                     5

Body:
What I was trying to do is update the records as follows
A: Replacing the old sponsors (old_sponsor) with the new ones (new_sponsor)
B: Updating the historical_sponsor_id with the values of old_sponsor
C: Adding all of them the same id_patron

I could do it this way based on the @clamp response..

DECLARE
   new_sponsor INTEGER[] := array[2300,2034,2032];
   old_sponsor INTEGER[] := array[1500,1501,1502];
BEGIN
   FOR i IN array_lower(new_sponsor, 1) .. array_upper(new_sponsor, 1)
   LOOP
    UPDATE x SET id_sponsor = new_sponsor[i],
        id_sponsor_historial = old_sponsor[i], id_patron = 5
    WHERE id_sponsor = old_sponsor[i];

   END LOOP;
END

I would like to know if it is useful for processing more than 10,000 records or if there is a better way to do it efficiently.


问:
How to open new activity by clicking on SearchView
I created an Android project in which I use search view. I want to open a new activity by clicking the SearchView. When I click icon of SearchView it work perfectly, but when I click in the empty space of the SearchView the keyboard pops up and the new activity is not opening up.

My java code:

```<code>searchView=root.findViewById(R.id.search);
searchView.setIconifiedByDefault(true);
searchView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent searchIntent=new Intent(getActivity(),Notification_activity.class);
        getActivity().startActivity(searchIntent);
    }
});
</code>```

My XML:

```<code><SearchView
    android:id="@+id/search"
    android:layout_width="333dp"
    android:layout_height="40dp"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:background="@drawable/search_round_corner"
    android:iconifiedByDefault="false"
    android:queryHint="Enter text to search"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">
</SearchView>
</code>```

答:
```<code>searchView.setOnSearchClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(this,page,class);
            startActivity(i);
        }
    });
    searchView.setOnCloseListener(new SearchView.OnCloseListener() {
        @Override
        public boolean onClose() {
            //do what you want  searchview is not expanded
            return false;
        }
    });
</code>```

Body:
I created an Android project in which I use search view. I want to open a new activity by clicking the SearchView. When I click icon of SearchView it work perfectly, but when I click in the empty space of the SearchView the keyboard pops up and the new activity is not opening up.

My java code:

searchView=root.findViewById(R.id.search);
searchView.setIconifiedByDefault(true);
searchView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent searchIntent=new Intent(getActivity(),Notification_activity.class);
        getActivity().startActivity(searchIntent);
    }
});

My XML:

<SearchView
    android:id="@+id/search"
    android:layout_width="333dp"
    android:layout_height="40dp"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:background="@drawable/search_round_corner"
    android:iconifiedByDefault="false"
    android:queryHint="Enter text to search"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">
</SearchView>


问:
When to use assert in client & common GWT code
There are several questions on StackOverflow discussing the question of when one should use an assert statement versus throwing some exception.  (Examples here, here, here, here, and here.

However, I have come to suspect that the conventional wisdom of assert-versus-throw is based upon the assumption that you are running within a JVM.   In the GWT universe, where your Java gets transliterated to JavaScript and runs in the context of a browser, the set of tradeoffs feels different:   asserts are always compiled-away when running in a browser, and anything that keeps the size of your JavaScript smaller is a win, especially if you web application must run on a mobile handset.   Asserts do get run in DevMode, however, so they have utility there during development.

So my questions are:  has anybody given any thought as to a set of best-practice rules that govern how to use the assert statement in GWT?   I have had members of my team ask me "since the assert gets compiled out, does it make sense to have them?", and I'd like to have a good answer  for them.

Also, does anybody have any insight into the philosophy that the developers of GWT at Google have on this subject?   Looking at the GWT source code, they appear to use it frequently.

答:
Google's FAQ says

Only use assertions for debugging purposes, not production logic because assertions will only work under GWT's development mode. By default, they are compiled away by the GWT compiler so do not have any effect in production mode unless you explicitly enable them.

This isn't any different from the answers given to the questions you linked to. Whether the Java code is being compiled in the usual way by javac or being compiled to JavaScript by GWT,
"assert" means "if this isn't true I have a bug." In contrast, code of the form

```<code>if (condition) throw new Exception(msg);
</code>```

means "if this is true then we have an unexpected situation that the program will have to handle."

As for the members of the team that don't see the point of assert, explain that they're supposed to have a bunch of unit tests that run with assertions enabled. If the tests have good code coverage and none of them cause the assertion to fail, then the assumption indicated by the assert statement is demonstrated to hold.

Body:
Google's FAQ says

Only use assertions for debugging purposes, not production logic because assertions will only work under GWT's development mode. By default, they are compiled away by the GWT compiler so do not have any effect in production mode unless you explicitly enable them.

This isn't any different from the answers given to the questions you linked to. Whether the Java code is being compiled in the usual way by javac or being compiled to JavaScript by GWT,
"assert" means "if this isn't true I have a bug." In contrast, code of the form

if (condition) throw new Exception(msg);

means "if this is true then we have an unexpected situation that the program will have to handle."

As for the members of the team that don't see the point of assert, explain that they're supposed to have a bunch of unit tests that run with assertions enabled. If the tests have good code coverage and none of them cause the assertion to fail, then the assumption indicated by the assert statement is demonstrated to hold.


问:
why did elasticsearch designed "store" field?
By default, field values are indexed to make them searchable, but they are not stored. This means that the field can be queried, but the original field value cannot be retrieved.

I am curious how does the implementation work on Elasticsearch backend works. How can they make a value not retrievable but searchable? (I would imagine it would need to be stored somewhere in order for you to search it right?) Why is Elasticsearch designed this way? what efficiency did it achieve for designing it this way?

答:
The source document is actually "stored" in the _source field (but it is not indexed) and all fields of the source documents are indexed (but not stored). All field values can usually be retrieved from the _source field using source filtering. This is how ES is configured by default, but you're free to change that.

You can, for instance, decide to not store the _source document at all and store only certain fields of your document. This might be a good idea if for instance your document has a field which contains a huge blob of text. It might not be wise to store the _source because that would take a lot of space for nothing. That huge blob of text might only be useful for full-text search and so would only need to be indexed, while all other fields might need to be indexed and stored as well because they need to be retrieved in order to be displayed.

So the bottom line is:

if a field can be searched, it doesn't need to be stored, it only needs to be indexed

if a field can be retrieved, it can either be configured to be stored or retrieved/filtered from the _source field (which is stored by default)


问:
Javscript fs module: where is output being written to?
I'm using the fs filesystem JS module to write to a file. I want this file to be in the ~/Desktop folder, so I do this:

```<code>var fs = require('fs');
let a = "text"
fs.writeFile('~/Desktop/output.txt', a, () => {})
</code>```

This runs with no errors, but I don't see an output.txt file on my Desktop, or anywhere in my system. It works fine when I just do output.txt instead of ~/Desktop/output.txt; it saves the output in a file output.txt in my current directory.

Does anyone know what's happening here?

答:
Node doesn't expand the bash specific shortcut tilde ("~") to your home directory.

Specify the full path or use a package like expand-tilde.

Body:
I'm using the fs filesystem JS module to write to a file. I want this file to be in the ~/Desktop folder, so I do this:

var fs = require('fs');
let a = "text"
fs.writeFile('~/Desktop/output.txt', a, () => {})

This runs with no errors, but I don't see an output.txt file on my Desktop, or anywhere in my system. It works fine when I just do output.txt instead of ~/Desktop/output.txt; it saves the output in a file output.txt in my current directory.

Does anyone know what's happening here?


问:
AFrame 1.0.3 Camera wont reset to zero rotation
I want to reset the camera to zero rotation on the click of a button. I have placed camera as a child of an entity. After I rotate the camera a bit I then click the button to reset the camera to zero rotation. It goes to zero but then snaps back to the rotation. How can I reset the camera to zero (or any specific rotation).
Thank you. Here is a basic hello world scene with an added button (red square at top) and a camera as a child of an entity.     </p>

```<code><html>
    <head>
        <script src="https://aframe.io/releases/1.0.3/aframe.min.js"></script>
    </head>
    <body>
        <a-scene  cursor="rayOrigin: mouse" raycaster="objects: #button , #toggle">
            <a-entity rotation="0 0 0" position="0 0 0" animation=" property: rotation; to: 0 0 0; startEvents: toggle">
                <a-camera  rotation="0 0 0" wasd-controls="acceleration:200" animation=" property: rotation; to: 0 0 0 ; startEvents: toggle">
                    <a-entity id = "toggle" geometry="primitive: plane; height: 0.2; width: 0.2" position="0.3 0.7 -1"
                        material="color: red; opacity: 0.5"  >
                    </a-entity>
                </a-camera>
            </a-entity>
            <a-box position="-1 0.5 -3" rotation="0 45 0" color="#4CC3D9"></a-box>
            <a-sphere position="0 1.25 -5" radius="1.25" color="#EF2D5E"></a-sphere>
            <a-cylinder position="1 0.75 -3" radius="0.5" height="1.5" color="#FFC65D"></a-cylinder>
            <a-plane position="0 0 -4" rotation="-90 0 0" width="4" height="4" color="#7BC8A4"></a-plane>
        </a-scene>

        <script>
            var toggleEl = document.querySelector('#toggle')
            toggleEl.addEventListener('click', function (evt) {
                toggleEl.emit("toggle");
            });
        </script>
  </body>
</html>
</code>```

答:
The camera ( primitive or camera component) is a wrapper around the THREE.PerspectiveCamera. It does not handle rotation by itself.

The rotation is handled, If not otherwise specified, by the look-controls component (which the  has by default).

In a HUGE nutshell, the rotation updates are done using two helper objects - the pitchObject and the yawObject. If you want to manipulate the camera orientation - you need to change their rotation, for example:

```<code>// reset the rotation
let controls = document.querySelector('a-camera').components['look-controls']
controls.pitchObject.rotation.x = 0
controls.yawObject.rotation.y = 0
</code>```

Check it out in this fiddle

Keep in mind, that manipulating a "free" camera is not considered a good practice, as it is a major inconvinience, especially in VR.

You may want to disable the look-controls and rotate a wrapper entity instead.

```<code><!-- Rotate or animate this --/>
<a-entity>
    <!-- instead of this --/>
    <a-camera look-controls='enabled: false'>
    </a-camera>
</a-entity>
</code>```

Body:
The camera (<a-camera> primitive or camera component) is a wrapper around the THREE.PerspectiveCamera. It does not handle rotation by itself.

The rotation is handled, If not otherwise specified, by the look-controls component (which the <a-camera> has by default).

In a HUGE nutshell, the rotation updates are done using two helper objects - the pitchObject and the yawObject. If you want to manipulate the camera orientation - you need to change their rotation, for example:

// reset the rotation
let controls = document.querySelector('a-camera').components['look-controls']
controls.pitchObject.rotation.x = 0
controls.yawObject.rotation.y = 0

Check it out in this fiddle

Keep in mind, that manipulating a "free" camera is not considered a good practice, as it is a major inconvinience, especially in VR.

You may want to disable the look-controls and rotate a wrapper entity instead.

<!-- Rotate or animate this --/>
<a-entity>
    <!-- instead of this --/>
    <a-camera look-controls='enabled: false'>
    </a-camera>
</a-entity>


问:
Total count across different columns in Tableau

Please find the dataset above
I need to get the

```<code>1) RM count across the whole table and per column
2) GI count across whole table and per column
3) NA or blank across whole table and per column
</code>```

I know how to get the count across columns
Need help with whole table

答:
Unless you can pivot your data, you can add count each column like so:

```<code>count(if [CL1] = 'RM' then 1 end) + count(if [CL2] = 'RM' then 1 end) + etc....
</code>```

Repeat for GI.

For NA or blank, you can do something similar

```<code>count(if [CL1] = 'NA' OR ISNULL([CL1]) then 1 end) + count(if [CL2] = 'NA' OR ISNULL([CL1]) then 1 end) + etc....
</code>```

Body:
Please find the dataset above
I need to get the

1) RM count across the whole table and per column
2) GI count across whole table and per column
3) NA or blank across whole table and per column

I know how to get the count across columns
Need help with whole table

Body:
Unless you can pivot your data, you can add count each column like so:

count(if [CL1] = 'RM' then 1 end) + count(if [CL2] = 'RM' then 1 end) + etc....

Repeat for GI.

For NA or blank, you can do something similar

count(if [CL1] = 'NA' OR ISNULL([CL1]) then 1 end) + count(if [CL2] = 'NA' OR ISNULL([CL1]) then 1 end) + etc....


问:
The create-react-app imports restriction outside of src directory
I am using create-react-app. I am trying to call an image from my public folder from a file inside my src/components. I am receiving this error message.

./src/components/website_index.js Module not found: You attempted to
  import ../../public/images/logo/WC-BlackonWhite.jpg which falls
  outside of the project src/ directory. Relative imports outside of
  src/ are not supported. You can either move it inside src/, or add a
  symlink to it from project's node_modules/.

import logo from '../../public/images/logo_2016.png';

I have read many things saying you can do an import to the path but that is still not working for me. Any help would be greatly appreciated. I know there are many questions like this but they are all telling me to import logo or image so clearly I am missing something in the big picture.

答:
Adding to Bartek Maciejiczek's answer, this is how it looks with Craco:

const ModuleScopePlugin = require("react-dev-utils/ModuleScopePlugin");
const path = require("path");

module.exports = {
  webpack: {
    configure: webpackConfig => {
      webpackConfig.resolve.plugins.forEach(plugin => {
        if (plugin instanceof ModuleScopePlugin) {
          plugin.allowedFiles.add(path.resolve("./config.json"));
        }
      });
      return webpackConfig;
    }
  }
};
```
<p>My previous workaround worked with Webpack 4, but not with 5. After skimming through the accumulated workarounds since then, I found the following one really easy (and seemingly scalable).</p>
<pre class="lang-js prettyprint-override"><code>import { CracoAliasPlugin } from 'react-app-alias';

const cracoConfig = {
  plugins: [
    {
      plugin: CracoAliasPlugin,
      options: {
        alias: { '~': './' },
      },
    },
  ],
}
</code>```

Then import like so:

import whatever from '~/<path-to-file>';
```

Body:
Adding to Bartek Maciejiczek's answer, this is how it looks with Craco:

const ModuleScopePlugin = require("react-dev-utils/ModuleScopePlugin");
const path = require("path");

module.exports = {
  webpack: {
    configure: webpackConfig => {
      webpackConfig.resolve.plugins.forEach(plugin => {
        if (plugin instanceof ModuleScopePlugin) {
          plugin.allowedFiles.add(path.resolve("./config.json"));
        }
      });
      return webpackConfig;
    }
  }
};

My previous workaround worked with Webpack 4, but not with 5. After skimming through the accumulated workarounds since then, I found the following one really easy (and seemingly scalable).

import { CracoAliasPlugin } from 'react-app-alias';

const cracoConfig = {
  plugins: [
    {
      plugin: CracoAliasPlugin,
      options: {
        alias: { '~': './' },
      },
    },
  ],
}

Then import like so:

import whatever from '~/<path-to-file>';