问:
'HttpResponse' object has no attribute 'data' in DRF
I've defined a url in urls.py to export some data as csv using Django 3.0.6 and djangorestframework 3.10.3

```<code>    re_path(
        r'^(?:v1/)?export/csv/$',
        api.ExportAPIView.as_view(),
        name='export'
    ),
</code>```

And here is the api.py code to handle this url:

```<code>class ExportAPIView(APIView):

    def get(self, request, *args, **kwargs):
        http_response = HttpResponse(content_type='text/csv')
        http_response[
            'Content-Disposition'] = 'attachment; filename="somefilename.csv"'

        writer = csv.writer(http_response)
        writer.writerow(['First row', 'Foo', 'Bar', 'Baz'])
        writer.writerow(
            ['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])

        return http_response
</code>```

The response of this code should be simple csv file containing two rows but I'm getting this error instead:

```<code>AttributeError at /v1/export/csv/
'HttpResponse' object has no attribute 'data'

</code>```

Note that I've used renderer_classes = [CSVRenderer] from djangorestframework-csv and StreamingHttpResponse with no luck either. So what is the problem that I'm missing here?

答:
As long as renderer_classes = [CSVRenderer] is set, you should be able to use something like this:

```<code>def get(self, request, *args, **kwargs):
    content = [
        ['First row', 'Foo', 'Bar', 'Baz'],
        ['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"]],
    ]
    response = Response(content)
    response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'

    return response
</code>```

Body:
I've defined a url in urls.py to export some data as csv using Django 3.0.6 and djangorestframework 3.10.3

    re_path(
        r'^(?:v1/)?export/csv/$',
        api.ExportAPIView.as_view(),
        name='export'
    ),

And here is the api.py code to handle this url:

class ExportAPIView(APIView):

    def get(self, request, *args, **kwargs):
        http_response = HttpResponse(content_type='text/csv')
        http_response[
            'Content-Disposition'] = 'attachment; filename="somefilename.csv"'

        writer = csv.writer(http_response)
        writer.writerow(['First row', 'Foo', 'Bar', 'Baz'])
        writer.writerow(
            ['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])

        return http_response

The response of this code should be simple csv file containing two rows but I'm getting this error instead:

AttributeError at /v1/export/csv/
'HttpResponse' object has no attribute 'data'

Note that I've used renderer_classes = [CSVRenderer] from djangorestframework-csv and StreamingHttpResponse with no luck either. So what is the problem that I'm missing here?

Body:
As long as renderer_classes = [CSVRenderer] is set, you should be able to use something like this:

def get(self, request, *args, **kwargs):
    content = [
        ['First row', 'Foo', 'Bar', 'Baz'],
        ['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"]],
    ]
    response = Response(content)
    response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'

    return response


来源: stackexchange

问:
How to animate removal transition of multiple rows from SwiftUI List?
Please see this sample view that demonstrates the problem:

```<code>struct ListRemovalTransition: View {
    let list1 = ["A", "B", "C", "D"]
    let list2 = ["A", "E", "F", "G", "H", "I", "J", "K"]

    @State var toggle = false
    var chosenList: [String] {
        toggle ? list1 : list2
    }

    var body: some View {
        VStack {
            Toggle(isOn: $toggle) {
                Text("Switch List")
            }

            List(chosenList, id: \.self) { item in
                Text(item)
                    .transition(AnyTransition.opacity.animation(.default))
            }
        }
        .padding()
    }
}

struct ListRemovalTransition_Previews: PreviewProvider {
    static var previews: some View {
        ListRemovalTransition()
    }
}
</code>```

The desired outcome is that the individual rows fade out when removed without changing position. Instead what's happening seems like all the rows first overlap each other before being removed. I've added a transition with animation to the row Text but this has no impact.

答:
Just add id(:) modifier to List to remove default animation. Then add transition(:) modifier to List for your desirable transition. It works perfectly. I just tested on Xcode 11.5. Here is my code...

```<code>struct ListRemovalTransition: View {
    let list1 = ["A", "B", "C", "D"]
    let list2 = ["A", "E", "F", "G", "H", "I", "J", "K"]

    @State var toggle = false
    var chosenList: [String] {
        toggle ? list1 : list2
    }

    var body: some View {
        VStack {
            Toggle(isOn: $toggle) {
                Text("Switch List")
            }

            List(chosenList, id: \.self) { item in
                Text(item)
            }
            .id(UUID())
            .transition(AnyTransition.opacity.animation(.default))
        }
        .padding()
    }
}
</code>```

https://media.giphy.com/media/dVu1CMqk3YdtZHefaE/giphy.gif

Thanks. X_X

ContentLicense: CC BY-SA 4.0

Body:
Please see this sample view that demonstrates the problem:

struct ListRemovalTransition: View {
    let list1 = ["A", "B", "C", "D"]
    let list2 = ["A", "E", "F", "G", "H", "I", "J", "K"]

    @State var toggle = false
    var chosenList: [String] {
        toggle ? list1 : list2
    }

    var body: some View {
        VStack {
            Toggle(isOn: $toggle) {
                Text("Switch List")
            }

            List(chosenList, id: \.self) { item in
                Text(item)
                    .transition(AnyTransition.opacity.animation(.default))
            }
        }
        .padding()
    }
}

struct ListRemovalTransition_Previews: PreviewProvider {
    static var previews: some View {
        ListRemovalTransition()
    }
}

The desired outcome is that the individual rows fade out when removed without changing position. Instead what's happening seems like all the rows first overlap each other before being removed. I've added a transition with animation to the row Text but this has no impact.

Body:
Just add id(:) modifier to List to remove default animation. Then add transition(:) modifier to List for your desirable transition. It works perfectly. I just tested on Xcode 11.5. Here is my code...

struct ListRemovalTransition: View {
    let list1 = ["A", "B", "C", "D"]
    let list2 = ["A", "E", "F", "G", "H", "I", "J", "K"]

    @State var toggle = false
    var chosenList: [String] {
        toggle ? list1 : list2
    }

    var body: some View {
        VStack {
            Toggle(isOn: $toggle) {
                Text("Switch List")
            }

            List(chosenList, id: \.self) { item in
                Text(item)
            }
            .id(UUID())
            .transition(AnyTransition.opacity.animation(.default))
        }
        .padding()
    }
}

https://media.giphy.com/media/dVu1CMqk3YdtZHefaE/giphy.gif

Thanks. X_X


问:
ASIHTTPRequest and ASIWebPageRequest loading local html file error
I'm trying to use the ASIWebPageRequest to load a local html file so that I can use the built-in caching in ASIWebPageRequest. I know this might sound a bit pointless however I want to use remote images in my local files that only get updated once a week or so. If that makes sense.

Here is what I'm doing in code:

```<code>//OUTPUT: file:///Users/ledixonuk/Library/Application%20Support/iPhone%20Simulator/4.3.2/Applications/FDF21331-CC80-4ECB-9A33-16AEC073D117/Documents/ItemOne.html
NSURL *fileUrl = [[NSURL alloc] initFileURLWithPath:[FileSystemHelper dataFilePathInDocuments:@"ItemOne.html"]];

// Assume request is a property of our controller
// First, we'll cancel any in-progress page load
[[self webRequest] setDelegate:nil];
[[self webRequest] cancel];

[self setWebRequest:[ASIWebPageRequest requestWithURL:fileUrl]];
[[self webRequest] setDelegate:self];
[[self webRequest] setDidFailSelector:@selector(webPageFailed:)];
[[self webRequest] setDidFinishSelector:@selector(webPageFinished:)];

// Tell the request to replace urls in this page with local urls
//[[self webRequest] setUrlReplacementMode:ASIReplaceExternalResourcesWithLocalURLs];

// Tell the request to embed external resources directly in the page
[[self webRequest] setUrlReplacementMode:ASIReplaceExternalResourcesWithData];

// It is strongly recommended you use a download cache with ASIWebPageRequest
// When using a cache, external resources are automatically stored in the cache
// and can be pulled from the cache on subsequent page loads
[[self webRequest] setDownloadCache:[ASIDownloadCache sharedCache]];

// Ask the download cache for a place to store the cached data
// This is the most efficient way for an ASIWebPageRequest to store a web page
[[self webRequest] setDownloadDestinationPath:[[ASIDownloadCache sharedCache] pathToStoreCachedResponseDataForRequest:[self webRequest]]];

[[self webRequest] startAsynchronous];
</code>```

And here is the error I'm getting:

  404 Not Found

Not Found

The requested URL /Users/ledixonuk/Library/Application Support/iPhone  Simulator/4.3.2/Applications/FDF21331-CC80-4ECB-9A33-16AEC073D117/Documents/ItemOne.html was > not found on this server.

Obviously the ASIWebPageRequest can not find the ItemOne.html file in the application document folder, however I've double checked and the file is definitely there.

Has anyone else had a similar issue to this? It's driving me mad trying to sort it out!

答:
ASIWebPageRequest is a subclass of ASIHTTPRequest, and unfortunately ASIHTTPRequest doesn't support fetching file: URLs - only http and https ones.

Basically you have all the code you need, you just need to find a way to plumb it together. You could create a subclass of ASIHTTPRequest that can load file: URLs (essentially provide your own implement of startAsyncronous that instead just calls back the delegates after setting up the right data files), or create a subclass of ASIWebPageRequest that does it. I've not yet thought about it in detail so I have no idea which way would be best.

(I think you're seeing the 404 page as ASIHTTPRequest is managing to contact a web server somewhere - perhaps it's trying to fetch from http://127.0.0.1/Users/ledixonuk/Library/....)

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to use the ASIWebPageRequest to load a local html file so that I can use the built-in caching in ASIWebPageRequest. I know this might sound a bit pointless however I want to use remote images in my local files that only get updated once a week or so. If that makes sense.

Here is what I'm doing in code:

//OUTPUT: file:///Users/ledixonuk/Library/Application%20Support/iPhone%20Simulator/4.3.2/Applications/FDF21331-CC80-4ECB-9A33-16AEC073D117/Documents/ItemOne.html
NSURL *fileUrl = [[NSURL alloc] initFileURLWithPath:[FileSystemHelper dataFilePathInDocuments:@"ItemOne.html"]];

// Assume request is a property of our controller
// First, we'll cancel any in-progress page load
[[self webRequest] setDelegate:nil];
[[self webRequest] cancel];

[self setWebRequest:[ASIWebPageRequest requestWithURL:fileUrl]];
[[self webRequest] setDelegate:self];
[[self webRequest] setDidFailSelector:@selector(webPageFailed:)];
[[self webRequest] setDidFinishSelector:@selector(webPageFinished:)];

// Tell the request to replace urls in this page with local urls
//[[self webRequest] setUrlReplacementMode:ASIReplaceExternalResourcesWithLocalURLs];

// Tell the request to embed external resources directly in the page
[[self webRequest] setUrlReplacementMode:ASIReplaceExternalResourcesWithData];

// It is strongly recommended you use a download cache with ASIWebPageRequest
// When using a cache, external resources are automatically stored in the cache
// and can be pulled from the cache on subsequent page loads
[[self webRequest] setDownloadCache:[ASIDownloadCache sharedCache]];

// Ask the download cache for a place to store the cached data
// This is the most efficient way for an ASIWebPageRequest to store a web page
[[self webRequest] setDownloadDestinationPath:[[ASIDownloadCache sharedCache] pathToStoreCachedResponseDataForRequest:[self webRequest]]];

[[self webRequest] startAsynchronous];

And here is the error I'm getting:

  404 Not Found

Not Found

The requested URL /Users/ledixonuk/Library/Application Support/iPhone  Simulator/4.3.2/Applications/FDF21331-CC80-4ECB-9A33-16AEC073D117/Documents/ItemOne.html was > not found on this server.

Obviously the ASIWebPageRequest can not find the ItemOne.html file in the application document folder, however I've double checked and the file is definitely there.

Has anyone else had a similar issue to this? It's driving me mad trying to sort it out!


问:
Referencing self in a long-running Rust thread
I'm left scratching my head about how to design this. Basically, I want to implement a worker pool – kind of similar to the ThreadPool from the book, but with a twist. In the book, they just pass a closure for one of the threads in the pool to run. However, I would like to have some state for every thread in the pool. Let me explain:

use std::sync::{mpsc, Arc, Mutex};
use std::thread;

struct Job {
    x: usize,
}

struct WorkerPool {
    sender: mpsc::Sender<Job>,
    workers: Vec<Worker>,
}

impl WorkerPool {
    fn new(num_workers: usize) -> WorkerPool {
        let mut workers = Vec::with_capacity(num_workers);
        let (sender, receiver) = mpsc::channel();
        let receiver = Arc::new(Mutex::new(receiver));

        for id in 0..num_workers {
            workers.push(Worker::new(id, receiver.clone()));
        }

        WorkerPool { sender, workers }
    }
}

struct Worker {
    id: usize,
    thread: Option<thread::JoinHandle<()>>,
    receiver: Arc<Mutex<mpsc::Receiver<Job>>>,
}

impl Worker {
    fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
        Worker {
            id,
            thread: None,
            receiver,
        }
    }

    fn start(&mut self) {
        self.thread = Some(thread::spawn(move || loop {
            let job = self.receiver.lock().unwrap().recv().unwrap();
            self.add_to_id(job.x);
        }));
    }

    pub fn add_to_id(&self, x: usize) {
        println!("The result is: {}", self.id + x);
    }
}
```

Every one of my Workers gets an id, and its job is to accept a Job containing a number, and printing its id plus that number (this is, of course, a simplified version; in my real use case, each worker gets an HTTP client and some other state). Pretty simple problem in my eyes, but obviously the code above does not compile.

I realize that the code in Worker::start cannot possibly work, because it is moving self into the thread closure while I am trying to assign to self at the same time.

The question is, how else would I access the fields in the "parent" struct of the thread?

Can I somehow constrain the thread closures lifetime to that of the struct? (Pretty sure the answer is no, because closures have to be 'static). Or the other way around, do I have to make everything 'static here?

答:
Not sure the exact problem you are trying to solve. But you can make your code compile by ensuring that references accessed within thread remain valid throughout the lifetime of thread. Make id remain valid using Arc<Mutex<usize>>

Shows an example where you make your code compile:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=ed750f5ba5db9597efb9b2b80bde2959

```<code>    let recv = self.receiver.clone();
    let id = self.id.clone();
    self.thread = Some(thread::spawn(move || loop {
        let job = recv.lock().unwrap().recv().unwrap();
        //self.add_to_id(job.x);
        *id.lock().unwrap() = job.x;
    }));
</code>```

Body:
I'm left scratching my head about how to design this. Basically, I want to implement a worker pool – kind of similar to the ThreadPool from the book, but with a twist. In the book, they just pass a closure for one of the threads in the pool to run. However, I would like to have some state for every thread in the pool. Let me explain:

use std::sync::{mpsc, Arc, Mutex};
use std::thread;

struct Job {
    x: usize,
}

struct WorkerPool {
    sender: mpsc::Sender<Job>,
    workers: Vec<Worker>,
}

impl WorkerPool {
    fn new(num_workers: usize) -> WorkerPool {
        let mut workers = Vec::with_capacity(num_workers);
        let (sender, receiver) = mpsc::channel();
        let receiver = Arc::new(Mutex::new(receiver));

        for id in 0..num_workers {
            workers.push(Worker::new(id, receiver.clone()));
        }

        WorkerPool { sender, workers }
    }
}

struct Worker {
    id: usize,
    thread: Option<thread::JoinHandle<()>>,
    receiver: Arc<Mutex<mpsc::Receiver<Job>>>,
}

impl Worker {
    fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
        Worker {
            id,
            thread: None,
            receiver,
        }
    }

    fn start(&mut self) {
        self.thread = Some(thread::spawn(move || loop {
            let job = self.receiver.lock().unwrap().recv().unwrap();
            self.add_to_id(job.x);
        }));
    }

    pub fn add_to_id(&self, x: usize) {
        println!("The result is: {}", self.id + x);
    }
}

Every one of my Workers gets an id, and its job is to accept a Job containing a number, and printing its id plus that number (this is, of course, a simplified version; in my real use case, each worker gets an HTTP client and some other state). Pretty simple problem in my eyes, but obviously the code above does not compile.

I realize that the code in Worker::start cannot possibly work, because it is moving self into the thread closure while I am trying to assign to self at the same time.

The question is, how else would I access the fields in the "parent" struct of the thread?

Can I somehow constrain the thread closures lifetime to that of the struct? (Pretty sure the answer is no, because closures have to be 'static). Or the other way around, do I have to make everything 'static here?

Body:
Not sure the exact problem you are trying to solve. But you can make your code compile by ensuring that references accessed within thread remain valid throughout the lifetime of thread. Make id remain valid using Arc<Mutex<usize>>

Shows an example where you make your code compile:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=ed750f5ba5db9597efb9b2b80bde2959

    let recv = self.receiver.clone();
    let id = self.id.clone();
    self.thread = Some(thread::spawn(move || loop {
        let job = recv.lock().unwrap().recv().unwrap();
        //self.add_to_id(job.x);
        *id.lock().unwrap() = job.x;
    }));


问:
How to I make python curses application pipeline friendly?
I am writing a python application that is intended to be used interactively inside unix pipelines. The application should fire up a curses based terminal UI, and based on user interaction, write to the standard output only right before exiting.

Typical usage would be that of a typical pipeline:

```<code>foo_command | my_application | sink_app
</code>```

The problem I am having is that python curses library sends all sorts of things to stdout while the app is running. Furthermore, sink_app starts executing while my_application is running.

How to I prevent curses from polluting stdout?

How do I buffer the output and control when I want to flush it?

Is it possible to control when sink_app starts executing and when it stops accepting input?

From what I gather, I need to save a reference to the stdout file descriptor so I can later write to it. And pass another fd (which one?) to ncurses. Supposedly through newterm(), but this isn't available on python curses binding.

答:
As suggested, juggling input streams. This is not well tested, but appears to be on the right track...</p>

```<code>import os

# back up the piped stdin
mystdin_fd = os.dup(0)

# open the terminal for reading keyboard events
termin = open("/dev/tty")

# replace stdin with the terminal, so curses initscr() and getch() work
os.dup2(termin.fileno(), 0)

# initialise curses - https://docs.python.org/3/howto/curses.html
...

# read from the piped stdin
mystdin = open(mystdin_fd, 'r')
for line in mystdin:
    ...
</code>```

Body:
I am writing a python application that is intended to be used interactively inside unix pipelines. The application should fire up a curses based terminal UI, and based on user interaction, write to the standard output only right before exiting.

Typical usage would be that of a typical pipeline:

foo_command | my_application | sink_app

The problem I am having is that python curses library sends all sorts of things to stdout while the app is running. Furthermore, sink_app starts executing while my_application is running.

How to I prevent curses from polluting stdout?

How do I buffer the output and control when I want to flush it?

Is it possible to control when sink_app starts executing and when it stops accepting input?

From what I gather, I need to save a reference to the stdout file descriptor so I can later write to it. And pass another fd (which one?) to ncurses. Supposedly through newterm(), but this isn't available on python curses binding.

Body:
As suggested, juggling input streams. This is not well tested, but appears to be on the right track...

import os

# back up the piped stdin
mystdin_fd = os.dup(0)

# open the terminal for reading keyboard events
termin = open("/dev/tty")

# replace stdin with the terminal, so curses initscr() and getch() work
os.dup2(termin.fileno(), 0)

# initialise curses - https://docs.python.org/3/howto/curses.html
...

# read from the piped stdin
mystdin = open(mystdin_fd, 'r')
for line in mystdin:
    ...


问:
CocoaPods test target Library not loaded exit code 82
This appears to be an issue with CocoaPods, asking here first as per the guidelines.

Using Xcode 7.3.1, CocoaPods 1.0.1, 1.0.0-beta6 and 1.1.0-beta1

Create a new pod project using pod lib create SwiftTest

Language? Swift

Demo? Yes

Test frameworks? None

View based testing? No

Add a single class function to the auto-generated ReplaceMe.swift file to test the projects integration.

Calling the function from the example project works as expected.

Calling the function from the test project fails with the following error:

```<code>The bundle “SwiftTest_Tests” couldn’t be loaded because it is damaged or missing necessary resources. Try reinstalling the bundle.
(dlopen_preflight(/...): Library not loaded: @rpath/SwiftTest.framework/SwiftTest ... Reason: image not found)
Program ended with exit code: 82
</code>```

Example project: https://github.com/NextFaze/SwiftTest

答:
In my case the test target didn't include .framework

It started to work, after following this step:

Select test target > Build Phases > Add the missing framework to both Link Binary With Libraries and Copy Frameworks

Body:
This appears to be an issue with CocoaPods, asking here first as per the guidelines.

Using Xcode 7.3.1, CocoaPods 1.0.1, 1.0.0-beta6 and 1.1.0-beta1

Create a new pod project using pod lib create SwiftTest

Language? Swift

Demo? Yes

Test frameworks? None

View based testing? No

Add a single class function to the auto-generated ReplaceMe.swift file to test the projects integration.

Calling the function from the example project works as expected.

Calling the function from the test project fails with the following error:

The bundle “SwiftTest_Tests” couldn’t be loaded because it is damaged or missing necessary resources. Try reinstalling the bundle.
(dlopen_preflight(/...): Library not loaded: @rpath/SwiftTest.framework/SwiftTest ... Reason: image not found)
Program ended with exit code: 82

Example project: https://github.com/NextFaze/SwiftTest


问:
Exporting a markdown file with inline PlantUml as a single SVG file
Our orginization uses markdown files with embedded PlantUml. We're trying to export the full markdown file to a single .svg file so we can view it on a third-party application. The plantuml VSCode plugin can export each embedded uml diagram to its own file, but doesn't appear to have an option to export the entire markdown to a new format.

Example

I would like this markdown diagram

```<code>## Read
```plantuml
@startuml
ClassA -> ClassB: Read done (location)
@enduml
```

## Write
```plantuml
@startuml
ClassC -> ClassD: Write done (location)
@enduml
```

## Etc...
</code>```

to be exported to a .svg file that looks something like this:

(This is a screenshot from Visual Studio, so ignore colors/fonts that may be different than a rendered .svg.)

I want the headers to be included as a part of the .svg, not just the class diagrams.

答:
It looks to be related (https://github.com/yzhang-gh/vscode-markdown/issues/684), which embeds PlantUML diagrams in the HTML.

Starting from Markdown All in One v3.0.0, you can export Markdown file to HTML which looks exactly the same as inside VSCode. In your case, just install both extensions (PlantUML and MAIO).

Body:
Our orginization uses markdown files with embedded PlantUml. We're trying to export the full markdown file to a single .svg file so we can view it on a third-party application. The plantuml VSCode plugin can export each embedded uml diagram to its own file, but doesn't appear to have an option to export the entire markdown to a new format.

Example

I would like this markdown diagram

## Read
```plantuml
@startuml
ClassA -> ClassB: Read done (location)
@enduml
```

## Write
```plantuml
@startuml
ClassC -> ClassD: Write done (location)
@enduml
```

## Etc...

to be exported to a .svg file that looks something like this:

(This is a screenshot from Visual Studio, so ignore colors/fonts that may be different than a rendered .svg.)

I want the headers to be included as a part of the .svg, not just the class diagrams.


问:
How to force prebuild script to run at each compile
We currently use Delphi 2009 and GIT to develop an application. We have set up a prebuild script to generate a version number and build ID using information from git and compile this as a resource that is included in the project. The problem is that this script doesn't run on a regular compile. This means that the other developers can end up with a discrepancy between the actual version number and the number in the resource (especially when switching branches in git).

Since we use our software to make some critical calculations, we would like to use this build id to reproduce calculations and track down problems.

Other than trying to force my developers to frequently press shift-F9, how can I ensure that the the prebuild script gets run when necessary (ideally at each compile)?

Jason

UPDATE: It's true that the pre-build script gets run at each compile. The problem was that I expected to get a different result pressing F9 after making a tag in git, even though no code had changed.

答:
Pre build actions do run before every compile.

You state in a comment that the actions sometimes don't run when you press F9. That makes sense because F9, or Run, only invokes a compile if source is deemed to have changed.

A BeforeCompile notifier plug in will behave in exactly the same way. Your solution is to make sure that you compile before running using Ctrl+F9.


问:
How to export Oracle database as system user with os authentication?
User oracle is configured with os authentication and logged in as oracle.

I am trying to to take full db export using the following expression:

exp 'system/as sysdba' file='full_exp.dmp' log='full_exp.log'  consistent='y'

but getting error:

LRM-00108: Invalid positional parameter value 'sysdba'

Also tried with:

exp 'system' file='full_exp.dmp' log='full_exp.log'  consistent='y'

Asks for password for system and empty password doesn't work, throws errors EXP-00004, EXP-00056 and ORA-01017.

Please guide me in taking full db export by os authenticated user.

答:
Doing a full export "as sysdba" is a bad idea - a major security risk (plus "system" doesn't have the sysdba privilege by default anyway). You are better off defining a user with exp_full_database and/or datapump_exp_full_database privileges only, with OS authentication or with an Oracle Wallet to hold the credentials, and using that account to run the full export.

```<code>create user export_user identified by [password];
grant create session, exp_full_database, datapump_exp_full_database to export_user;
</code>```

There is a reference on my blog on how to set up an Oracle Wallet for the credentials. Then your expdp or exp command would look like this:

```<code>exp export_user file='full_exp.dmp' ...
</code>```

or

```<code>expdp export_user directory=export_dir ...
</code>```

Last - seriously consider using Datapump (expdp) rather than the old-school "export" utility (exp). Newer versions of Oracle include object types that export doesn't support, and Datapump is generally faster and more flexible in terms of options.

Body:
Doing a full export "as sysdba" is a bad idea - a major security risk (plus "system" doesn't have the sysdba privilege by default anyway). You are better off defining a user with exp_full_database and/or datapump_exp_full_database privileges only, with OS authentication or with an Oracle Wallet to hold the credentials, and using that account to run the full export.

create user export_user identified by [password];
grant create session, exp_full_database, datapump_exp_full_database to export_user;

There is a reference on my blog on how to set up an Oracle Wallet for the credentials. Then your expdp or exp command would look like this:

exp export_user file='full_exp.dmp' ...

or

expdp export_user directory=export_dir ...

Last - seriously consider using Datapump (expdp) rather than the old-school "export" utility (exp). Newer versions of Oracle include object types that export doesn't support, and Datapump is generally faster and more flexible in terms of options.


问:
Network request failed in react native expo
im using expo in react native.i have a problem when post data to api laravel.its say"Network Request Failed".heres my code:

i hope you can help me guys thankyou.enter image description here

答:
I see that your fetch URL is served using an HTTP endpoint. You can only make requests to HTTPS endpoints from react-native projects.

A possible workaround is to use ngrok. Just download it and run:

```<code>./ngrok http 8000
</code>```

Since your port number is 8000. It will expose an HTTPS endpoint and replace your fetch URL with that link and try fetching the data again

Body:
I see that your fetch URL is served using an HTTP endpoint. You can only make requests to HTTPS endpoints from react-native projects.

A possible workaround is to use ngrok. Just download it and run:

./ngrok http 8000

Since your port number is 8000. It will expose an HTTPS endpoint and replace your fetch URL with that link and try fetching the data again


问:
Prevent error "funk" sound in event monitor OS X
I'm writing an app in swift that lives in the menu bar at the top of the screen. I need both a global and local event monitor to open the popover on a specific key press. There is no problem with the local event monitor, but when the user hits the key command (cmd+shift+8) from inside an app like Finder, the popover opens but the mac error "Funk" sound is played as well. Is there any way I can disable this? Perhaps some way for the app to eat the sound, or register it as a valid keyboard shortcut so the sound is never played?

Here is the code:

```<code>        NSEvent.addGlobalMonitorForEvents(matching: NSEventMask.keyDown, handler: {(event: NSEvent!) -> Void in
        if (event.keyCode == 28 && event.modifierFlags.contains(NSEventModifierFlags.command) && event.modifierFlags.contains(NSEventModifierFlags.shift)){
            self.togglePopover(sender: self)
        }
    });

    NSEvent.addLocalMonitorForEvents(matching: NSEventMask.keyDown, handler: {(event: NSEvent!) -> NSEvent? in
        if (event.keyCode == 28 && event.modifierFlags.contains(NSEventModifierFlags.command) && event.modifierFlags.contains(NSEventModifierFlags.shift)){
            self.togglePopover(sender: self)
        }
        return event
    });
</code>```

答:
In your addGlobalMonitorForEventsMatchingMask handler, save the current volume level and turn the volume down on both channels.  You can do you own event processing in the handler before or after turning down the volume.

Before returning from the handler, restore the original volume, but include a delay to give the OS time to process the event (it will send the "funk," but you won't hear it).

One side effect: if you're listening to something (e.g., music), that will be briefly silenced, too.

My event code:

```<code>[NSEvent addGlobalMonitorForEventsMatchingMask:NSEventMaskKeyDown
                                       handler:^(NSEvent *event) {
    if ( event.type == NSEventTypeKeyDown ) {
        if ( event.keyCode == 106 ) { // F16
            // process the event here
            [self adjustVolume:@(NO)];
            [self performSelector:@selector(adjustVolume:) withObject:@(YES) afterDelay:0.3];
            // 0.2 seconds was too soon
        }
    }
}];
</code>```

My volume adjustment code:

```<code>- (void)adjustVolume:(NSNumber *)offOn
{
    // get audio device...
    AudioObjectPropertyAddress getDefaultOutputDevicePropertyAddress = {
        kAudioHardwarePropertyDefaultOutputDevice,
        kAudioObjectPropertyScopeGlobal,
        kAudioObjectPropertyElementMaster
    };

    AudioDeviceID defaultOutputDeviceID;
    UInt32 infoSize = sizeof(defaultOutputDeviceID);
    AudioObjectGetPropertyData(kAudioObjectSystemObject,
                               &getDefaultOutputDevicePropertyAddress,
                               0, NULL,
                               &infoSize, &defaultOutputDeviceID);

    // structurs to access the left/right volume setting
    AudioObjectPropertyAddress volumePropertyAddress1 = {
        kAudioDevicePropertyVolumeScalar,
        kAudioDevicePropertyScopeOutput,
        1 /* left */
    };
    AudioObjectPropertyAddress volumePropertyAddress2 = {
        kAudioDevicePropertyVolumeScalar,
        kAudioDevicePropertyScopeOutput,
        2 /* right */
    };

    // save the original volume (assumes left/right are the same
    static Float32 volumeOriginal; // could be an iVar

    if ( offOn.boolValue == NO ) { // turn off

        UInt32 volumedataSize = sizeof(volumeOriginal);
        AudioObjectGetPropertyData(defaultOutputDeviceID,
                                   &volumePropertyAddress1,
                                   0, NULL,
                                   &volumedataSize, &volumeOriginal);
        //NSLog(@"volumeOriginal %f",volumeOriginal);

        // turn off both channels
        Float32 volume = 0.0;
        AudioObjectSetPropertyData(defaultOutputDeviceID,
                                   &volumePropertyAddress1,
                                   0, NULL,
                                   sizeof(volume), &volume);
        AudioObjectSetPropertyData(defaultOutputDeviceID,
                                   &volumePropertyAddress2,
                                   0, NULL,
                                   sizeof(volume), &volume);

    } else { // restore

        //NSLog(@"restoring volume");
        AudioObjectSetPropertyData(defaultOutputDeviceID,
                                   &volumePropertyAddress1,
                                   0, NULL,
                                   sizeof(volumeOriginal), &volumeOriginal);
        AudioObjectSetPropertyData(defaultOutputDeviceID,
                                   &volumePropertyAddress2,
                                   0, NULL,
                                   sizeof(volumeOriginal), &volumeOriginal);
    }
}
</code>```

With recognition to Thomas O'Dell for getting me started on this Change OS X system volume programmatically

Body:
I'm writing an app in swift that lives in the menu bar at the top of the screen. I need both a global and local event monitor to open the popover on a specific key press. There is no problem with the local event monitor, but when the user hits the key command (cmd+shift+8) from inside an app like Finder, the popover opens but the mac error "Funk" sound is played as well. Is there any way I can disable this? Perhaps some way for the app to eat the sound, or register it as a valid keyboard shortcut so the sound is never played?

Here is the code:

        NSEvent.addGlobalMonitorForEvents(matching: NSEventMask.keyDown, handler: {(event: NSEvent!) -> Void in
        if (event.keyCode == 28 && event.modifierFlags.contains(NSEventModifierFlags.command) && event.modifierFlags.contains(NSEventModifierFlags.shift)){
            self.togglePopover(sender: self)
        }
    });

    NSEvent.addLocalMonitorForEvents(matching: NSEventMask.keyDown, handler: {(event: NSEvent!) -> NSEvent? in
        if (event.keyCode == 28 && event.modifierFlags.contains(NSEventModifierFlags.command) && event.modifierFlags.contains(NSEventModifierFlags.shift)){
            self.togglePopover(sender: self)
        }
        return event
    });

Body:
In your addGlobalMonitorForEventsMatchingMask handler, save the current volume level and turn the volume down on both channels.  You can do you own event processing in the handler before or after turning down the volume.

Before returning from the handler, restore the original volume, but include a delay to give the OS time to process the event (it will send the "funk," but you won't hear it).

One side effect: if you're listening to something (e.g., music), that will be briefly silenced, too.

My event code:

[NSEvent addGlobalMonitorForEventsMatchingMask:NSEventMaskKeyDown
                                       handler:^(NSEvent *event) {
    if ( event.type == NSEventTypeKeyDown ) {
        if ( event.keyCode == 106 ) { // F16
            // process the event here
            [self adjustVolume:@(NO)];
            [self performSelector:@selector(adjustVolume:) withObject:@(YES) afterDelay:0.3];
            // 0.2 seconds was too soon
        }
    }
}];

My volume adjustment code:

- (void)adjustVolume:(NSNumber *)offOn
{
    // get audio device...
    AudioObjectPropertyAddress getDefaultOutputDevicePropertyAddress = {
        kAudioHardwarePropertyDefaultOutputDevice,
        kAudioObjectPropertyScopeGlobal,
        kAudioObjectPropertyElementMaster
    };

    AudioDeviceID defaultOutputDeviceID;
    UInt32 infoSize = sizeof(defaultOutputDeviceID);
    AudioObjectGetPropertyData(kAudioObjectSystemObject,
                               &getDefaultOutputDevicePropertyAddress,
                               0, NULL,
                               &infoSize, &defaultOutputDeviceID);

    // structurs to access the left/right volume setting
    AudioObjectPropertyAddress volumePropertyAddress1 = {
        kAudioDevicePropertyVolumeScalar,
        kAudioDevicePropertyScopeOutput,
        1 /* left */
    };
    AudioObjectPropertyAddress volumePropertyAddress2 = {
        kAudioDevicePropertyVolumeScalar,
        kAudioDevicePropertyScopeOutput,
        2 /* right */
    };

    // save the original volume (assumes left/right are the same
    static Float32 volumeOriginal; // could be an iVar

    if ( offOn.boolValue == NO ) { // turn off

        UInt32 volumedataSize = sizeof(volumeOriginal);
        AudioObjectGetPropertyData(defaultOutputDeviceID,
                                   &volumePropertyAddress1,
                                   0, NULL,
                                   &volumedataSize, &volumeOriginal);
        //NSLog(@"volumeOriginal %f",volumeOriginal);

        // turn off both channels
        Float32 volume = 0.0;
        AudioObjectSetPropertyData(defaultOutputDeviceID,
                                   &volumePropertyAddress1,
                                   0, NULL,
                                   sizeof(volume), &volume);
        AudioObjectSetPropertyData(defaultOutputDeviceID,
                                   &volumePropertyAddress2,
                                   0, NULL,
                                   sizeof(volume), &volume);

    } else { // restore

        //NSLog(@"restoring volume");
        AudioObjectSetPropertyData(defaultOutputDeviceID,
                                   &volumePropertyAddress1,
                                   0, NULL,
                                   sizeof(volumeOriginal), &volumeOriginal);
        AudioObjectSetPropertyData(defaultOutputDeviceID,
                                   &volumePropertyAddress2,
                                   0, NULL,
                                   sizeof(volumeOriginal), &volumeOriginal);
    }
}

With recognition to Thomas O'Dell for getting me started on this Change OS X system volume programmatically


问:
aggregate dataframe horizontally
I have the following data:

```<code>inputdata = [[1,'long',30.2,'Win'],[1,'long',-12.4,'Loss'],
            [2,'short',-12.3,'Loss'],[1,'long',3.2,'Win'],
            [3,'short',0.0,'B/E'],[3,'short',23.2,'Win'],
            [3,'long',3.2,'Win'],[4,'short',-4.2,'Loss']]
datadf = DataFrame(columns=['AssetId','Direction','PnL','W_L'], data = inputdata)

datadf

    AssetId Direction   PnL     W_L
0   1       long        30.2    Win
1   1       long       -12.4    Loss
2   2       short      -12.3    Loss
3   1       long        3.2     Win
4   3       short       0.0     B/E
5   3       short       23.2    Win
6   3       long        3.2     Win
7   4       short      -4.2     Loss
</code>```

Now I want to aggregate this further into a new dataframe that looks like this mock up (a few sample rows added, more stats to be added:

```<code>    Stat    Long    Short   Total
0   Trades  4       4       8
1   Won     3       1       4
2   Lost    1       2       3
    (...)
</code>```

I tried this:

```<code>datadf.groupby(['Direction'])['PnL'].count()
Direction
long     4
short    4
Name: PnL, dtype: int64
</code>```

This produces the necessary data, but I would have to fill my aggregation data frame field by field, which seems cumbersome and I am not even sure how to get the exact value into each row/column. Based on this example, is there a better way to achieve this goal?

答:
Use pivot_table:

```<code>res = pd.pivot_table(df.iloc[:,1:], index=["W_L"], columns=["Direction"], aggfunc="count").droplevel(0, 1)
res["total"] = res.sum(1)

print (res.append(res.sum().rename(index="Trades")))

Direction  long  short  total
W_L
B/E         NaN    1.0    1.0
Loss        1.0    2.0    3.0
Win         3.0    1.0    4.0
Trades      4.0    4.0    8.0
</code>```

Title: aggregate dataframe horizontally

Body:
I have the following data:

inputdata = [[1,'long',30.2,'Win'],[1,'long',-12.4,'Loss'],
            [2,'short',-12.3,'Loss'],[1,'long',3.2,'Win'],
            [3,'short',0.0,'B/E'],[3,'short',23.2,'Win'],
            [3,'long',3.2,'Win'],[4,'short',-4.2,'Loss']]
datadf = DataFrame(columns=['AssetId','Direction','PnL','W_L'], data = inputdata)

datadf

    AssetId Direction   PnL     W_L
0   1       long        30.2    Win
1   1       long       -12.4    Loss
2   2       short      -12.3    Loss
3   1       long        3.2     Win
4   3       short       0.0     B/E
5   3       short       23.2    Win
6   3       long        3.2     Win
7   4       short      -4.2     Loss

Now I want to aggregate this further into a new dataframe that looks like this mock up (a few sample rows added, more stats to be added:

    Stat    Long    Short   Total
0   Trades  4       4       8
1   Won     3       1       4
2   Lost    1       2       3
    (...)

I tried this:

datadf.groupby(['Direction'])['PnL'].count()
Direction
long     4
short    4
Name: PnL, dtype: int64

This produces the necessary data, but I would have to fill my aggregation data frame field by field, which seems cumbersome and I am not even sure how to get the exact value into each row/column. Based on this example, is there a better way to achieve this goal?

Body:
Use pivot_table:

res = pd.pivot_table(df.iloc[:,1:], index=["W_L"], columns=["Direction"], aggfunc="count").droplevel(0, 1)
res["total"] = res.sum(1)

print (res.append(res.sum().rename(index="Trades")))

Direction  long  short  total
W_L
B/E         NaN    1.0    1.0
Loss        1.0    2.0    3.0
Win         3.0    1.0    4.0
Trades      4.0    4.0    8.0


问:
TFS is saying I have a file with status 'lock/edit' and I cannot undo it
In Team Explorer it says I have a file with the status of 'lock,edit' and the undo option is not enabled so I am not sure how to unlock this file.

I am the user who it is reporting that has the lock,edit but I can't undo it.

What options do I have?

答:
You may have multiple workspace. Go to Source Control Explorer -- Workspace, to check whether you have multiple workspace. The change may exist in other workspace. You need to select correct workspace and undo the changes.

Another way is using TFS powertools. If you install TFS Powertools, you'll see Find by Status option by right click the locked file and select Find:

Click Find by Status -- Find, you 'll see the locked files list. Then right click the files and select Undo, the file would be released.


问:
"UserWarning: An input could not be retrieved. It could be because a worker has died. We do not have any information on the lost sample."
While training model I got this warning "UserWarning: An input could not be retrieved. It could be because a worker has died.We do not have any information on the lost sample.)", after showing this warning, model starts training. What does this warning means? Is it something that will affect my training and I need to worry about?</p>

答:
If you are running the training in GPU, the Warning will occur. You have to know that there are two running progress during the fit_generator running.

GPU, trains the IMAGE DATASETS with each steps in each epoch.

CPU, prepares the IMAGE DATASETS with each batch size.

While, they are parallel tasks. So if CPU's compute is lower than GPUs', the Warning occurs.

Solution:

Just set your batch_size smaller or upgrade your CPU config.


问:
Extract string between two characters in a string
I have a set of strings that has datetime values and I would like to extract them. I am not sure if this is even possible using T-SQL.

```<code>CREATE TABLE #Temp (
BLOB_NM VARCHAR(100)
);

INSERT INTO #Temp
SELECT 'products_country_20200528102030.txt'
UNION ALL
SELECT 'products_territory_20190528102030.txt'
UNION ALL
SELECT 'products_country_2020-05-20_20200528102030.txt'
;
</code>```

Expected Results:

```<code>20200528102030
20190528102030
20200528102030
</code>```

答:
i suppose :

Files extension are not always 3 of characters length

Your Date/Time format are always on 14 characters

Try this :

```<code>select
CONVERT(DATETIME, STUFF(STUFF(STUFF(left(right(BLOB_NM, charindex('_', reverse(BLOB_NM) + '_') - 1), 14),13,0,':'),11,0,':'),9,0,' ')) as Result
from #Temp
</code>```

Body:
I have a set of strings that has datetime values and I would like to extract them. I am not sure if this is even possible using T-SQL.

CREATE TABLE #Temp (
BLOB_NM VARCHAR(100)
);

INSERT INTO #Temp
SELECT 'products_country_20200528102030.txt'
UNION ALL
SELECT 'products_territory_20190528102030.txt'
UNION ALL
SELECT 'products_country_2020-05-20_20200528102030.txt'
;

Expected Results:

20200528102030
20190528102030
20200528102030

Body:
i suppose :

Files extension are not always 3 of characters length

Your Date/Time format are always on 14 characters

Try this :

select
CONVERT(DATETIME, STUFF(STUFF(STUFF(left(right(BLOB_NM, charindex('_', reverse(BLOB_NM) + '_') - 1), 14),13,0,':'),11,0,':'),9,0,' ')) as Result
from #Temp


问:
Getting error MSB406 "TypeScript.Tasks.CheckFileSystemCaseSensitive" in Windows Powershell but the same build works in VS Powershell
While trying to build a newly setup project using npm run build, I am facing the below mentioned error in Powershell on Windows, however, it runs fine inside the Visual Studio integrated Powershell.

Error:

C:..\src\packages\Microsoft.Portal.Tools.5.0.303.3330\build\TypeScript\tools\Microsoft.TypeScript.targets(219,5): error MSB406 2: The "TypeScript.Tasks.CheckFileSystemCaseSensitive" task could not be loaded from the assembly C:..\src\packages\Microsoft.Portal.Tools.5.0.303.3330\build\TypeScript\build..\tools\net45\TypeScript.Tasks.dll. Could not load file or assembly 'Microsoft.Build.Utilities.Core, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified. Confirm that the  declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask[C:..\src\Default\Extension\Extension.csproj]

答:
Getting error MSB406 “TypeScript.Tasks.CheckFileSystemCaseSensitive”
  in Windows Powershell but the same build works in VS Powershell

Since you built extension project successfully in vs powershell, I think you put a wrong MSBuild version in PATH system environment variables.

Instead, you should use C:\Program Files (x86)\Microsoft Visual Studio\2019\xxx\MSBuild\Current\Bin\MSBuild.exe.

Solution

1) check the PATH and remove the previous wrong MSBuild path.

2) then input C:\Program Files (x86)\Microsoft Visual Studio\2019\xxx\MSBuild\Current\Bin in PATH, restart Windows Powershell to build again.


问:
Make folders nodes in TreeView, and move nodes between them
I want to make a treeview structure like this. I can only find an example on how to copy nodes.

But I don't know how to organize it to folders, to move nodes between them. Any advice will be very helpful.
I'm using winforms.

答:
Basically you are going to have a recursive loop like so:

```<code>protected void Populate(TreeNode parentNode, DirectoryInfo directory)
{
    foreach (DirectoryInfo dir in directory.GetDirectories())
    {
        TreeNode node = parentNode.Nodes[dir.Name]
            ?? parentNode.Nodes.Add(dir.Name, dir.Name);
        node.Tag = dir;
        // node.ContextMenuStrip = cmenu;
        Populate(node, dir);
    }
}
</code>```

To drag and drop with TreeView, see this Microsoft example.

Body:
Basically you are going to have a recursive loop like so:

protected void Populate(TreeNode parentNode, DirectoryInfo directory)
{
    foreach (DirectoryInfo dir in directory.GetDirectories())
    {
        TreeNode node = parentNode.Nodes[dir.Name]
            ?? parentNode.Nodes.Add(dir.Name, dir.Name);
        node.Tag = dir;
        // node.ContextMenuStrip = cmenu;
        Populate(node, dir);
    }
}

To drag and drop with TreeView, see this Microsoft example.


问:
Adding a new array does not update my total array count in Swift Xcode
Problem: Initially my count is correct, however, adding a new array does not update my total array count label.

I have a View Controller (VC) that shows a label with a count of total arrays.
I have a Table View Controller (TVC) that arrays are added or deleted from.
I have a separate struct file to hold the arrays.

The label populates with the correct number of arrays when I run it. However, adding a new array item (via TVC) in the simulator does not update the label on the VC.

Questions:

Should I put the count in a function in VC? It is currently in the viewDidLoad()

Should I then call the function in TVC when adding or deleting an array?

If 2 is yes then do I reference the function in VTC? Would it simply be
updateCount() or do I have to reference the VC controller e.g.
ViewController.updateCount()

I have tried both ways but it does not seem to work, if I can get confirmation that would be great then I can make it work.

Thank you in Advance

答:
If you do something like this:

```<code>var x = 0
var y = x
x = 7
print(y) //y is still 0
</code>```

You need to update the count whenever you change the amount of arrays. To call a view controller's function from another view controller, you need to use a protocol. I suggest you research how to make protocols in swift - I would help you but it's hard without being able to see the code.

Body:
If you do something like this:

var x = 0
var y = x
x = 7
print(y) //y is still 0

You need to update the count whenever you change the amount of arrays. To call a view controller's function from another view controller, you need to use a protocol. I suggest you research how to make protocols in swift - I would help you but it's hard without being able to see the code.


问:
HTML / CSS Hide / Show Page Objects Without JavaScript Toggle Switch
How to use a single function to toggle multiple buttons/images. Here is what I have now for a demo. It only works for single button/images but I need to make multiple control.

body,
html {
  height: 100%;
}

#bg {
  background-image: url(http://basicblue.biz/treasure/treasuremap_01.jpg);
  height: 100%;
  width: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: 1080px 1080px;
  position: relative;
}

#menu {
  position: absolute;
  top: 50px;
  left: 50px;
  z-index: 100;
}

#menu button {
  background-color: lightblue;
  border: 1px solid white;
  color: darkblue;
  padding: 10px 24px;
  cursor: pointer;
  display: block;
}

#mark01 {
  position: absolute;
  top: 240px;
  right: 490px;
  z-index: 80;
}

#mark02 {
  position: absolute;
  top: 480px;
  left: 460px;
  z-index: 80;
}

#mark03 {
  position: absolute;
  bottom: 260px;
  right: 490px;
  z-index: 80;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="styles.css">
  <title>Treasure Map</title>
</head>

<body>

  <div id="menu">
    <button onclick="myMark01()">Marker 1</button>
    <button onclick="myMark02()">Marker 2</button>
    <button onclick="myMark03()">Marker 3</button>
  </div>

  <div id="bg">
    <img id="mark01" src="http://basicblue.biz/treasure/xmark_01.png">
    <img id="mark02" src="http://basicblue.biz/treasure/xmark_02.png">
    <img id="mark03" src="http://basicblue.biz/treasure/xmark_03.png">
  </div>

  <script>
    function myMark01() {
      var x = document.getElementById("mark01");
      if (x.style.display === "none") {
        x.style.display = "block";
      } else {
        x.style.display = "none";
      }
    }

    function myMark02() {
      var x = document.getElementById("mark02");
      if (x.style.display === "none") {
        x.style.display = "block";
      } else {
        x.style.display = "none";
      }
    }

    function myMark03() {
      var x = document.getElementById("mark03");
      if (x.style.display === "none") {
        x.style.display = "block";
      } else {
        x.style.display = "none";
      }
    }
  </script>

</body>

</html></code>```

I want to do this with Pure HTML / CSS. Is it achievable or how to make this code more efficient.

So basically I need each button to control a different image layer allowing for individual control.

Thanks,

答:
Ok here is a modified example using the tips you provided. Thanks

body, html {
  height: 100%;
}

#bg {
  background-image: url(http://basicblue.biz/treasure/treasuremap_01.jpg);
  height: 100%;
  width: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: 1080px 1080px;
  position: relative;
  }

  #menu {
    display: block;
    width: 100px;
  }

  input:checked + .hidable {
    display: none;
  }

  input:not(:checked) + .showable {
    display: none;
  }

  #mark01 {
    position: absolute;
    top: 240px;
    right: 490px;
  }

  #mark02 {
    position: absolute;
    top: 480px;
    left: 460px;
  }

  #mark03 {
    position: absolute;
    bottom: 260px;
    right: 490px;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<title>Treasure Map</title>
</head>
<body>

  <div id="bg">
    <div id="menu">
      <input type="checkbox" /> Marker 1
      <div class="showable"><img id="mark01" src="http://basicblue.biz/treasure/xmark_01.png" alt="X Mark Red"></div>
      <input type="checkbox" /> Marker 2
      <div class="showable"><img id="mark02" src="http://basicblue.biz/treasure/xmark_02.png" alt="X Mark Green"></div>
      <input type="checkbox" /> Marker 3
      <div class="showable"><img id="mark03" src="http://basicblue.biz/treasure/xmark_03.png" alt="X Mark Magenta"></div>
    </div>
  </div>

</body>
</html></code>```

This works really nicely. The only issue I am facing is that I have to figure out how to lock my background image and the keep the marks I am toggling on/off to their respective fixed positions. Every time the browser window is resized everything breaks visually (any tips for that?)...

Your tips helped and now pure HTML / CSS.

Thanks,

Body:
How to use a single function to toggle multiple buttons/images. Here is what I have now for a demo. It only works for single button/images but I need to make multiple control.

body,
html {
  height: 100%;
}

#bg {
  background-image: url(http://basicblue.biz/treasure/treasuremap_01.jpg);
  height: 100%;
  width: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: 1080px 1080px;
  position: relative;
}

#menu {
  position: absolute;
  top: 50px;
  left: 50px;
  z-index: 100;
}

#menu button {
  background-color: lightblue;
  border: 1px solid white;
  color: darkblue;
  padding: 10px 24px;
  cursor: pointer;
  display: block;
}

#mark01 {
  position: absolute;
  top: 240px;
  right: 490px;
  z-index: 80;
}

#mark02 {
  position: absolute;
  top: 480px;
  left: 460px;
  z-index: 80;
}

#mark03 {
  position: absolute;
  bottom: 260px;
  right: 490px;
  z-index: 80;
}

<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="styles.css">
  <title>Treasure Map</title>

    <button onclick="myMark01()">Marker 1</button>
    <button onclick="myMark02()">Marker 2</button>
    <button onclick="myMark03()">Marker 3</button>

I want to do this with Pure HTML / CSS. Is it achievable or how to make this code more efficient.

So basically I need each button to control a different image layer allowing for individual control.

Thanks,

Body:
Ok here is a modified example using the tips you provided. Thanks

body, html {
  height: 100%;
}

#bg {
  background-image: url(http://basicblue.biz/treasure/treasuremap_01.jpg);
  height: 100%;
  width: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: 1080px 1080px;
  position: relative;
  }

  #menu {
    display: block;
    width: 100px;
  }

  input:checked + .hidable {
    display: none;
  }

  input:not(:checked) + .showable {
    display: none;
  }

  #mark01 {
    position: absolute;
    top: 240px;
    right: 490px;
  }

  #mark02 {
    position: absolute;
    top: 480px;
    left: 460px;
  }

  #mark03 {
    position: absolute;
    bottom: 260px;
    right: 490px;
  }

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<title>Treasure Map</title>
</head>
<body>

  <div id="bg">
    <div id="menu">
      <input type="checkbox" /> Marker 1
      <div class="showable"><img id="mark01" src="http://basicblue.biz/treasure/xmark_01.png" alt="X Mark Red"></div>
      <input type="checkbox" /> Marker 2
      <div class="showable"><img id="mark02" src="http://basicblue.biz/treasure/xmark_02.png" alt="X Mark Green"></div>
      <input type="checkbox" /> Marker 3
      <div class="showable"><img id="mark03" src="http://basicblue.biz/treasure/xmark_03.png" alt="X Mark Magenta"></div>
    </div>
  </div>

</body>
</html>

This works really nicely. The only issue I am facing is that I have to figure out how to lock my background image and the keep the marks I am toggling on/off to their respective fixed positions. Every time the browser window is resized everything breaks visually (any tips for that?)...

Your tips helped and now pure HTML / CSS.

Thanks,


问:
"missing script: build:ssr" error when trying to build server Angular Universal app
I created simple Angular app and then tried to create a server-side app using Angular Universal. However, in every single tutorial the first step is to run npm run build:ssr which in my case throws an error:

npm ERR! missing script: build:ssr

I must be missing something obvious but I can't figure out what. I checked StackOverflow for this issue, there is one, however, without accepted answer. One hint would be to check the Angular/Angular Universal version, but these seems to be aligned for me:

```<code>    "@angular/common": "~7.2.0",
    "@angular/compiler": "~7.2.0",
    "@angular/core": "~7.2.0",
    "@angular/forms": "~7.2.0",
    "@angular/http": "^7.2.14",
    "@angular/platform-browser": "~7.2.0",
    "@angular/platform-browser-dynamic": "~7.2.0",
    "@angular/platform-server": "^7.2.14",
    "@angular/router": "~7.2.0",
    "@ng-toolkit/universal": "^7.1.2",
    "@nguniversal/common": "^7.1.1",
    "@nguniversal/express-engine": "^7.1.1",
    "@nguniversal/module-map-ngfactory-loader": "^7.1.1",
</code>```

Any help would be much appreciated. Thanks!

答:
this issue is occurring probably because you might not have run the
@nguniversal express-engine command :

```<code> ng add @nguniversal/express-engine --clientProject (Project Name)
</code>```

Project name can be found in angular.json file under projects attribute.

This will generate server module and build:ssr It should work after running this hopefully.

Body:
I created simple Angular app and then tried to create a server-side app using Angular Universal. However, in every single tutorial the first step is to run npm run build:ssr which in my case throws an error:

npm ERR! missing script: build:ssr

I must be missing something obvious but I can't figure out what. I checked StackOverflow for this issue, there is one, however, without accepted answer. One hint would be to check the Angular/Angular Universal version, but these seems to be aligned for me:

    "@angular/common": "~7.2.0",
    "@angular/compiler": "~7.2.0",
    "@angular/core": "~7.2.0",
    "@angular/forms": "~7.2.0",
    "@angular/http": "^7.2.14",
    "@angular/platform-browser": "~7.2.0",
    "@angular/platform-browser-dynamic": "~7.2.0",
    "@angular/platform-server": "^7.2.14",
    "@angular/router": "~7.2.0",
    "@ng-toolkit/universal": "^7.1.2",
    "@nguniversal/common": "^7.1.1",
    "@nguniversal/express-engine": "^7.1.1",
    "@nguniversal/module-map-ngfactory-loader": "^7.1.1",

Any help would be much appreciated. Thanks!

Body:
this issue is occurring probably because you might not have run the
@nguniversal express-engine command :

 ng add @nguniversal/express-engine --clientProject (Project Name)

Project name can be found in angular.json file under projects attribute.

This will generate server module and build:ssr It should work after running this hopefully.


问:
EC2 Name tag and its position
I have this code, it works but I soon realized standards is not something we do. In my code I am getting the Tags value for 'Name'. However, the way i do it, I am assuming it is the first tag at position 0. I am wrong to assume. How can I make it more robust to just look for value of the key 'Name' irrelevant of position?</p>

```<code> response = client.describe_instances(Filters=[{'Name':'tag-key','Values':['Name']}])

for item in response['Reservations']:
    #pprint(item['Instances'])
        print("AWS Account ID: {}".format(item['OwnerId']))
        for instance_id in item['Instances']:
            #print(instance_id)
            Tags = instance_id['Tags'][0]['Value']
            State = instance_id['State']['Name']
            print("EC2 Name: {}".format(Tags))
            print("Instance Id is: {}\nInstance Type is: {}".format(instance_id['InstanceId'],instance_id['InstanceType']))

</code>```

答:
For a more Pythonic version:

response = ec2_client.describe_instances()

for reservation in response['Reservations']:
    for instance in reservation['Instances']:
        if name := [tag['Value'] for tag in instance['Tags'] if tag['Key'] == 'Name']:
            print(name[0])
```

<p>Or using resource methods:</p>

<pre class="lang-py prettyprint-override"><code>ec2_resource = boto3.resource('ec2')

for instance in ec2_resource.instances.all():
    if name := [tag['Value'] for tag in instance.tags if tag['Key'] == 'Name']:
        print(name[0])
</code>```

(Requires Python 3.8)

Title: EC2 Name tag and its position

Body:
I have this code, it works but I soon realized standards is not something we do. In my code I am getting the Tags value for 'Name'. However, the way i do it, I am assuming it is the first tag at position 0. I am wrong to assume. How can I make it more robust to just look for value of the key 'Name' irrelevant of position?

 response = client.describe_instances(Filters=[{'Name':'tag-key','Values':['Name']}])

for item in response['Reservations']:
    #pprint(item['Instances'])
        print("AWS Account ID: {}".format(item['OwnerId']))
        for instance_id in item['Instances']:
            #print(instance_id)
            Tags = instance_id['Tags'][0]['Value']
            State = instance_id['State']['Name']
            print("EC2 Name: {}".format(Tags))
            print("Instance Id is: {}\nInstance Type is: {}".format(instance_id['InstanceId'],instance_id['InstanceType']))

Body:
For a more Pythonic version:

response = ec2_client.describe_instances()

for reservation in response['Reservations']:
    for instance in reservation['Instances']:
        if name := [tag['Value'] for tag in instance['Tags'] if tag['Key'] == 'Name']:
            print(name[0])

Or using resource methods:

ec2_resource = boto3.resource('ec2')

for instance in ec2_resource.instances.all():
    if name := [tag['Value'] for tag in instance.tags if tag['Key'] == 'Name']:
        print(name[0])

(Requires Python 3.8)


问:
How to dynamically filter sublist based on addField?
I have a Suitelet that calls a sublist but I would like to trigger a filter when an "addButton" is clicked.

Suitelet:

```<code>    var form = serverWidget.createForm({ title : 'Unbilled Orders', hideNavBar : false });
    form.addField({id: 'name_criteria', label: 'Name', type: serverWidget.FieldType.MULTISELECT, source: 'customer'});
    form.addButton({label: 'Filter',id: 'custpage_mybutton',functionName: 'myButtonFunction()'});

    var name_field = context.request.parameters.name_criteria;
    //# Filter does not work as name_field='' #
    var objSublistSearch = search.load({ id: SEARCH_ID });
    var filterArray = objSublistSearch.filters;
    filterArray.push(search.createFilter({ name: 'entity', operator: search.Operator.ANYOF, values: name_field }));
    objSublistSearch.filters = filterArray;

    var SublistSearch = objSublistSearch.run();
...
 context.response.writePage(form);
</code>```

Client script (does not update the sublist):

```<code>function myButtonFunction() {
           // Load current record in order to manipulate it
           var objRecord  = currentRecord.get()
         var field2 =  objRecord.getValue({
               fieldId: 'name_criteria',
           });
         log.debug("field2",field2 );}
</code>```

答:
You're only looking at the "body" field not a sublist.

Try using sublist functions within the client script.

```<code>var lines = objRecord.getLineCount({sublistId:'custpage_sublistid'});

for (line = 0; line < lines; line++) {

    objRecord.selectLine({sublistId:'custpage_sublistid', line:line });

    var existingValue = objRecord.getSublistValue({sublistId:'custpage_sublistid', fieldId:'custpage_columnid', line: line });

    objRecord.setCurrentSublistValue({sublistId:'custpage_sublistid', fieldId:'custpage_columnid', value: 12345 });

    // do other stuff

}
</code>```

Body:
I have a Suitelet that calls a sublist but I would like to trigger a filter when an "addButton" is clicked.

Suitelet:

    var form = serverWidget.createForm({ title : 'Unbilled Orders', hideNavBar : false });
    form.addField({id: 'name_criteria', label: 'Name', type: serverWidget.FieldType.MULTISELECT, source: 'customer'});
    form.addButton({label: 'Filter',id: 'custpage_mybutton',functionName: 'myButtonFunction()'});

    var name_field = context.request.parameters.name_criteria;
    //# Filter does not work as name_field='' #
    var objSublistSearch = search.load({ id: SEARCH_ID });
    var filterArray = objSublistSearch.filters;
    filterArray.push(search.createFilter({ name: 'entity', operator: search.Operator.ANYOF, values: name_field }));
    objSublistSearch.filters = filterArray;

    var SublistSearch = objSublistSearch.run();
...
 context.response.writePage(form);

Client script (does not update the sublist):

function myButtonFunction() {
           // Load current record in order to manipulate it
           var objRecord  = currentRecord.get()
         var field2 =  objRecord.getValue({
               fieldId: 'name_criteria',
           });
         log.debug("field2",field2 );}

Body:
You're only looking at the "body" field not a sublist.

Try using sublist functions within the client script.

var lines = objRecord.getLineCount({sublistId:'custpage_sublistid'});

for (line = 0; line < lines; line++) {

    objRecord.selectLine({sublistId:'custpage_sublistid', line:line });

    var existingValue = objRecord.getSublistValue({sublistId:'custpage_sublistid', fieldId:'custpage_columnid', line: line });

    objRecord.setCurrentSublistValue({sublistId:'custpage_sublistid', fieldId:'custpage_columnid', value: 12345 });

    // do other stuff

}


问:
Bad packaged library - Angular custom library - NPM
I am learning to publish a simple Angular library to NPM. I followed many different tutorials (such as here or here or here) and got the package on the NPM. However, when I try using it in a test project, it always throws an error.

WHAT I DID

TL;DR: You can find what I was attempting to make from github and npm.

I created the new angular project as outlined in their documentation:

```<code>ng new angularx-wrapper-workspace --create-application=false
cd angularx-wrapper-workspace
ng generate library angularx-wrapper
</code>```

My folder structure is as followed:

I develop the library, simply put, these are the core files:

//public-api.ts
export * from './lib/angularx-wrapper.module';
export * from './lib/angularx-wrapper.component';
```
<pre class="lang-js prettyprint-override"><code>//angularx-wrapper.module.ts
import { NgModule } from '@angular/core';
import { AngularXWrapperComponent } from './angularx-wrapper.component';
import { CommonModule } from '@angular/common';

@NgModule({
  declarations: [AngularXWrapperComponent],
  imports: [
      CommonModule
  ],
  exports: [AngularXWrapperComponent]
})
export class AngularXWrapperModule { }

</code>```

(The error appears to be with the npm packing process, so I will omit irrelevant details)

I build the library for publishing:

```<code>ng build angularx-wrapper --prod
</code>```

I publish the library:

```<code>npm publish
</code>```

The library was published successfully. However, when I create a new test application to see if it works (the test application is completely different and not inside the library folder):

```<code>ng new test
cd test
npm install angularx-wrapper
</code>```

QUESTIONS

Two things happened. The first thing was that I was not able to import the library to my test app:

The only way to import it is to do this:

Even after successfully importing the library to my test app, running it produced this error:

```<code>ERROR in ./node_modules/angularx-wrapper/src/lib/angularx-wrapper.component.ts
Module build failed (from ./node_modules/@ngtools/webpack/src/index.js):
Error: /code/user/test/node_modules/angularx-wrapper/src/lib/angularx-wrapper.component.ts is missing from the TypeScript compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property.
The missing file seems to be part of a third party library. TS files in published libraries are often a sign of a badly packaged library. Please open an issue in the library repository to alert its author and ask them to package the library using the Angular Package Format.
    at AngularCompilerPlugin.getCompiledFile (/code/user/code/user/test/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:933:23)
    at /code/afunworm/code/user/test/node_modules/@ngtools/webpack/src/loader.js:41:31
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
ERROR in ./node_modules/angularx-wrapper/src/lib/angularx-wrapper.module.ts
Module build failed (from ./node_modules/@ngtools/webpack/src/index.js):
Error: /code/user/code/user/test/node_modules/angularx-wrapper/src/lib/angularx-wrapper.module.ts is missing from the TypeScript compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property.
The missing file seems to be part of a third party library. TS files in published libraries are often a sign of a badly packaged library. Please open an issue in the library repository to alert its author and ask them to package the library using the Angular Package Format.
    at AngularCompilerPlugin.getCompiledFile (/code/user/code/user/test/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:933:23)
    at /code/user/code/user/test/node_modules/@ngtools/webpack/src/loader.js:41:31
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
</code>```

What step did I do that was wrong? Was it the folder structure of my library that caused the problem? I can't seem to find any resources on how to resolve this.

答: I have found the problems. The problem is that you have to run npm publish from the dist folder, NOT the library folder itself. It was rather a silly mistake, but there's no documentation specifically for that mistake so I figure I will leave the answer here.

Body:
I am learning to publish a simple Angular library to NPM. I followed many different tutorials (such as here or here or here) and got the package on the NPM. However, when I try using it in a test project, it always throws an error.

WHAT I DID

TL;DR: You can find what I was attempting to make from github and npm.

I created the new angular project as outlined in their documentation:

ng new angularx-wrapper-workspace --create-application=false
cd angularx-wrapper-workspace
ng generate library angularx-wrapper

My folder structure is as followed:

I develop the library, simply put, these are the core files:

//public-api.ts
export * from './lib/angularx-wrapper.module';
export * from './lib/angularx-wrapper.component';

//angularx-wrapper.module.ts
import { NgModule } from '@angular/core';
import { AngularXWrapperComponent } from './angularx-wrapper.component';
import { CommonModule } from '@angular/common';

@NgModule({
  declarations: [AngularXWrapperComponent],
  imports: [
      CommonModule
  ],
  exports: [AngularXWrapperComponent]
})
export class AngularXWrapperModule { }

(The error appears to be with the npm packing process, so I will omit irrelevant details)

I build the library for publishing:

ng build angularx-wrapper --prod

I publish the library:

npm publish

The library was published successfully. However, when I create a new test application to see if it works (the test application is completely different and not inside the library folder):

ng new test
cd test
npm install angularx-wrapper

QUESTIONS

Two things happened. The first thing was that I was not able to import the library to my test app:

The only way to import it is to do this:

Even after successfully importing the library to my test app, running it produced this error:

ERROR in ./node_modules/angularx-wrapper/src/lib/angularx-wrapper.component.ts
Module build failed (from ./node_modules/@ngtools/webpack/src/index.js):
Error: /code/user/test/node_modules/angularx-wrapper/src/lib/angularx-wrapper.component.ts is missing from the TypeScript compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property.
The missing file seems to be part of a third party library. TS files in published libraries are often a sign of a badly packaged library. Please open an issue in the library repository to alert its author and ask them to package the library using the Angular Package Format.
    at AngularCompilerPlugin.getCompiledFile (/code/user/code/user/test/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:933:23)
    at /code/afunworm/code/user/test/node_modules/@ngtools/webpack/src/loader.js:41:31
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
ERROR in ./node_modules/angularx-wrapper/src/lib/angularx-wrapper.module.ts
Module build failed (from ./node_modules/@ngtools/webpack/src/index.js):
Error: /code/user/code/user/test/node_modules/angularx-wrapper/src/lib/angularx-wrapper.module.ts is missing from the TypeScript compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property.
The missing file seems to be part of a third party library. TS files in published libraries are often a sign of a badly packaged library. Please open an issue in the library repository to alert its author and ask them to package the library using the Angular Package Format.
    at AngularCompilerPlugin.getCompiledFile (/code/user/code/user/test/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:933:23)
    at /code/user/code/user/test/node_modules/@ngtools/webpack/src/loader.js:41:31
    at processTicksAndRejections (internal/process/task_queues.js:97:5)

What step did I do that was wrong? Was it the folder structure of my library that caused the problem? I can't seem to find any resources on how to resolve this.


问:
Javascript Border and button line break question
I'm having a few issues with my javascript webpage. My first question is how to create a small border that wraps around a title? The bottom portion of my professor's sample webpage looks like this: https://i.imgur.com/4DVozv9.png

The bottom portion of my webpage so far looks like this: https://i.imgur.com/8STmOGd.png

I don't understand how to make that small border that circles around the "Shipping Method", "Shipping Address", and "Payment Details" titles.

Also for some reason the "
" tag on my "Complete Payment" button isn't placing my button on the next line for some reason. Here is my code so far, note though that it's incomplete so my functions and other features aren't ready yet, right now I'm just focusing purely on presentation. Thank you for your time.

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>YOUR NAME  Final Project Checkout</title>
    <link href="layout.css" type="text/css" rel="stylesheet">

<script type="text/javascript" src="guest-functions.js"></script>
<script type="text/javascript" src="cart-functions.js"></script>

<script>
window.onload=function(){
    setGuest();
    updateCartTotal();
}

</script>

</head>

<body>
<header><img src="90s-Gamers-Logo.png" width="798" height="82" alt="My Company"/></header>
<nav>
<form id="form1" name="form1" method="post">
<p>Choose a page to visit:<br>
  <select name="select" id="select" onchange="location = this.options[this.selectedIndex].value;">
    <option value="index.html">Home</option>
    <option value="shop.html">Shop</option>
    <option value="cart.html">Cart</option>
    <option value="checkout.html" selected="selected">Checkout</option>
  </select>
</p><br>

<p><b>Welcome Guest!</b></p>
<p>Enter your name:</p>
<input id="sign-in-text"><br>
<button onclick="setGuest()" id="sign-in-button">Sign-In</button><br><br>
<p>Your shopping cart is now</p>
<!--Need variable here-->
<p><b>empty!</b></p>
</form>

<p> </p>

<div id="divGuestArea"> </div>
<p> </p>

<div id="divCartSummary"> </div>

</nav>

<div id="main">
<h1>Checkout</h1>
<!--<p>This is where the transaction would take place so create a form here to take care of that final process as appropriate. Such form fields as contact info, shipping method, payment method, receipt, etc. Use HTML attributes wisely to help with validation and write JavaScript to validate any needed fields that are not sure to be validated by this HTML.</p>
<p>Connect your form to a "thankyou.html" page that you create so that after the form is submitted and found to be filled out properly, you thank them by name on "thankyou.html".</p>-->
<table border="1" cellspacing="0" cellpadding="6" summary="Table of Quantity, Description, Price, and Product Totals">
            <tbody>
               <tr>
                <td><b>Quantity</b></td>
                <td><b>Description</b></td>
                <td><b>Price</b></td>
                <td><b>Product Total</b></td>
              </tr>
              <tr style="text-align:right">
                <td>later</td>
                <td>later</td>
                <td>later</td>
                <td>later</td>
              </tr>
                <tr style="text-align:right">
                <td>later</td>
                <td>later</td>
                <td>later</td>
                <td>later</td>
              </tr>
                <tr style="text-align:right">
                <td colspan="3">Subtotal:</td>
                <td>later</td>
              </tr>
                <tr style="text-align:right">
                <td colspan="3">Tax:</td>
                <td>later</td>
              </tr>
                <tr style="text-align:right">
                <td colspan="3"><b>Grand total:</b></td>
                <td><b>later</b></td>
              </tr>
            </tbody>
        </table><br>
<p>Display total amount</p>
<p>Shipping Method</p>
<p> <input type="radio" name="ShipType" id="standard" value="2">
                <label for="standard">Standard Shipping ($2)</label>
                <input type="radio" name="ShipType" id="2-day" value="5">
                <label for="2-day">2-Day Shipping ($5)</label>
                <input type="radio" name="ShipType" id="overnight" value="10">
                <label for="overnight">Overnight Shipping ($10)</label>
                <br>

<p>Shipping Address</p>
    Full Name:
    <input type="text" id="FullName" name="FullName">
    Street Address:
    <input type="text" id="StreetAddress" name="StreetAddress"><br><br>
    City:
    <input type="text" id="City" name="City">
    State/Province/Region:
    <input type="text" id="State" name="State"><br><br>
    ZIP:
    <input type="text" id="Zip" name="Zip">
    Country:
    <input type="text" id="Country" name="Country"><br><br>
    Phone Number:
    <input type="text" id="PhoneNumber" name="PhoneNumber"><br>

    <p>Payment Details</p>
    <select id="selPayment" name="selPayment" onChange="getSelectValue();">
                    <option value="" selected="selected">- Choose one -</option>
                    <option value="Visa">Visa Credit</option>
                    <option value="MasterCard">MasterCard Credit</option>
                    <option value="American Express">American Express Credit</option>
                    <option value="Debit Card">Debit Card</option>
                    <option value="Pay Pal">Paypal</option>
                </select> <br><br>

    Card #:
    <input type="text" id="CardNumber" name="CardNumber"><br><br>

    Expiration Month:
    <select id="selMonth" name="selMonth" onChange="getSelectMonth();">
                    <option value="" selected="selected">- Choose one -</option>
                    <option value="January">January</option>
                    <option value="February">Febraury</option>
                    <option value="March">March</option>
                    <option value="April">April</option>
                    <option value="May">May</option>
                    <option value="June">June</option>
                    <option value="July">July</option>
                    <option value="August">August</option>
                    <option value="September">September</option>
                    <option value="October">October</option>
                    <option value="November">November</option>
                    <option value="December">December</option>
                </select> <br><br>
    Expiration Year:
    <select id="selYear" name="selYear" onChange="getSelectYear();">
                    <option value="" selected="selected">- Choose one -</option>
                    <option value="2020">2020</option>
                    <option value="2021">2021</option>
                    <option value="2022">2022</option>
                    <option value="2023">2023</option>
                    <option value="2024">2024</option>

        <br><p>
        <input type="button" value="Complete Payment"
               onclick="storeAndGo();">
    </p>
<footer>
Copyright 2020, 90's Gamers.
</footer>
</div>
</body>
</html>
</code>```

答:
I don't understand how to make that small border that circles around the "Shipping Method", "Shipping Address", and "Payment Details" titles.

CSS

```<code>border: 1px solid;
border-radius: 25px;
</code>```

Body:
I'm having a few issues with my javascript webpage. My first question is how to create a small border that wraps around a title? The bottom portion of my professor's sample webpage looks like this: https://i.imgur.com/4DVozv9.png

The bottom portion of my webpage so far looks like this: https://i.imgur.com/8STmOGd.png

I don't understand how to make that small border that circles around the "Shipping Method", "Shipping Address", and "Payment Details" titles.

Also for some reason the "
" tag on my "Complete Payment" button isn't placing my button on the next line for some reason. Here is my code so far, note though that it's incomplete so my functions and other features aren't ready yet, right now I'm just focusing purely on presentation. Thank you for your time.

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>YOUR NAME  Final Project Checkout</title>
    <link href="layout.css" type="text/css" rel="stylesheet">

<form id="form1" name="form1" method="post">

Choose a page to visit:

  <select name="select" id="select" onchange="location = this.options[this.selectedIndex].value;">
    <option value="index.html">Home</option>
    <option value="shop.html">Shop</option>
    <option value="cart.html">Cart</option>
    <option value="checkout.html" selected="selected">Checkout</option>
  </select>

Welcome Guest!

Enter your name:

<input id="sign-in-text">

<button onclick="setGuest()" id="sign-in-button">Sign-In</button>

Your shopping cart is now

empty!

</form>

Checkout

                Quantity
                Description
                Price
                Product Total

                later
                later
                later
                later

                later
                later
                later
                later

                Subtotal:
                later

                Tax:
                later

                Grand total:
                later

Display total amount

Shipping Method

 <input type="radio" name="ShipType" id="standard" value="2">
                Standard Shipping ($2)
                <input type="radio" name="ShipType" id="2-day" value="5">
                2-Day Shipping ($5)
                <input type="radio" name="ShipType" id="overnight" value="10">
                Overnight Shipping ($10)

Shipping Address

    Full Name:
    <input type="text" id="FullName" name="FullName">
    Street Address:
    <input type="text" id="StreetAddress" name="StreetAddress">

    City:
    <input type="text" id="City" name="City">
    State/Province/Region:
    <input type="text" id="State" name="State">

    ZIP:
    <input type="text" id="Zip" name="Zip">
    Country:
    <input type="text" id="Country" name="Country">

    Phone Number:
    <input type="text" id="PhoneNumber" name="PhoneNumber">

Payment Details

    <select id="selPayment" name="selPayment" onChange="getSelectValue();">
                    <option value="" selected="selected">- Choose one -</option>
                    <option value="Visa">Visa Credit</option>
                    <option value="MasterCard">MasterCard Credit</option>
                    <option value="American Express">American Express Credit</option>
                    <option value="Debit Card">Debit Card</option>
                    <option value="Pay Pal">Paypal</option>
                </select>

    Card #:
    <input type="text" id="CardNumber" name="CardNumber">

    Expiration Month:
    <select id="selMonth" name="selMonth" onChange="getSelectMonth();">
                    <option value="" selected="selected">- Choose one -</option>
                    <option value="January">January</option>
                    <option value="February">Febraury</option>
                    <option value="March">March</option>
                    <option value="April">April</option>
                    <option value="May">May</option>
                    <option value="June">June</option>
                    <option value="July">July</option>
                    <option value="August">August</option>
                    <option value="September">September</option>
                    <option value="October">October</option>
                    <option value="November">November</option>
                    <option value="December">December</option>
                </select>

    Expiration Year:
    <select id="selYear" name="selYear" onChange="getSelectYear();">
                    <option value="" selected="selected">- Choose one -</option>
                    <option value="2020">2020</option>
                    <option value="2021">2021</option>
                    <option value="2022">2022</option>
                    <option value="2023">2023</option>
                    <option value="2024">2024</option>

        <input type="button" value="Complete Payment"
               onclick="storeAndGo();">

Copyright 2020, 90's Gamers.

Body:
I don't understand how to make that small border that circles around the "Shipping Method", "Shipping Address", and "Payment Details" titles.

CSS

border: 1px solid;
border-radius: 25px;


问:
NHibernate Designer - many to many
Following on from a previous question, I am evaluating MindScape's NHibernate Designer.

When I add a many to many mapping, it says that it won't propagate this to the database..

Is there a way to map the many to many using this tool (a code generator). If I manually edit the mappings xml I lose it on changing the model.

The produced map:

```<code><bag name='Roles' table='`RoleUser`'>
  <key column='`UserId`' />
  <many-to-many column='`RoleId`' class='Role' />
</bag>
</code>```

I don't want to create an entity item_item and do a one to many on that link table as this should be done by the designer (adding an entity pollutes the business objects and is wrong).

Their help documents say that this can happen if you set the source column name, and destination column name... Not working!

答:
I am one of the developers of the NHibernate designer.

Earlier versions of the designer didn't support generating the database schema for many-to-many associations.  This limitation has been removed in the latest version.  You can get the latest version through the VS2010 Extension Manager Updates tab.

Title: NHibernate Designer - many to many

Body:
Following on from a previous question, I am evaluating MindScape's NHibernate Designer.

When I add a many to many mapping, it says that it won't propagate this to the database..

Is there a way to map the many to many using this tool (a code generator). If I manually edit the mappings xml I lose it on changing the model.

The produced map:

<bag name='Roles' table='`RoleUser`'>
  <key column='`UserId`' />
  <many-to-many column='`RoleId`' class='Role' />
</bag>

I don't want to create an entity item_item and do a one to many on that link table as this should be done by the designer (adding an entity pollutes the business objects and is wrong).

Their help documents say that this can happen if you set the source column name, and destination column name... Not working!


问:
SQL Server Float data type calculation vs decimal
In the following query

```<code>declare @a float(23)
declare @b float(23)
declare @c float(53)
set @a = 123456789012.1234
set @b = 1234567.12345678
set @c = @a * @b
select @c

select LTRIM(STR((@c),32,12))

declare @x  decimal(16,4)
declare @y decimal(16,8)
declare @z decimal (32,12)

set @x = 123456789012.1234
set @y = 1234567.12345678
set @z = @x * @y
select @z
</code>```

I get answers as

```<code>1.52415693411713E+17
152415693411713020.000000000000
152415692881907790.143935926652
</code>```

From the above answers the third answer is the correct one. Is this the reason why float data type is called Approximate Numeric Data Type

Or am I doing something fundamentally wrong.

BTW this is due to a problem I have with legacy system wherein I have to use float as storage data type, at the same time in there should not be loss of precision while calculation.

Please suggest alternatives, or an explanation.

答:
Problem not with float Data type.
Problem is with using float(23).
This data type has a capacity of holding 8 significant digits, not 15 as float(53).
And that's exactly how many correct digits you've got in the output.

Calculation of 2 float(23) numbers is done with float(23) precision, and only afterwards converted to float(53), which is absolutely useless and misleading.

Fix the initial declarations of @a and @b and the problem will disappear.

Body:
In the following query

declare @a float(23)
declare @b float(23)
declare @c float(53)
set @a = 123456789012.1234
set @b = 1234567.12345678
set @c = @a * @b
select @c

select LTRIM(STR((@c),32,12))

declare @x  decimal(16,4)
declare @y decimal(16,8)
declare @z decimal (32,12)

set @x = 123456789012.1234
set @y = 1234567.12345678
set @z = @x * @y
select @z

I get answers as

1.52415693411713E+17
152415693411713020.000000000000
152415692881907790.143935926652

From the above answers the third answer is the correct one. Is this the reason why float data type is called Approximate Numeric Data Type

Or am I doing something fundamentally wrong.

BTW this is due to a problem I have with legacy system wherein I have to use float as storage data type, at the same time in there should not be loss of precision while calculation.

Please suggest alternatives, or an explanation.


问:
Sankey Diagram with networkD3 package miximises CPU usage and does not show the diagram
Most times I try plot a Sankey diagram in R my CPU is maximised and the diagram does not show. Does anyone know what could be causing this? My computer is decent with i7-7600U CPU @ 2.80GHz 2.90GHZ. To get the CPU back down again I have been having to restart R.

For example I was using this example code

```<code>library("networkD3")

myDf <- list(
    nodes=data.frame(name=c( "A", "B", "C", "D", "E",
                             "V", "W", "X", "Y", "Z")),
    links=data.frame(source=as.integer(c(0, 1, 2, 3, 3, 4, 4)),
                     target=as.integer(c(7, 6, 7, 8, 7, 5, 9)),
                     value =           c(1, 4, 1, 5, 1, 5, 3)
    )
)

sankeyNetwork(Links = myDf$links, Nodes = myDf$nodes, Source = "source",
              Target = "target", Value = "value", NodeID = "name",
              units = "TWh", fontSize = 25, nodeWidth = 30,
              fontFamily = "sans-serif", iterations = 0)
</code>```

答:
This could be an issue with your package or R Studio configuration.

Try saving the sankeyNetwork as an HTML file using the saveNetwork() command from the same package (networkD3) and opening that.

e.g.

```<code>library("networkD3")

myDf <- list(
    nodes=data.frame(name=c( "A", "B", "C", "D", "E",
                             "V", "W", "X", "Y", "Z")),
    links=data.frame(source=as.integer(c(0, 1, 2, 3, 3, 4, 4)),
                     target=as.integer(c(7, 6, 7, 8, 7, 5, 9)),
                     value =           c(1, 4, 1, 5, 1, 5, 3)
    )
)

sk <- sankeyNetwork(Links = myDf$links, Nodes = myDf$nodes, Source = "source",
              Target = "target", Value = "value", NodeID = "name",
              units = "TWh", fontSize = 25, nodeWidth = 30,
              fontFamily = "sans-serif", iterations = 0)

saveNetwork(sk,file = "sk.html")
</code>```

Body:
Most times I try plot a Sankey diagram in R my CPU is maximised and the diagram does not show. Does anyone know what could be causing this? My computer is decent with i7-7600U CPU @ 2.80GHz 2.90GHZ. To get the CPU back down again I have been having to restart R.

For example I was using this example code

library("networkD3")

myDf <- list(
    nodes=data.frame(name=c( "A", "B", "C", "D", "E",
                             "V", "W", "X", "Y", "Z")),
    links=data.frame(source=as.integer(c(0, 1, 2, 3, 3, 4, 4)),
                     target=as.integer(c(7, 6, 7, 8, 7, 5, 9)),
                     value =           c(1, 4, 1, 5, 1, 5, 3)
    )
)

sankeyNetwork(Links = myDf$links, Nodes = myDf$nodes, Source = "source",
              Target = "target", Value = "value", NodeID = "name",
              units = "TWh", fontSize = 25, nodeWidth = 30,
              fontFamily = "sans-serif", iterations = 0)

Body:
This could be an issue with your package or R Studio configuration.

Try saving the sankeyNetwork as an HTML file using the saveNetwork() command from the same package (networkD3) and opening that.

e.g.

library("networkD3")

myDf <- list(
    nodes=data.frame(name=c( "A", "B", "C", "D", "E",
                             "V", "W", "X", "Y", "Z")),
    links=data.frame(source=as.integer(c(0, 1, 2, 3, 3, 4, 4)),
                     target=as.integer(c(7, 6, 7, 8, 7, 5, 9)),
                     value =           c(1, 4, 1, 5, 1, 5, 3)
    )
)

sk <- sankeyNetwork(Links = myDf$links, Nodes = myDf$nodes, Source = "source",
              Target = "target", Value = "value", NodeID = "name",
              units = "TWh", fontSize = 25, nodeWidth = 30,
              fontFamily = "sans-serif", iterations = 0)

saveNetwork(sk,file = "sk.html")