问:
Overwrite repository definition in gradle subproject
Imagine you have a gradle build with a gradle subproject.
This subproject has some applied script plugin which define their own repositories like this:

```<code>buildscript {
    repositories {
        //jcenter()
        maven {
            url 'https://example.com/plugins.gradle.org/m2/'
        }
    }
    dependencies {
        classpath 'org.asciidoctor:asciidoctor-gradle-plugin:1.5.3'
    }
}
</code>```

Now imagine you only own the main project, not the sub project (it is a git submodule).

How can you override the repository definitions of the subproject from the main project?

PS: if you need a better description of the subproject, here it is: https://github.com/docToolchain/docToolchain

Update: I've created an example to paly around with: https://github.com/rdmueller/SO56283254/blob/master/README.adoc

see the readme for more details

答:
As said in my previous comment, you are in the same situation as described in issue/request
 https://discuss.gradle.org/t/configure-buildscript-repositories-for-all-project-globally-in-init-gradle/6572/2,  which has related opened issue https://github.com/gradle/gradle/issues/1038 . Unfortunately this issue has not been solved yet.

I had a deeper look and it seems to me impossible to make this work with current Gradle version:  there is no way to "alter" the script plugin's buildscript block by somehow injecting other repositories, so Gradle won't be able to compile this script plugin before applying it to the subproject.

Body:
Imagine you have a gradle build with a gradle subproject.
This subproject has some applied script plugin which define their own repositories like this:

buildscript {
    repositories {
        //jcenter()
        maven {
            url 'https://example.com/plugins.gradle.org/m2/'
        }
    }
    dependencies {
        classpath 'org.asciidoctor:asciidoctor-gradle-plugin:1.5.3'
    }
}

Now imagine you only own the main project, not the sub project (it is a git submodule).

How can you override the repository definitions of the subproject from the main project?

PS: if you need a better description of the subproject, here it is: https://github.com/docToolchain/docToolchain

Update: I've created an example to paly around with: https://github.com/rdmueller/SO56283254/blob/master/README.adoc

see the readme for more details


来源: stackexchange

问:
multithread handling in java
I have stuck in a serious problem. I am sending a request to server which contains some URL as its data.If I explain it , it is like I have a file which contains some URL in a sequential order I have to read those sequential data by using thread. Now the problem is there are one hundred thousand URL, I have to send each URL in the server in a particular time(say  suppose 30 seconds).So I have to create threads which will serve the task in the desired time. But I have to read the file in such a way if first thread serve first 100 URL then 2nd thread will serve the next 100 URL and in the same way the other threads also.And I am doing it in a socket programming,so there is only one port at a time that I can use. So how to solve this problem. Give me a nice and simple idea, and if possible give me an example also.

Thanks in Advance

答:
One thing that you could look into is the fork/join framework.  The way that the java tutorials explains this is: "It is designed for work that can be broken into smaller pieces recursively. The goal is to use all the available processing power to make your application wicked fast". Then all you really need to do is figure out how to break up your tasks.

http://download.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html

you can find the jar for this at: http://g.oswego.edu/dl/concurrency-interest/

ContentLicense: CC BY-SA 3.0

Title: multithread handling in java


问:
Understanding Rails singular and plural paths
I'm very new to using Rails and at the moment am building an Instagram clone as a project to help me understand Rails a bit better. I am following this very helpful tutorial on how to implement the likes/unlikes feature:

https://medium.com/full-taxx/how-to-add-likes-to-posts-in-rails-e81430101bc2

However, I don't fully understand the Rails paths - please could someone explain the difference between:

post_like_path and post_likes_path as mentioned in the tutorial. I cannot see why one is like and one is likes? :(

Really trying to get my head around this so would be so grateful for any insight!

Thanks :)

答:
In Rails as per the REST -

If trying to refer to the single resource then use post_like_path.

If trying to refer to a collection of resources then use post_likes_path

When you want to show or delete a particular resource then you will have to provide an :id for the resource so that the target resource can be found.

[/posts/1/likes/1] - A single record of "like" is being referred here.

While in case of all records plural path is formed to refer to all like records -

[/posts/1/likes] - All records of "like" are being referred here.

ContentLicense: CC BY-SA 4.0


问:
How to fix ''Expected ';' after top level declarator" and "Unknown type name 'class'?
I use cocoa to import TUIKit which is a imSDK demo written in objective-c by Tencent into my blank swift app. I get the error:  Expected ';' after top level declarator and Unknown type name 'class'; did you mean 'Class'?

The file whith the error is wav.h and there is wav.mm file. Here is the code:

File wav.h

```<code>#ifndef WAV_H
#define WAV_H
#include <stdio.h>
class WavWriter {
public:
    WavWriter(const char *filename, int sampleRate, int bitsPerSample, int channels);
    ~WavWriter();
    void writeData(const unsigned char* data, int length);
private:
    void writeString(const char *str);
    void writeInt32(int value);
    void writeInt16(int value);
    void writeHeader(int length);
    FILE *wav;
    int dataLength;
    int sampleRate;
    int bitsPerSample;
    int channels;
};
#endif
</code>```

The error is on the line "class WavWriter".

The wav.mm file

```<code>#import <UIKit/UIKit.h>
#include "wav.h"
void WavWriter::writeString(const char *str) {

    fputc(str[0], wav);
    fputc(str[1], wav);
    fputc(str[2], wav);
    fputc(str[3], wav);
}
</code>```

....

I searched for two days and couldn't find the answer. Any help? Thanks.

答:
Your wav.h filer is being included in a compilation unit that is not a .mm file (which means "compile as Objective-C++" i.e. either a .m or a .c file.

You need to enclose the class definition with

```<code>#if defined __cplusplus

// the C++ defs

#endif
</code>```

The lines between the #ifdef ... #endif will be ignored unless the file being compiled is C++ or Objective-C++.

If you have straight Objective-C files that need to know the type exists, you can use a typedef to void* or to make it an incomplete struct type

```<code>#if defined __cplusplus

// the C++ defs

class WavWriter {
// ...
};

#else

typedef struct WavWriter WavWriter; // Sets up incomplete type for C code

#endif

@interface Foo

@private
    WavWriter* writer; // In C++ a pointer to your class, in C a pointer to an opaque type.
</code>```

Body:
I use cocoa to import TUIKit which is a imSDK demo written in objective-c by Tencent into my blank swift app. I get the error:  Expected ';' after top level declarator and Unknown type name 'class'; did you mean 'Class'?

The file whith the error is wav.h and there is wav.mm file. Here is the code:

File wav.h

#ifndef WAV_H
#define WAV_H
#include <stdio.h>
class WavWriter {
public:
    WavWriter(const char *filename, int sampleRate, int bitsPerSample, int channels);
    ~WavWriter();
    void writeData(const unsigned char* data, int length);
private:
    void writeString(const char *str);
    void writeInt32(int value);
    void writeInt16(int value);
    void writeHeader(int length);
    FILE *wav;
    int dataLength;
    int sampleRate;
    int bitsPerSample;
    int channels;
};
#endif

The error is on the line "class WavWriter".

The wav.mm file

#import <UIKit/UIKit.h>
#include "wav.h"
void WavWriter::writeString(const char *str) {

    fputc(str[0], wav);
    fputc(str[1], wav);
    fputc(str[2], wav);
    fputc(str[3], wav);
}

....

I searched for two days and couldn't find the answer. Any help? Thanks.

Body:
Your wav.h filer is being included in a compilation unit that is not a .mm file (which means "compile as Objective-C++" i.e. either a .m or a .c file.

You need to enclose the class definition with

#if defined __cplusplus

// the C++ defs

#endif

The lines between the #ifdef ... #endif will be ignored unless the file being compiled is C++ or Objective-C++.

If you have straight Objective-C files that need to know the type exists, you can use a typedef to void* or to make it an incomplete struct type

#if defined __cplusplus

// the C++ defs

class WavWriter {
// ...
};

#else

typedef struct WavWriter WavWriter; // Sets up incomplete type for C code

#endif

@interface Foo

@private
    WavWriter* writer; // In C++ a pointer to your class, in C a pointer to an opaque type.


问:
Create a partial view for the imports of css and js asp.net core 2.2
It is a question regarding design. In my ASP.Net Core MVC app I have 2 Layouts. My Default Layout and my Admin Layout which are quite self explanatory by there name. I do import the same js and css for both of my layouts e.g. Bootstrap and jQuery and some more. I wonder if I should create a partial view which contains these.
There might be different solutions which I do not know about.

Any help is appreciated.

答:
I can't tell if it would be good or not to create a partial for both layouts, but I would recommend a hidden, tiny tag helper for script tag (and link as well) that I think you might find useful. It is asp-src-include.

```<code><script asp-src-include="/assets/js/*.js"></script>
</code>```

is rendered to the html like;

```<code><script src="/assets/js/jquery.js"></script>
<script src="/assets/js/bootstrap.js"></script>
<script src="/assets/js/custom.js"></script>
</code>```

and same functionality applies to link tag as well.

I think this might tidy up your layouts a bit. Yo can find out detailed posts about these tag helpers here and here

Body:
I can't tell if it would be good or not to create a partial for both layouts, but I would recommend a hidden, tiny tag helper for script tag (and link as well) that I think you might find useful. It is asp-src-include.

<script asp-src-include="/assets/js/*.js"></script>

is rendered to the html like;

<script src="/assets/js/jquery.js"></script>
<script src="/assets/js/bootstrap.js"></script>
<script src="/assets/js/custom.js"></script>

and same functionality applies to link tag as well.

I think this might tidy up your layouts a bit. Yo can find out detailed posts about these tag helpers here and here


问:
Android: show soft keyboard automatically when focus is on an EditText
I'm showing an input box using AlertDialog. The EditText inside the dialog itself is automatically focused when I call AlertDialog.show(), but the soft keyboard is not automatically shown.

How do I make the soft keyboard automatically show when the dialog is shown? (and there is no physical/hardware keyboard). Similar to how when I press the Search button to invoke the global search, the soft keyboard is automatically shown.

答:
Tried many but this is what worked for me (kotlin):</p>

```<code>        val dialog = builder.create()
        dialog.setOnShowListener {
            nameEditText.requestFocus()
            val s = ContextCompat.getSystemService(requireContext(), InputMethodManager::class.java)
            s?.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
        }

        dialog.setOnDismissListener {
            val s = ContextCompat.getSystemService(requireContext(), InputMethodManager::class.java)
            s?.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0)
        }

        dialog.show()
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Tried many but this is what worked for me (kotlin):

        val dialog = builder.create()
        dialog.setOnShowListener {
            nameEditText.requestFocus()
            val s = ContextCompat.getSystemService(requireContext(), InputMethodManager::class.java)
            s?.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
        }

        dialog.setOnDismissListener {
            val s = ContextCompat.getSystemService(requireContext(), InputMethodManager::class.java)
            s?.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0)
        }

        dialog.show()


问:
Keystore file doesn't exist. Unable to get SHA1 key
Unable to get SHA1 key, it is showing error about path, Keystore file doesn't exist.

Tried multiple numbers of solutions,
I am using the following command

```<code>keytool -list -v -keystore c:\users\your_user_name\.android\debug.keystore -alias androiddebugkey -storepass android -keypass android
</code>```

答:
The keystore file does not exists, you have to create it yourself.

Here is the procedure : Generate android release and debug keystores

Body:
Unable to get SHA1 key, it is showing error about path, Keystore file doesn't exist.

Tried multiple numbers of solutions,
I am using the following command

keytool -list -v -keystore c:\users\your_user_name\.android\debug.keystore -alias androiddebugkey -storepass android -keypass android


问:
Transport Close on console log
I have 3 roads

```<code>//Roads
const signin = io.of('/signin');
const cancelOfferOrDemand = io.of("/cancel");
const disconnect = io.of("/disconnect");
</code>```

The first two of them are working perfectly and logged the information sent.
The third prints me "transport close" instead of the information content that I send. In order to test and send those data I just have an html file where I just switch the server adress where to connect and the signal sent. So the data sent and the same in the three cases.

```<code>//------------------------------ SIGNIN ---------------------------------------//
signin.on('connection', function (socket, information) {

    const collection = client.db(dbName).collection('UserConnected');

    socket.on('new', async function(information) {
        console.log(information);
    });

});

//----------------------- CANCEL OFFER DEMAND --------------------------------//
cancelOfferOrDemand.on('connection', function (socket, information) {
    socket.on('cancel_demand', async function(information) {
        console.log("information");

    });
});

//------------------------------ DISCONNECT ----------------------------------//
disconnect.on('connection', function (socket, information) {
    socket.on('disconnect', async function (information) {
        console.log(information);
        });
});
</code>```

Thanks for your help.

答:
The 2nd parameter information from socket.on('disconnect', function(information) { ... }) can only give you 3 response : io server disconnect, io client disconnect, ping timeout.

The information that you're printing is normally the second parameter. If you want to show the first one, make sure to change the name and check the reference inside of your console.log(). You should also do the same for the connect and cancel_demand event.

Documentation event connect

Documentation event disconnect

Title: Transport Close on console log

Body:
I have 3 roads

//Roads
const signin = io.of('/signin');
const cancelOfferOrDemand = io.of("/cancel");
const disconnect = io.of("/disconnect");

The first two of them are working perfectly and logged the information sent.
The third prints me "transport close" instead of the information content that I send. In order to test and send those data I just have an html file where I just switch the server adress where to connect and the signal sent. So the data sent and the same in the three cases.

//------------------------------ SIGNIN ---------------------------------------//
signin.on('connection', function (socket, information) {

    const collection = client.db(dbName).collection('UserConnected');

    socket.on('new', async function(information) {
        console.log(information);
    });

});

//----------------------- CANCEL OFFER DEMAND --------------------------------//
cancelOfferOrDemand.on('connection', function (socket, information) {
    socket.on('cancel_demand', async function(information) {
        console.log("information");

    });
});

//------------------------------ DISCONNECT ----------------------------------//
disconnect.on('connection', function (socket, information) {
    socket.on('disconnect', async function (information) {
        console.log(information);
        });
});

Thanks for your help.


问:
Working with more than one xml file in android
I am new to android development.

If I have more than one xml file, other than the main.xml, then how can I call the other files?

答: You should call it by name of the file. For examole for main.xml you call it as R.layout.main, so for my_menu_activity.xml it would be R.layout.my_menu_activity</p>


问:
How to change position of a carousel depending on screen size?
how to Change the position of a carousel depending on screen size?

```<code>#carousel-1 {
  width: 1024;
  height: 439;
  margin: 10px;
  padding: 10px;
}
</code>```

I have block containing 1 row 2 column.in the left column, I have heading and text and in the right column, I have the carousel.
expected results:
for the mobile screen, I want the carousel to come below heading and text.
actual results:
carousel still remain on the right side of the screen.

答: You can use MeidaQuery for this purpose. Your desirable screen work properly as u want. </p>

Body:
how to Change the position of a carousel depending on screen size?

#carousel-1 {
  width: 1024;
  height: 439;
  margin: 10px;
  padding: 10px;
}

I have block containing 1 row 2 column.in the left column, I have heading and text and in the right column, I have the carousel.
expected results:
for the mobile screen, I want the carousel to come below heading and text.
actual results:
carousel still remain on the right side of the screen.


问:
Akka streams: attach new publishers/subscribers to Flow
I'm building an Akka application and want to expose the FSM state transitions of some actors to external consumers. (The end goal is to be able to push the state transition messages to a websocket so that they can be viewed in realtime.)

Based on the documentation, Combining dynamic stages to build a simple Publish-Subscribe service, it looks like I need to expose the Flow that represents the pub-sub channel so that it can be used by consumers and producers.

The part I'm having trouble with is attaching new Source(s) to the Flow such that each new actor that is spawned will publish its state transitions to the Source. The other issue is adding new Sinks to the Flow (in the end, this will be websockets but for testing purposes, it could be any new Sink).

First I connect a MergeHub and a BroadcastHub to form a "channel" and then create the Flow from the materialized sink and source:

```<code>    val orderFlow: Flow[String, String, NotUsed] = {
        val (sink, source) = MergeHub.source[String](16)
            .toMat(BroadcastHub.sink(256))(Keep.both).run()
        Flow.fromSinkAndSource(sink, source)
    }
</code>```

The question is then how can I dynamically add new producers and consumers to this Flow? Any ideas?

答:
I use the following solution in one of my projects to handle the requests from the websocket by multiple request processors which could produce a stream of responses or provide an endless subscription.

```<code>// requests coming from websocket, it could be any source, it's doesn't matter
val requests: Source[Request, NotUsed] = ...

// the request processing here can provide endles stream of responses
val requestProcessing: Flow[Request, Response, NotUsed] = ...

val (outSink, outSource) =
  MergeHub
    .source[Result](perProducerBufferSize = 4)
    .toMat(BroadcastHub.sink(bufferSize = 32))(Keep.both)
    .run()

Source.tick(Duration.Zero, KeepAliveInterval, ConnectionKeepAlive)
  .to(outSink)
  .run()

requests.fold {
  case State(state, AuthRequest(r)) if checkAuth(r) =>
    Source.single(AuthenticationAck).to(outSink)
    state.copy(isAuthenticated = true)
 case State(state, AuthRequest(r)) =>
    Source.single(AuthenticationFailedError).to(outSink)
    state

 case State(state, request) if s.isAuthenticated =>
    // here the most of busines
    Source.single(request).via(requestProcessing).to(outSink)
    state

 case State(state, _) =>
    Source.single(NonAuthorizedError).to(outSink)
    state
}.toMat(Sink.ignore)(Keep.right)

outSource.runForeach { response =>
  // here we get the stream of responses mixed from all requests
}

outSource.runForeach { response =>
  // of course, we could have as many subscribers as we need
}
</code>```

I hope it helps :)

Body:
I'm building an Akka application and want to expose the FSM state transitions of some actors to external consumers. (The end goal is to be able to push the state transition messages to a websocket so that they can be viewed in realtime.)

Based on the documentation, Combining dynamic stages to build a simple Publish-Subscribe service, it looks like I need to expose the Flow that represents the pub-sub channel so that it can be used by consumers and producers.

The part I'm having trouble with is attaching new Source(s) to the Flow such that each new actor that is spawned will publish its state transitions to the Source. The other issue is adding new Sinks to the Flow (in the end, this will be websockets but for testing purposes, it could be any new Sink).

First I connect a MergeHub and a BroadcastHub to form a "channel" and then create the Flow from the materialized sink and source:

    val orderFlow: Flow[String, String, NotUsed] = {
        val (sink, source) = MergeHub.source[String](16)
            .toMat(BroadcastHub.sink(256))(Keep.both).run()
        Flow.fromSinkAndSource(sink, source)
    }

The question is then how can I dynamically add new producers and consumers to this Flow? Any ideas?

Body:
I use the following solution in one of my projects to handle the requests from the websocket by multiple request processors which could produce a stream of responses or provide an endless subscription.

// requests coming from websocket, it could be any source, it's doesn't matter
val requests: Source[Request, NotUsed] = ...

// the request processing here can provide endles stream of responses
val requestProcessing: Flow[Request, Response, NotUsed] = ...

val (outSink, outSource) =
  MergeHub
    .source[Result](perProducerBufferSize = 4)
    .toMat(BroadcastHub.sink(bufferSize = 32))(Keep.both)
    .run()

Source.tick(Duration.Zero, KeepAliveInterval, ConnectionKeepAlive)
  .to(outSink)
  .run()

requests.fold {
  case State(state, AuthRequest(r)) if checkAuth(r) =>
    Source.single(AuthenticationAck).to(outSink)
    state.copy(isAuthenticated = true)
 case State(state, AuthRequest(r)) =>
    Source.single(AuthenticationFailedError).to(outSink)
    state

 case State(state, request) if s.isAuthenticated =>
    // here the most of busines
    Source.single(request).via(requestProcessing).to(outSink)
    state

 case State(state, _) =>
    Source.single(NonAuthorizedError).to(outSink)
    state
}.toMat(Sink.ignore)(Keep.right)

outSource.runForeach { response =>
  // here we get the stream of responses mixed from all requests
}

outSource.runForeach { response =>
  // of course, we could have as many subscribers as we need
}

I hope it helps :)


问:
How can I extract all the HTML tags from a page. Not the data between the tags
Sorry if it’s a newbie question. I’ve been googling for an hour and I also checked several questions on this site but I can’t seem to figure it out.

I’m trying to extract all the HTML tags (elements) from a few different pages. I don’t need the data between the HTML tags. I only need the tags that are being used, comments, etc.

So the output I’m looking for is whatever is between <> I guess. As an example, if the code is

```<code><head> title </head>
<body id=“body text”> blah blah blah </body>
</code>```

I’d like the output to be:

```<code><head> </head>
<body id=“body text”> </body>
</code>```

Thanks a lot in advance and sorry if it’s a silly question.

答:
if you just want whatever between <>, try:</p>

```<code>sed -n  's/.*\(<.*>\).*/\1/p' xx.html
</code>```

Body:
Sorry if it’s a newbie question. I’ve been googling for an hour and I also checked several questions on this site but I can’t seem to figure it out.

I’m trying to extract all the HTML tags (elements) from a few different pages. I don’t need the data between the HTML tags. I only need the tags that are being used, comments, etc.

So the output I’m looking for is whatever is between <> I guess. As an example, if the code is

 title
 blah blah blah

I’d like the output to be:

Thanks a lot in advance and sorry if it’s a silly question.

Body:
if you just want whatever between <>, try:

sed -n  's/.*\(<.*>\).*/\1/p' xx.html


问:
c# Task.WhenAll to block while awaiting completion
I have a simple Winforms application. I would like to background TCP connections/print requests and check the output of all tasks at a set point in my code.

I would expect ReportOnTasks to block until WaitAll is complete. Please could someone explain why this is not the case? I'm also worried I haven't structured this correctly.

Edit, to clarify my intentions:
I would like to send the print jobs as soon as I receive the data. Then continue with some other DB operations. Once all the print operations are complete, I would like to update the UI to state the result.

I've attempted to simplify the code as much as I can. Maybe too much. HomeController just inits some stuff. There are buttons on the form and file watchers that trigger the main functionality.

```<code>public class HomeController
{

    public HomeController(){

        MessageBox.Show("1");

        oPrintController.PrintAsync("192.168.2.213", Encoding.ASCII.GetBytes("string to print"));

        MessageBox.Show("2");

        // Block here untill tasks are complete
        ReportOnTasks();

        MessageBox.Show("Report on tasks complete");
    }

    public async void ReportOnTasks()
    {
        await Task.WhenAll(oPrintController.Tasks);

        foreach(Task<PrintController.PrintResult> PR in oPrintController.Tasks)
        {
            // do something with the result of task
        }
    }
}
</code>```

and the PrintController

```<code>public class PrintController
{

    public List<Task<PrintResult>> Tasks = new List<Task<PrintResult>>();

    public async void PrintAsync(string sIP, List<byte[]> lsToPrint, int iPort = 9100)
    {
        var s = await Task.Run(() => PrintAsync1(sIP, lsToPrint));
    }

    public async System.Threading.Tasks.Task<PrintResult> PrintAsync1(string sIP, List<byte[]> lsToPrint, int iPort = 9100)
    {

        using (TcpClient tc = new TcpClient())
        {
            await tc.ConnectAsync(sIP, iPort);
            using (var ns = tc.GetStream())
            {
                foreach (byte[] btLabel in lsToPrint)
                {
                    await ns.WriteAsync(btLabel, 0, btLabel.Length);
                }
            }
        }

        Thread.Sleep(10000);

        return new PrintResult();
    }
}

public class PrintResult
{
    bool bSuccess = false;
}
</code>```

答:
It's generally not recommended to perform heavy operations in class constructors, but I suppose you won't change that part, so in order to wait for ReportOnTasks to finish, you need to make it synchronous.

Take into account, that constructor itself doesn't support async/await, it's not possible to mark it async.

Having said that, you won't have real performance enhancement marking void ReportOnTasks as async. In addition, it is not recommended to mark void methods as async due to issues with exceptions handling, which is usually not possible.

So, you can either postpone ReportOnTasks like Alex showed you, or you can synchronously wait until all tasks are finished (which is possible inside ctor).

```<code>    public void ReportOnTasks()
    {
        Task.WhenAll(oPrintController.Tasks).GetAwaiter().GetResult(); //synchronously wait

        foreach(Task<PrintController.PrintResult> PR in oPrintController.Tasks)
        {
            // do something with the result of task
        }
    }
</code>```

However, I wouldn't suggest this approach, because instance creation will take a while and most importantly block UI thread - and that's usually signal something is really fishy

Body:
I have a simple Winforms application. I would like to background TCP connections/print requests and check the output of all tasks at a set point in my code.

I would expect ReportOnTasks to block until WaitAll is complete. Please could someone explain why this is not the case? I'm also worried I haven't structured this correctly.

Edit, to clarify my intentions:
I would like to send the print jobs as soon as I receive the data. Then continue with some other DB operations. Once all the print operations are complete, I would like to update the UI to state the result.

I've attempted to simplify the code as much as I can. Maybe too much. HomeController just inits some stuff. There are buttons on the form and file watchers that trigger the main functionality.

public class HomeController
{

    public HomeController(){

        MessageBox.Show("1");

        oPrintController.PrintAsync("192.168.2.213", Encoding.ASCII.GetBytes("string to print"));

        MessageBox.Show("2");

        // Block here untill tasks are complete
        ReportOnTasks();

        MessageBox.Show("Report on tasks complete");
    }

    public async void ReportOnTasks()
    {
        await Task.WhenAll(oPrintController.Tasks);

        foreach(Task<PrintController.PrintResult> PR in oPrintController.Tasks)
        {
            // do something with the result of task
        }
    }
}

and the PrintController

public class PrintController
{

    public List<Task<PrintResult>> Tasks = new List<Task<PrintResult>>();

    public async void PrintAsync(string sIP, List<byte[]> lsToPrint, int iPort = 9100)
    {
        var s = await Task.Run(() => PrintAsync1(sIP, lsToPrint));
    }

    public async System.Threading.Tasks.Task<PrintResult> PrintAsync1(string sIP, List<byte[]> lsToPrint, int iPort = 9100)
    {

        using (TcpClient tc = new TcpClient())
        {
            await tc.ConnectAsync(sIP, iPort);
            using (var ns = tc.GetStream())
            {
                foreach (byte[] btLabel in lsToPrint)
                {
                    await ns.WriteAsync(btLabel, 0, btLabel.Length);
                }
            }
        }

        Thread.Sleep(10000);

        return new PrintResult();
    }
}

public class PrintResult
{
    bool bSuccess = false;
}

Body:
It's generally not recommended to perform heavy operations in class constructors, but I suppose you won't change that part, so in order to wait for ReportOnTasks to finish, you need to make it synchronous.

Take into account, that constructor itself doesn't support async/await, it's not possible to mark it async.

Having said that, you won't have real performance enhancement marking void ReportOnTasks as async. In addition, it is not recommended to mark void methods as async due to issues with exceptions handling, which is usually not possible.

So, you can either postpone ReportOnTasks like Alex showed you, or you can synchronously wait until all tasks are finished (which is possible inside ctor).

    public void ReportOnTasks()
    {
        Task.WhenAll(oPrintController.Tasks).GetAwaiter().GetResult(); //synchronously wait

        foreach(Task<PrintController.PrintResult> PR in oPrintController.Tasks)
        {
            // do something with the result of task
        }
    }

However, I wouldn't suggest this approach, because instance creation will take a while and most importantly block UI thread - and that's usually signal something is really fishy


问:
while loop with exception handling
This is my first time using exception handling so be gentle. I have a simple blob class that accepts an ID, the id must be between 30 and 50 or else an exception is thrown.

```<code>public class Blob {
int id;

public Blob() {

}

public Blob(int id) throws Exception {
    this.id = id;
    if (id < 30 || id > 50)
        throw new Exception ("id = " +id+ ", must be between 30 and 50 inclusive");
}
}
</code>```

It should prompt the user to enter an id, and throw the exception if it's not between 30 and 50, and should continue until the user enters a valid input and then simply displays the id number.

```<code>public class BlobCreator {

public static void main(String[] args) {
    int id;
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter ID number: ");
    id = scan.nextInt();

    do {
        try {
            Blob b = new Blob(id);
        }

        catch (Exception e) {
            System.out.println(e);
        }
        System.out.println("Enter a different ID: ");
        id = scan.nextInt();
    }
    while(true);
    }
System.out.println("Blob ID: " +id);
}
</code>```

I think that I am using the throw and catch correctly, but my loop isn't working correctly so I think that should be a simple fix but I can't get it just right. Also is using a while loop like I have the best way for this situation or is there a better way to loop through throw and catch?

Thanks for any and all help

答:
Sorry, its kind of late to the party. Hope users who endup here may find this useful.
 The use of break keyword is discouraged
Here is a very simple implementation to break away after implementing a retry mechanism
This iterates over the loop for the specified number of times and also if the exception still persists, then the exception is thrown. This can be leveraged for an actual real world scenario where the resttemplate might actually result in IO/Network errors and can be retried in those cases

```<code>public class TestClass {

    public static void main(String[] args) throws Exception {

        try {
            int c = anotherM();
            System.out.println("Now the value is" + c);
        } catch (Exception e) {
            System.out.println("Inside" + e);
        }
    }

    public static int anotherM() throws Exception {
        int i = 4;
        Exception ex = null;
        while (i > 0) {
            try {
                System.out.println("print i" + i);

                throw new IOException();
                // return i;
            } catch (Exception e) {
                System.out.println(e);

                i--;
                if (i == 1) {
                    ex = new Exception("ttt");

                }

            }
        }
        if (ex != null) {
            throw new Exception("all new");
        } else {
            return i;
        }

    }

}
</code>```

Title: while loop with exception handling

Body:
This is my first time using exception handling so be gentle. I have a simple blob class that accepts an ID, the id must be between 30 and 50 or else an exception is thrown.

public class Blob {
int id;

public Blob() {

}

public Blob(int id) throws Exception {
    this.id = id;
    if (id < 30 || id > 50)
        throw new Exception ("id = " +id+ ", must be between 30 and 50 inclusive");
}
}

It should prompt the user to enter an id, and throw the exception if it's not between 30 and 50, and should continue until the user enters a valid input and then simply displays the id number.

public class BlobCreator {

public static void main(String[] args) {
    int id;
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter ID number: ");
    id = scan.nextInt();

    do {
        try {
            Blob b = new Blob(id);
        }

        catch (Exception e) {
            System.out.println(e);
        }
        System.out.println("Enter a different ID: ");
        id = scan.nextInt();
    }
    while(true);
    }
System.out.println("Blob ID: " +id);
}

I think that I am using the throw and catch correctly, but my loop isn't working correctly so I think that should be a simple fix but I can't get it just right. Also is using a while loop like I have the best way for this situation or is there a better way to loop through throw and catch?

Thanks for any and all help

Body:
Sorry, its kind of late to the party. Hope users who endup here may find this useful.
 The use of break keyword is discouraged
Here is a very simple implementation to break away after implementing a retry mechanism
This iterates over the loop for the specified number of times and also if the exception still persists, then the exception is thrown. This can be leveraged for an actual real world scenario where the resttemplate might actually result in IO/Network errors and can be retried in those cases

public class TestClass {

    public static void main(String[] args) throws Exception {

        try {
            int c = anotherM();
            System.out.println("Now the value is" + c);
        } catch (Exception e) {
            System.out.println("Inside" + e);
        }
    }

    public static int anotherM() throws Exception {
        int i = 4;
        Exception ex = null;
        while (i > 0) {
            try {
                System.out.println("print i" + i);

                throw new IOException();
                // return i;
            } catch (Exception e) {
                System.out.println(e);

                i--;
                if (i == 1) {
                    ex = new Exception("ttt");

                }

            }
        }
        if (ex != null) {
            throw new Exception("all new");
        } else {
            return i;
        }

    }

}


问:
Memset In C Using Sizeof Operator :
Here is a struct :

```<code>typedef struct tag_device_sys
{
    char device[STRING_SIZE];
    int id;
    char category;
} device_sys;
</code>```

For memset, which one should be used from below ?

```<code>memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(device_sys));
</code>```

or

```<code>memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(dev_sys));
</code>```

What are the differences ?

答: Richard Stevens (Advanced Programming in the Unix Environment, etc) suggests bzero() or your own portable equivalent because it avoids the common bug of swapping memset() arguments.  You could even make a single-arg macro ZERO(obj) that did bzero(obj, sizeof(*obj)).  Or  ZERO(object) (memset (&(object), '\0', sizeof ((object)))) perhaps is an alternative. Along those lines, nice way to make bugs less possible.

Title: Memset In C Using Sizeof Operator :

Body:
Here is a struct :

typedef struct tag_device_sys
{
    char device[STRING_SIZE];
    int id;
    char category;
} device_sys;

For memset, which one should be used from below ?

memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(device_sys));

or

memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(dev_sys));

What are the differences ?


问:
How to update a Lookup field and a user field in SharePoint with Microsoft Graph?
I'm looking for a way how to update a lookup field and a user field with Microsoft graph ?
I can read the item, but I don't find a way to create or update this kind of field even if I put a correct ID value.</p>

答:
Nowadays it is supported to update lookup fields via Microsoft Graph API.

Lets say there is a field named Category, then depending whether lookup field is represented as single or multi valued, the following examples demonstrate how to set lookup field value.

for single-valued field:

```<code>Url: https://graph.microsoft.com/v1.0/sites/{site-id}/lists/{list-id}/items/{item-id}/fields
Method: PATCH
Body: {
  "CategoryLookupId": "1"
}
</code>```

where

field name is provided in the following format: {field-name}LookupId

field value corresponds to lookup id and provided as a string

for multi-valued field

```<code>Url: https://graph.microsoft.com/v1.0/sites/{site-id}/lists/{list-id}/items/{item-id}/fields
Method: PATCH
{
    "CategoryLookupId@odata.type": "Collection(Edm.String)",
    "CategoryLookupId":["1","2"]
}
</code>```

Body:
Nowadays it is supported to update lookup fields via Microsoft Graph API.

Lets say there is a field named Category, then depending whether lookup field is represented as single or multi valued, the following examples demonstrate how to set lookup field value.

for single-valued field:

Url: https://graph.microsoft.com/v1.0/sites/{site-id}/lists/{list-id}/items/{item-id}/fields
Method: PATCH
Body: {
  "CategoryLookupId": "1"
}

where

field name is provided in the following format: {field-name}LookupId

field value corresponds to lookup id and provided as a string

for multi-valued field

Url: https://graph.microsoft.com/v1.0/sites/{site-id}/lists/{list-id}/items/{item-id}/fields
Method: PATCH
{
    "CategoryLookupId@odata.type": "Collection(Edm.String)",
    "CategoryLookupId":["1","2"]
}


问:
What happens if arguments passed to sscanf are cast
While reviewing and old piece of code, I stumbled upon some coding horror like this one:

```<code>struct Foo
{
    unsigned int  bar;
    unsigned char qux;
    unsigned char xyz;
    unsigned int  etc;
};

void horror(const char* s1, const char* s2, const char* s3, const char* s4, Foo* foo)
{
    sscanf(s1, "%u", &(foo->bar));
    sscanf(s2, "%u", (unsigned int*) &(foo->qux));
    sscanf(s3, "%u", (unsigned int*) &(foo->xyz));
    sscanf(s4, "%u", &(foo->etc));
}
</code>```

So, what is actually happening in the second and third sscanf, with the argument passed being a unsigned char* cast to unsigned int*, but with the format specifier for an unsigned integer? Whatever happens is due to undefined behavior, but why is this even "working"?

As far as I know, the cast effectively does nothing in this case (the actual type of the arguments passed as ... is unknown to the called function). However this has been in production for years and it has never crashed and the surrounding values apparently are not overwritten, I suppose because the members of the structure are all aligned to 32 bits. This is even reading the correct value on the target machine (a little endian 32 bit ARM) but I think that it would no longer work on a different endianness.

Bonus question: what is the cleanest correct way to do this? I know that now we have the %hhu format specifier (apparently introduced by C++11), but what about a legacy C89 compiler?

Please note that the original question had uint32_t instead of unsigned int and unsigned char instead of uint8_t but that was just misleading and out of topic, and by the way the original code I was reviewing uses its own typedefs.

答:
First of all, this of course invokes Undefined Behaviour.

But that kind of horror was quite common in old code, where the C language was used as a higher level assembly language. So here are 2 possible behaviours:

the structure has a 32 bits alignment. All is (rather fine) on a little endian machine: the uint8_t members will recieve the least significant byte of the 32 bits value and the padding bytes will be zeroed (I assume that the program does not try to store a value greater than 255 into an uint8_t)

the structure has not a 32 bits alignement, but the architecture allows scanf to write into mis-aligned variables. The least significant byte of the value read for qux will correctly go into qux and the next 3 zero bytes will erase xyz and etc. On next line, xyz receives its value and etc recieves one more 0 byte. And finally etc will recieve its value. This could have been a rather common hack in the early 80' on an 8086 type machine.

For a portable way, I would use an temporary unsigned integer:

```<code>uint32_t u;
sscanf(s1, "%u", &(foo->bar));
sscanf(s2, "%u", &u);
foo->qux = (uint8_t) u;
sscanf(s3, "%u", &u);
foo->xyz = (uint8_t) u;
sscanf(s4, "%u", &(foo->etc));
</code>```

and trust the compiler to generate code as efficient as the horror way.

Body:
While reviewing and old piece of code, I stumbled upon some coding horror like this one:

struct Foo
{
    unsigned int  bar;
    unsigned char qux;
    unsigned char xyz;
    unsigned int  etc;
};

void horror(const char* s1, const char* s2, const char* s3, const char* s4, Foo* foo)
{
    sscanf(s1, "%u", &(foo->bar));
    sscanf(s2, "%u", (unsigned int*) &(foo->qux));
    sscanf(s3, "%u", (unsigned int*) &(foo->xyz));
    sscanf(s4, "%u", &(foo->etc));
}

So, what is actually happening in the second and third sscanf, with the argument passed being a unsigned char* cast to unsigned int*, but with the format specifier for an unsigned integer? Whatever happens is due to undefined behavior, but why is this even "working"?

As far as I know, the cast effectively does nothing in this case (the actual type of the arguments passed as ... is unknown to the called function). However this has been in production for years and it has never crashed and the surrounding values apparently are not overwritten, I suppose because the members of the structure are all aligned to 32 bits. This is even reading the correct value on the target machine (a little endian 32 bit ARM) but I think that it would no longer work on a different endianness.

Bonus question: what is the cleanest correct way to do this? I know that now we have the %hhu format specifier (apparently introduced by C++11), but what about a legacy C89 compiler?

Please note that the original question had uint32_t instead of unsigned int and unsigned char instead of uint8_t but that was just misleading and out of topic, and by the way the original code I was reviewing uses its own typedefs.

Body:
First of all, this of course invokes Undefined Behaviour.

But that kind of horror was quite common in old code, where the C language was used as a higher level assembly language. So here are 2 possible behaviours:

the structure has a 32 bits alignment. All is (rather fine) on a little endian machine: the uint8_t members will recieve the least significant byte of the 32 bits value and the padding bytes will be zeroed (I assume that the program does not try to store a value greater than 255 into an uint8_t)

the structure has not a 32 bits alignement, but the architecture allows scanf to write into mis-aligned variables. The least significant byte of the value read for qux will correctly go into qux and the next 3 zero bytes will erase xyz and etc. On next line, xyz receives its value and etc recieves one more 0 byte. And finally etc will recieve its value. This could have been a rather common hack in the early 80' on an 8086 type machine.

For a portable way, I would use an temporary unsigned integer:

uint32_t u;
sscanf(s1, "%u", &(foo->bar));
sscanf(s2, "%u", &u);
foo->qux = (uint8_t) u;
sscanf(s3, "%u", &u);
foo->xyz = (uint8_t) u;
sscanf(s4, "%u", &(foo->etc));

and trust the compiler to generate code as efficient as the horror way.


答:
I created a file with following content:

```<code><a><B>
nothing
<blabla>
</blabla>
</B>
</a>
</code>```

In order to get the tags contents, I used following command:

```<code>grep -o "<[a-zA-Z0-9]*>" testtttt.txt
</code>```

Which yielded following result:

```<code><a>
<B>
<blabla>
</code>```

Title: How can I extract all the HTML tags from a page. Not the data between the tags

Body:
I created a file with following content:

<a><B>
nothing
<blabla>
</blabla>
</B>
</a>

In order to get the tags contents, I used following command:

grep -o "<[a-zA-Z0-9]*>" testtttt.txt

Which yielded following result:

<a>
<B>
<blabla>


问:
Should I always use a parallel stream when possible?
With Java 8 and lambdas it's easy to iterate over collections as streams, and just as easy to use a parallel stream. Two examples from the docs, the second one using parallelStream:

```<code>myShapesCollection.stream()
    .filter(e -> e.getColor() == Color.RED)
    .forEach(e -> System.out.println(e.getName()));

myShapesCollection.parallelStream() // <-- This one uses parallel
    .filter(e -> e.getColor() == Color.RED)
    .forEach(e -> System.out.println(e.getName()));
</code>```

As long as I don't care about the order, would it always be beneficial to use the parallel? One would think it is faster dividing the work on more cores.

Are there other considerations? When should parallel stream be used and when should the non-parallel be used?

(This question is asked to trigger a discussion about how and when to use parallel streams, not because I think always using them is a good idea.)

答:
Other answers have already covered profiling to avoid premature optimization and overhead cost in parallel processing. This answer explains the ideal choice of data structures for parallel streaming.

As a rule, performance gains from parallelism are best on streams over ArrayList , HashMap , HashSet , and ConcurrentHashMap instances; arrays; int ranges; and long ranges. What these data structures have in common is that they can all be accurately and cheaply split into subranges of any desired sizes, which makes it easy to divide work among parallel threads. The abstraction used by the streams library to perform this task is the spliterator , which is returned by the spliterator method on Stream and Iterable.

Another important factor that all of these data structures have in common is that they provide good-to-excellent locality of reference when processed sequentially: sequential element references are stored together in memory. The objects referred to by those references may not be close to one another in memory, which reduces locality-of-reference. Locality-of-reference turns out to be critically important for parallelizing bulk operations: without it, threads spend much of their time idle, waiting for data to be transferred from memory into the processor’s cache. The data structures with the best locality of reference are primitive arrays because the data itself is stored contiguously in memory.

Source: Item #48 Use Caution When Making Streams Parallel, Effective Java 3e by Joshua Bloch

Body:
With Java 8 and lambdas it's easy to iterate over collections as streams, and just as easy to use a parallel stream. Two examples from the docs, the second one using parallelStream:

myShapesCollection.stream()
    .filter(e -> e.getColor() == Color.RED)
    .forEach(e -> System.out.println(e.getName()));

myShapesCollection.parallelStream() // <-- This one uses parallel
    .filter(e -> e.getColor() == Color.RED)
    .forEach(e -> System.out.println(e.getName()));

As long as I don't care about the order, would it always be beneficial to use the parallel? One would think it is faster dividing the work on more cores.

Are there other considerations? When should parallel stream be used and when should the non-parallel be used?

(This question is asked to trigger a discussion about how and when to use parallel streams, not because I think always using them is a good idea.)


问:
DevExpress Gridview selection count is 1 but the row is not selected
I'm trying to select gridview row in code source, ı'm using that code block: grdList.Selection.SelectRowByKey("value");

this code is selecting row in the gridview but i can't see the selection on the view , i can get count of selected row 1 but i can't see that on the page,

what is wrong?

grdList.Selection.SelectRowByKey("value");

答: Most likely, your scenario is similar to the one described in the How to select Grid View rows on the sever ticket and the SelectRowByKey method is called during a callback to the server. In this case, call the grid's client-side PerformCallback method and handle the server-side CustomCallback event to select grid rows.</p>


问:
How to allow cascade delete for complex object that has two lists of other complex objects?
I'm struggling with trying to make it work.

I'd want to have an Dealer who has Two Lists of the same type of Items that are in relation, but I'd want also to be able to cascadly delete them.

```<code>public class Dealer
{
    [Key]
    public Guid Id { get; set; }

    public string Name { get; set; }

    public List<Car> OldCars { get; set; } = new List<Car>();

    public List<Car> NewCars { get; set; } = new List<Car>();
}

public class Car
{
    [Key]
    public Guid Id { get; set; }

    public string Model { get; set; }

    public Dealer Dealer { get; set; }
}
</code>```

What I've been trying:

Attempt #1

```<code>modelBuilder.Entity<Car>()
.HasOne(s => s.Dealer)
.WithMany(s => s.OldCars)
.HasForeignKey(x => x.Dealer)
.OnDelete(DeleteBehavior.Cascade);

modelBuilder.Entity<Car>()
.HasOne(s => s.Dealer)
.WithMany(s => s.NewCars)
.HasForeignKey(x => x.Dealer)
.OnDelete(DeleteBehavior.Cascade);
</code>```

System.InvalidOperationException: ''Dealer' cannot be used as a property on entity type 'Car' because it is configured as a navigation.'

Attempt #2
Meanwhile with:

```<code>modelBuilder.Entity<Car>()
.HasOne(s => s.Dealer)
.WithMany(s => s.NewCars)
.HasPrincipalKey(x => x.Id) <--- Principal!
.OnDelete(DeleteBehavior.Cascade);
</code>```

It works properly, but shows warning that

warn: Microsoft.EntityFrameworkCore.Model[10605]
        There are multiple relationships between 'Car' and 'Dealer' without configured foreign key properties causing EF to create shadow properties on 'Car' with names dependent on the discovery order.

Unfortunely while attempting to perform Delete (cascade) it throws an exception:

SqlException: The DELETE statement conflicted with the REFERENCE constraint "FK_Cars_Dealers_DealerId1". The conflict occurred in database "testDB", table "dbo.Cars", column 'DealerId1'.
  The statement has been terminated.

Attempt #3

When I add Dealer's Id to Car

```<code>public class Car
{
    [Key]
    public Guid Id { get; set; }

    public string Model { get; set; }

    public Dealer Dealer { get; set; }

    public Guid DealerID { get; set; }
}
</code>```

It yells about

System.Data.SqlClient.SqlException: 'Cannot create, drop, enable, or disable more than one constraint, column, index, or trigger named 'FK_Cars_Dealers_DealerId' in this context. Duplicate names are not allowed.
  Column names in each table must be unique. Column name 'DealerId' in table 'Cars' is specified more than once.'

#Attempt #3.1

So, after renaming Guid DealerID to e.g Guid DealerID123

it yells

SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Cars_Dealers_DealerID123". The conflict occurred in database "testDB", table "dbo.Dealers", column 'Id'.
  The statement has been terminated.

Anybody has an idea how to make it work?

答:
Thanks to Ivan Stoev recommendation, I managed to resolve it as follow: </p>

```<code>public class Dealer
{
   [Key]
   public Guid Id { get; set; }
   public string Name { get; set; }
   [NotMapped]
   public List<Car> OldCars { get; set; } => NewCars.Where(c => c.IsOld == true);
   public List<Car> NewCars { get; set; } = new List<Car>();
}

public class Car
{
   [Key]
   public Guid Id { get; set; }
   public string Model { get; set; }
   public Dealer Dealer { get; set; }
   public bool IsOld { get; set; }
}
</code>```

<p>In EF6 ModelBuilder I did as follow: </p>

```<code>modelBuilder.Entity<Dealer>()
.HasMany(d => d.NewCars)
.WithRequired()
.WillCascadeOnDelete(true);
</code>```

Body:
I'm struggling with trying to make it work.

I'd want to have an Dealer who has Two Lists of the same type of Items that are in relation, but I'd want also to be able to cascadly delete them.

public class Dealer
{
    [Key]
    public Guid Id { get; set; }

    public string Name { get; set; }

    public List<Car> OldCars { get; set; } = new List<Car>();

    public List<Car> NewCars { get; set; } = new List<Car>();
}

public class Car
{
    [Key]
    public Guid Id { get; set; }

    public string Model { get; set; }

    public Dealer Dealer { get; set; }
}

What I've been trying:

Attempt #1

modelBuilder.Entity<Car>()
.HasOne(s => s.Dealer)
.WithMany(s => s.OldCars)
.HasForeignKey(x => x.Dealer)
.OnDelete(DeleteBehavior.Cascade);

modelBuilder.Entity<Car>()
.HasOne(s => s.Dealer)
.WithMany(s => s.NewCars)
.HasForeignKey(x => x.Dealer)
.OnDelete(DeleteBehavior.Cascade);

System.InvalidOperationException: ''Dealer' cannot be used as a property on entity type 'Car' because it is configured as a navigation.'

Attempt #2
Meanwhile with:

modelBuilder.Entity<Car>()
.HasOne(s => s.Dealer)
.WithMany(s => s.NewCars)
.HasPrincipalKey(x => x.Id) <--- Principal!
.OnDelete(DeleteBehavior.Cascade);

It works properly, but shows warning that

warn: Microsoft.EntityFrameworkCore.Model[10605]
        There are multiple relationships between 'Car' and 'Dealer' without configured foreign key properties causing EF to create shadow properties on 'Car' with names dependent on the discovery order.

Unfortunely while attempting to perform Delete (cascade) it throws an exception:

SqlException: The DELETE statement conflicted with the REFERENCE constraint "FK_Cars_Dealers_DealerId1". The conflict occurred in database "testDB", table "dbo.Cars", column 'DealerId1'.
  The statement has been terminated.

Attempt #3

When I add Dealer's Id to Car

public class Car
{
    [Key]
    public Guid Id { get; set; }

    public string Model { get; set; }

    public Dealer Dealer { get; set; }

    public Guid DealerID { get; set; }
}

It yells about

System.Data.SqlClient.SqlException: 'Cannot create, drop, enable, or disable more than one constraint, column, index, or trigger named 'FK_Cars_Dealers_DealerId' in this context. Duplicate names are not allowed.
  Column names in each table must be unique. Column name 'DealerId' in table 'Cars' is specified more than once.'

#Attempt #3.1

So, after renaming Guid DealerID to e.g Guid DealerID123

it yells

SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Cars_Dealers_DealerID123". The conflict occurred in database "testDB", table "dbo.Dealers", column 'Id'.
  The statement has been terminated.

Anybody has an idea how to make it work?

Body:
Thanks to Ivan Stoev recommendation, I managed to resolve it as follow:

public class Dealer
{
   [Key]
   public Guid Id { get; set; }
   public string Name { get; set; }
   [NotMapped]
   public List<Car> OldCars { get; set; } => NewCars.Where(c => c.IsOld == true);
   public List<Car> NewCars { get; set; } = new List<Car>();
}

public class Car
{
   [Key]
   public Guid Id { get; set; }
   public string Model { get; set; }
   public Dealer Dealer { get; set; }
   public bool IsOld { get; set; }
}

In EF6 ModelBuilder I did as follow:

modelBuilder.Entity<Dealer>()
.HasMany(d => d.NewCars)
.WithRequired()
.WillCascadeOnDelete(true);


问:
How can I sort a collection based in the given order in other array
I have a array of ibject with another object inside each element like

```<code>data = [
  {
    name: "A",
    type: "AA",
    children: [ { id: 1, name: "Child-A", admin: ["Y"] }],
    other: "NA"
  },
  {
    name: "B",
    type: "BB",
    children: [ { id: 2, name: "Child-B" }],
    other: "NA"
  },
  {
    name: "C",
    type: "CC",
    children: [ { id: 3, name: "Child-C" }],
    other: "NA"
  }

]
</code>```

I want to order the whole collection by the children.id value but based on the order given by another array

```<code>orderArray = [3, 1, 2]
</code>```

So the output would be

```<code>data =[
    {
        name: "C",
        type: "CC",
        children: [ { id: 3, name: "Child-C" }],
        other: "NA"
    },
    {
        name: "A",
        type: "AA",
        children: [ { id: 1, name: "Child-A", admin: ["Y"] }],
        other: "NA"
    },
    {
        name: "B",
        type: "BB",
        children: [ { id: 2, name: "Child-B" }],
        other: "NA"
    }
]
</code>```

答:
You can pass a comparator to Array.sort which compares/sorts by index of children[0].id in orderArray array

let data = [{name:"A",type:"AA",children:[{id:1,name:"Child-A",admin:["Y"]}],other:"NA"},{name:"B",type:"BB",children:[{id:2,name:"Child-B"}],other:"NA"},{name:"C",type:"CC",children:[{id:3,name:"Child-C"}],other:"NA"}];
let orderArray = [3, 1, 2];

data.sort((a,b) => orderArray.indexOf(a.children[0].id) - orderArray.indexOf(b.children[0].id));
console.log(data);```

Body:
I have a array of ibject with another object inside each element like

data = [
  {
    name: "A",
    type: "AA",
    children: [ { id: 1, name: "Child-A", admin: ["Y"] }],
    other: "NA"
  },
  {
    name: "B",
    type: "BB",
    children: [ { id: 2, name: "Child-B" }],
    other: "NA"
  },
  {
    name: "C",
    type: "CC",
    children: [ { id: 3, name: "Child-C" }],
    other: "NA"
  }

]

I want to order the whole collection by the children.id value but based on the order given by another array

orderArray = [3, 1, 2]

So the output would be

data =[
    {
        name: "C",
        type: "CC",
        children: [ { id: 3, name: "Child-C" }],
        other: "NA"
    },
    {
        name: "A",
        type: "AA",
        children: [ { id: 1, name: "Child-A", admin: ["Y"] }],
        other: "NA"
    },
    {
        name: "B",
        type: "BB",
        children: [ { id: 2, name: "Child-B" }],
        other: "NA"
    }
]


问:
java.lang.IllegalArgumentException: Not a managed type: class while initiating repository bean
Hi I am trying to load some database values at start time of spring boot application. I have autowired service, and in service i have autowired Dao. Below is the error.

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'validationExpressionService': Unsatisfied dependency expressed through field 'validationExpressionDao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'IValidationExpressionDao': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.ril.nfg.dao.bean.ValidationExpression

I have added @EnitityScan @EnableJPARepository
FYI, Primary key in the case in String, hope that is ok.

Entity

```<code>import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

/**
 * The Class ValidationExpression.
 */
package com.ril.nfg.dao.bean;

@Entity
@Table(name = "VALIDATION_EXPRESSION")
public class ValidationExpression implements Serializable {

    private static final long serialVersionUID = 9096950800262493651L;

    private String validationId;
    private String expression;
    private String createdBy;
    private Date createdOn;
    private String description;
    private String responseCode;

     @Id
     @Column(name = "VALIDATION_ID", nullable = false, length = 100)
    public String getValidationId() {
        return validationId;
    }

    public void setValidationId(String validationId) {
        this.validationId = validationId;
    }

     @Column(name = "EXPRESSION", nullable = false, length = 200)
    public String getExpression() {
        return expression;
    }

    public void setExpression(String expression) {
        this.expression = expression;
    }
//remaining getters and setters
}
</code>```

Repository

```<code>package com.ril.nfg.dao.repos;

import com.ril.nfg.dao.bean.ValidationExpression;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

/**
 * The Interface IValidationExpressionDao.
 */
@Repository
public interface IValidationExpressionDao extends JpaRepository<ValidationExpression, String> {
}
</code>```

Service

```<code>import java.util.List;

@Service
public class ValidationExpressionService {

    @Autowired
    IValidationExpressionDao validationExpressionDao;

    public List<ValidationExpression> getAll() {
        return validationExpressionDao.findAll();
    }
}
</code>```

Class with @Autwired Service

```<code>public class CacheModuleParam implements ApplicationContextAware{

private static List<ValidationExpression> validationExpressionList = null;

@Autowired
    ValidationExpressionService validationExpressionService;

@Override
    public void setApplicationContext(final ApplicationContext appContext) throws BeansException {
validationExpressionList = validationExpressionService.getAll();
}
}
</code>```

Application Class

```<code>@ComponentScan(basePackages = {"com.ril.nfg"})
@EnableWebMvc
@EnableAutoConfiguration
@SpringBootApplication//(exclude={DataSourceAutoConfiguration.class})
@EnableJpaRepositories(basePackages="com.ril.nfg.dao.repos",entityManagerFactoryRef="oracleEntityManagerFactory")
//@EntityScan(basePackages = "com.ril.nfg.dao.bean")
public class NFGApplication {

    public static void main(String[] args) {
        SpringApplication.run(NFGApplication.class, args);
    }

}
</code>```

All solutions on internet focuses on @EntityScan. Please help me understand what is wrong with this code. Thanks in advance

答:
Why do you have all this configuration? Simply put our application in the package tree one level above all the other classes and you can go with a class like this:

```<code>@SpringBootApplication
public class NFGApplication {

    public static void main(String[] args) {
        SpringApplication.run(NFGApplication.class, args);
    }

}
</code>```

Packages:

```<code>com.ril.nfg <- here you put NFGApplication
</code>```

And all other classes in subpackages of com.ril.nfg

And then everything will work!

Body:
Hi I am trying to load some database values at start time of spring boot application. I have autowired service, and in service i have autowired Dao. Below is the error.

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'validationExpressionService': Unsatisfied dependency expressed through field 'validationExpressionDao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'IValidationExpressionDao': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.ril.nfg.dao.bean.ValidationExpression

I have added @EnitityScan @EnableJPARepository
FYI, Primary key in the case in String, hope that is ok.

Entity

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

/**
 * The Class ValidationExpression.
 */
package com.ril.nfg.dao.bean;

@Entity
@Table(name = "VALIDATION_EXPRESSION")
public class ValidationExpression implements Serializable {

    private static final long serialVersionUID = 9096950800262493651L;

    private String validationId;
    private String expression;
    private String createdBy;
    private Date createdOn;
    private String description;
    private String responseCode;

     @Id
     @Column(name = "VALIDATION_ID", nullable = false, length = 100)
    public String getValidationId() {
        return validationId;
    }

    public void setValidationId(String validationId) {
        this.validationId = validationId;
    }

     @Column(name = "EXPRESSION", nullable = false, length = 200)
    public String getExpression() {
        return expression;
    }

    public void setExpression(String expression) {
        this.expression = expression;
    }
//remaining getters and setters
}

Repository

package com.ril.nfg.dao.repos;

import com.ril.nfg.dao.bean.ValidationExpression;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

/**
 * The Interface IValidationExpressionDao.
 */
@Repository
public interface IValidationExpressionDao extends JpaRepository<ValidationExpression, String> {
}

Service

import java.util.List;

@Service
public class ValidationExpressionService {

    @Autowired
    IValidationExpressionDao validationExpressionDao;

    public List<ValidationExpression> getAll() {
        return validationExpressionDao.findAll();
    }
}

Class with @Autwired Service

public class CacheModuleParam implements ApplicationContextAware{

private static List<ValidationExpression> validationExpressionList = null;

@Autowired
    ValidationExpressionService validationExpressionService;

@Override
    public void setApplicationContext(final ApplicationContext appContext) throws BeansException {
validationExpressionList = validationExpressionService.getAll();
}
}

Application Class

@ComponentScan(basePackages = {"com.ril.nfg"})
@EnableWebMvc
@EnableAutoConfiguration
@SpringBootApplication//(exclude={DataSourceAutoConfiguration.class})
@EnableJpaRepositories(basePackages="com.ril.nfg.dao.repos",entityManagerFactoryRef="oracleEntityManagerFactory")
//@EntityScan(basePackages = "com.ril.nfg.dao.bean")
public class NFGApplication {

    public static void main(String[] args) {
        SpringApplication.run(NFGApplication.class, args);
    }

}

All solutions on internet focuses on @EntityScan. Please help me understand what is wrong with this code. Thanks in advance

Body:
Why do you have all this configuration? Simply put our application in the package tree one level above all the other classes and you can go with a class like this:

@SpringBootApplication
public class NFGApplication {

    public static void main(String[] args) {
        SpringApplication.run(NFGApplication.class, args);
    }

}

Packages:

com.ril.nfg <- here you put NFGApplication

And all other classes in subpackages of com.ril.nfg

And then everything will work!


答:
Get alternating columns, add them, and divide by 2:</p>

```<code># example data, 5 rows, 11 cols
x <- mtcars[1:5,  ]

cbind(
  # keep first 7 columns as is
  x[ 1:7 ],
  # then take alternating cols, add, and, divide by 2
  (x[ 8:11 ][, c(TRUE, FALSE) ] + x[ 8:11 ][, c(FALSE, TRUE) ]) / 2
  )
</code>```

Title: Averaging two columns with partial matching in R (big size data)

Body:
I have a matrix which has 562709 rows and 803 columns, and for the columns, it has 7 metadata and 796 replicates data which should be combined in pair and take the average.

I googled the same problems but it didn't work well especially since my matrix is so huge, so I wonder if anybody can help me with this matter.

 [1] "seqnames"
 [2] "start"
 [3] "end"
 [4] "name"
 [5] "score"
 [6] "annotation"
 [7] "GC"
 [8] "ACCx_025FE5F8_885E_433D_9018_7AE322A92285_X034_S09_L133_B1_T1_PMRG"
 [9] "ACCx_025FE5F8_885E_433D_9018_7AE322A92285_X034_S09_L134_B1_T2_PMRG"
[10] "ACCx_2A5AE757_20D5_49B6_95FF_CAE08E8197A0_X012_S05_L033_B1_T1_P024"
[11] "ACCx_2A5AE757_20D5_49B6_95FF_CAE08E8197A0_X012_S05_L034_B1_T2_P025"
[12] "ACCx_3D0CD3BD_3960_46FB_92C3_777F11CCD0FC_X011_S06_L011_B1_T1_P024"
[13] "ACCx_3D0CD3BD_3960_46FB_92C3_777F11CCD0FC_X011_S06_L012_B1_T2_P026"
[14] "ACCx_4D0D43F5_D8F0_4735_92D5_F40E321C7A05_X010_S09_L065_B1_T1_P019"
[15] "ACCx_4D0D43F5_D8F0_4735_92D5_F40E321C7A05_X010_S09_L066_B1_T2_P020"
[16] "ACCx_81A262BD_3078_4BDB_8EB1_30DD6D7948C3_X027_S03_L081_B1_T1_P063"
[17] "ACCx_81A262BD_3078_4BDB_8EB1_30DD6D7948C3_X027_S03_L082_B1_T2_P067"
...
[800]"UCEC_C335297F_2D63_4973_9182_FA18C28E001E_X037_S04_L055_B1_T1_P088"
[801]"UCEC_C335297F_2D63_4973_9182_FA18C28E001E_X037_S04_L056_B1_T2_P089"
[802]"UCEC_D820B024_6B3B_4B5B_866E_F9A8139C270B_X039_S09_L113_B1_T1_P099"
[803]"UCEC_D820B024_6B3B_4B5B_866E_F9A8139C270B_X039_S09_L114_B1_T2_P098"

Like above, the first 7 columns shouldn't be modified, but for the columns from 8, pair should be combined as their average. (eg. column 8,9 should be combined, and 10,11...)

Body:
Get alternating columns, add them, and divide by 2:

# example data, 5 rows, 11 cols
x <- mtcars[1:5,  ]

cbind(
  # keep first 7 columns as is
  x[ 1:7 ],
  # then take alternating cols, add, and, divide by 2
  (x[ 8:11 ][, c(TRUE, FALSE) ] + x[ 8:11 ][, c(FALSE, TRUE) ]) / 2
  )


问:
Odoo Security Access rule
I have created a security file as that the user who is logged in can only able to see his data. The domain force is correct and working. But from some users, while creating any lead in the crm_lead model, I am finding such error:

The requested operation cannot be completed due to security restrictions. Please contact your system administrator.

(Document type: res. users, Operation: read).
    And, in some users, I am available to do create lead and generate it too.
    Please let me know, what am I doing wrong?

```<code><record model="ir.module.category" id="module_management">
    <field name="name">CRM LEAD MODIFICATION</field>
    <field name="description">User access level for CRM module</field>
    <field name="sequence">3</field>
</record>

    <record id="machines_group_user" model="res.groups">

     <field name="name">CRM / User</field>
     <field name="category_id" ref="crm_partner.module_management"/>

    </record>
    <record id="machines_manager_user" model="res.groups">
        <field name="name">CRM / Manager</field>
        <field name="category_id" ref="crm_partner.module_management"/>

    </record>
    <record id="rule_machines_group_user" model="ir.rule">
     <field name="name">CRM User</field>
     <field name="model_id" ref="model_res_partner"/>
     <field name="domain_force">['|',('create_uid','=',False),('create_uid','=',user.id)]</field>

        <!-- <field name="domain_force">['|',('parent_id','=',False),('parent_id','=',user.parent_id.id),('create_uid','=',user.id)]</field> -->

     <field name="groups" eval="[(4, ref('crm_partner.machines_group_user'))]"/>

    </record>
    <record id="hr_crm_lead manager" model="ir.rule">
        <field name="name">CRM Manager</field>
        <field name="model_id" ref="model_res_partner" />
        <field name="domain_force">[(1, '=', 1)]</field>
        <field name="groups" eval="[(4, ref('crm_partner.machines_manager_user'))]"/>
    </record>
</code>```

答: This error normally occurs when the record rules are not given correctly, which means it is not matching with the access rights. Uncheck the active button in the record rules to check the page loads without any errors. Domain values given should be valid and it should go along with the access rights.</p>

Title: Odoo Security Access rule

Body:
I have created a security file as that the user who is logged in can only able to see his data. The domain force is correct and working. But from some users, while creating any lead in the crm_lead model, I am finding such error:

The requested operation cannot be completed due to security restrictions. Please contact your system administrator.

(Document type: res. users, Operation: read).
    And, in some users, I am available to do create lead and generate it too.
    Please let me know, what am I doing wrong?

<record model="ir.module.category" id="module_management">
    <field name="name">CRM LEAD MODIFICATION</field>
    <field name="description">User access level for CRM module</field>
    <field name="sequence">3</field>
</record>

    <record id="machines_group_user" model="res.groups">

     <field name="name">CRM / User</field>
     <field name="category_id" ref="crm_partner.module_management"/>

    </record>
    <record id="machines_manager_user" model="res.groups">
        <field name="name">CRM / Manager</field>
        <field name="category_id" ref="crm_partner.module_management"/>

    </record>
    <record id="rule_machines_group_user" model="ir.rule">
     <field name="name">CRM User</field>
     <field name="model_id" ref="model_res_partner"/>
     <field name="domain_force">['|',('create_uid','=',False),('create_uid','=',user.id)]</field>

     <field name="groups" eval="[(4, ref('crm_partner.machines_group_user'))]"/>

    </record>
    <record id="hr_crm_lead manager" model="ir.rule">
        <field name="name">CRM Manager</field>
        <field name="model_id" ref="model_res_partner" />
        <field name="domain_force">[(1, '=', 1)]</field>
        <field name="groups" eval="[(4, ref('crm_partner.machines_manager_user'))]"/>
    </record>


问:
Least repeating chararcter in a string
I'm trying to find the least repeating character in a string ,it works for some input but it fails for some input.

```<code>Map<Character, Integer> map = new HashMap<Character, Integer> ();

    String s = "abcdabcdabcdacd";
    char[] chars = s.toCharArray();

    for (Character ch: chars) {
        if (map.containsKey(ch)) {
            map.put(ch, map.get(ch) + 1);
        } else {
            map.put(ch, 1);
        }
    }

    Set<Character> keys = map.keySet();

    for (Character ch: keys) {
        if (map.get(ch) ==1) {
            System.out.println(ch + " ");
        }
    }
</code>```

I expect the output to be b but it doesn't show anything.
If i give aabaa as the input then it shows b and that's correct.

答:
Using streams you may simply do:

```<code>final String s = "abcdabcdabcdacd";

String leastRepeated =
   s.chars().mapToObj(i -> Character.toString((char) i))      // map to Stream<String>
    .collect(Collectors.toMap(k -> k, v -> 1, Integer::sum))  // Map<String, Integer>
    .entrySet().stream()                                      // stream over map
    .min(Comparator.comparing(Entry::getValue))               // comparing values in map
    .get().getKey();                                          // get resp entry
</code>```

which outputs:

b

Title: Least repeating chararcter in a string

Body:
I'm trying to find the least repeating character in a string ,it works for some input but it fails for some input.

Map<Character, Integer> map = new HashMap<Character, Integer> ();

    String s = "abcdabcdabcdacd";
    char[] chars = s.toCharArray();

    for (Character ch: chars) {
        if (map.containsKey(ch)) {
            map.put(ch, map.get(ch) + 1);
        } else {
            map.put(ch, 1);
        }
    }

    Set<Character> keys = map.keySet();

    for (Character ch: keys) {
        if (map.get(ch) ==1) {
            System.out.println(ch + " ");
        }
    }

I expect the output to be b but it doesn't show anything.
If i give aabaa as the input then it shows b and that's correct.

Body:
Using streams you may simply do:

final String s = "abcdabcdabcdacd";

String leastRepeated =
   s.chars().mapToObj(i -> Character.toString((char) i))      // map to Stream<String>
    .collect(Collectors.toMap(k -> k, v -> 1, Integer::sum))  // Map<String, Integer>
    .entrySet().stream()                                      // stream over map
    .min(Comparator.comparing(Entry::getValue))               // comparing values in map
    .get().getKey();                                          // get resp entry

which outputs:

b


问:
Can an asyncio event loop run in the background without suspending the Python interpreter?
The documentation for asyncio gives two examples for how to print "Hello World" every two seconds:
https://docs.python.org/3/library/asyncio-eventloop.html#asyncio-hello-world-callback
https://docs.python.org/3/library/asyncio-task.html#asyncio-hello-world-coroutine

I can run those from the interpreter, but if I do I lose access to the interpreter. Can an asyncio event loop be run in the background, so that I can keep typing commands at the interpreter?

答:
With Python 3.8, you can use the new asyncio REPL.</p>

```<code>$ python -m asyncio
>>> async def greet_every_two_seconds():
...     while True:
...         print('Hello World')
...         await asyncio.sleep(2)
...
>>> # run in main thread (Ctrl+C to cancel)
>>> await greet_every_two_seconds()
...
>>> # run in background
>>> asyncio.create_task(greet_every_two_seconds())
</code>```

Body:
With Python 3.8, you can use the new asyncio REPL.

$ python -m asyncio
>>> async def greet_every_two_seconds():
...     while True:
...         print('Hello World')
...         await asyncio.sleep(2)
...
>>> # run in main thread (Ctrl+C to cancel)
>>> await greet_every_two_seconds()
...
>>> # run in background
>>> asyncio.create_task(greet_every_two_seconds())