问:
Pass an argument from a module
I need help understanding how to pass on an argument from an imported module.

The module contains some custom arguments such as -one, -two, -three

I am trying to make a GUI using the commands from the module.
eg. If "One" is selected from the drop down menu, pass through the -one command.

However when I do so (using the example below), I get the error: "A positional parameter cannot be found that accepts argument '-one'."

I can see that using the code below, it adds single quotations around the command which probably breaks it.

I know I can run an IF statement (eg if combobox.text = "one", do this), however I would prefer to use a variable instead of having to make multiple if statements or a loop. The use of a variable seems like a simpler option.

I'm learning this language as I go so I'm not quite there yet with the knowledge :)

Thanks for any help. Hope this made sense.

$variable = $comboboxNumbers.Text
#example One is selected from the dropdown

Custom-ADCommand -identity "username" $variable

```

答:
Below is simple example method:

```<code>    function Set-SwitchParams {
        [CmdletBinding()]
        param (
            # Parameter help description
            [Parameter(Mandatory = $false)]
            [switch]
            $SwitchA,
            [Parameter(Mandatory = $false)]
            [switch]
            $SwitchB
        )

        begin {
        }

        process {
        }

        end {
            if ($SwitchA){
                Write-Host "SwitchA is activated"
            }
            if ($SwitchB){
                Write-Host "SwitchB is activated"
            }
        }
    }
</code>```

Put the method in a PS1 file, e.g. SwitchPlayground.ps1. Then source the file in PowerShell via:

```<code>  . .\SwitchPlayground.ps1
</code>```

Afterward, you can play around with the command, e.g.:

```<code> Set-SwitchParmas -SwitchA
</code>```

I'd suggest studying the following links:

about functions basic

about functions advanced

about function parameters

Hope that helps.

Title: Pass an argument from a module

Body:
Below is simple example method:

    function Set-SwitchParams {
        [CmdletBinding()]
        param (
            # Parameter help description
            [Parameter(Mandatory = $false)]
            [switch]
            $SwitchA,
            [Parameter(Mandatory = $false)]
            [switch]
            $SwitchB
        )

        begin {
        }

        process {
        }

        end {
            if ($SwitchA){
                Write-Host "SwitchA is activated"
            }
            if ($SwitchB){
                Write-Host "SwitchB is activated"
            }
        }
    }

Put the method in a PS1 file, e.g. SwitchPlayground.ps1. Then source the file in PowerShell via:

  . .\SwitchPlayground.ps1

Afterward, you can play around with the command, e.g.:

 Set-SwitchParmas -SwitchA

I'd suggest studying the following links:

about functions basic

about functions advanced

about function parameters

Hope that helps.


来源: stackexchange

答:
An If statement if probably much nicer, but its possible to create a string and then execute the string in powershell.

As a simple example take this string

$string = '@("test","hello","whats up")'

I can then execute it and use it to create an array

$array = invoke-expression $string

Which will create an array with "test", "hello" and "whats up" and store it in $array

PS C:\temp> $string = '@("test","hi","what")'
PS C:\temp> $array = Invoke-Expression $string
PS C:\temp> $array
test
hi
what

ContentLicense: CC BY-SA 4.0

Title: Pass an argument from a module

Body:
I need help understanding how to pass on an argument from an imported module.

The module contains some custom arguments such as -one, -two, -three

I am trying to make a GUI using the commands from the module.
eg. If "One" is selected from the drop down menu, pass through the -one command.

However when I do so (using the example below), I get the error: "A positional parameter cannot be found that accepts argument '-one'."

I can see that using the code below, it adds single quotations around the command which probably breaks it.

I know I can run an IF statement (eg if combobox.text = "one", do this), however I would prefer to use a variable instead of having to make multiple if statements or a loop. The use of a variable seems like a simpler option.

I'm learning this language as I go so I'm not quite there yet with the knowledge :)

Thanks for any help. Hope this made sense.

$variable = $comboboxNumbers.Text
#example One is selected from the dropdown

Custom-ADCommand -identity "username" $variable


问:
Illegal characters in path when calling the index view from my controller
I am receiving an ArgumentException when invoking the index action of one of my controllers and I am not sure why. The error message is the following:

Server Error in '/' Application.

Illegal characters in path.

```<code>[ArgumentException: Illegal characters in path.]
 System.IO.Path.CheckInvalidPathChars(String path) +126
 System.IO.Path.Combine(String path1, String path2) +38
</code>```

I am not sure why this is happening. here is the code from the controller:

```<code>    public ActionResult Index()
    {
        var glaccounts = db.GLAccounts.ToString();
        return View(glaccounts);
    }
</code>```

答:
The ambiguity comes from the fact that you are using string as model type. This ambiguity could be resolved like this:

```<code>public ActionResult Index()
{
    var glaccounts = db.GLAccounts.ToString();
    return View((object)glaccounts);
}
</code>```

or:

```<code>public ActionResult Index()
{
    object glaccounts = db.GLAccounts.ToString();
    return View(glaccounts);
}
</code>```

or:

```<code>public ActionResult Index()
{
    var glaccounts = db.GLAccounts.ToString();
    return View("Index", glaccounts);
}
</code>```

Notice the cast to object to pick the proper method overload as there is already a View method which takes a string argument which represents the view name so you cannot throw whatever you want to it => if it's a string it must be the name of the view and this view must exist.

ContentLicense: CC BY-SA 3.0

Body:
I am receiving an ArgumentException when invoking the index action of one of my controllers and I am not sure why. The error message is the following:

Server Error in '/' Application.

Illegal characters in path.

[ArgumentException: Illegal characters in path.]
 System.IO.Path.CheckInvalidPathChars(String path) +126
 System.IO.Path.Combine(String path1, String path2) +38

I am not sure why this is happening. here is the code from the controller:

    public ActionResult Index()
    {
        var glaccounts = db.GLAccounts.ToString();
        return View(glaccounts);
    }

Body:
The ambiguity comes from the fact that you are using string as model type. This ambiguity could be resolved like this:

public ActionResult Index()
{
    var glaccounts = db.GLAccounts.ToString();
    return View((object)glaccounts);
}

or:

public ActionResult Index()
{
    object glaccounts = db.GLAccounts.ToString();
    return View(glaccounts);
}

or:

public ActionResult Index()
{
    var glaccounts = db.GLAccounts.ToString();
    return View("Index", glaccounts);
}

Notice the cast to object to pick the proper method overload as there is already a View method which takes a string argument which represents the view name so you cannot throw whatever you want to it => if it's a string it must be the name of the view and this view must exist.


问:
Understanding scoping of event handlers in web workers
Consider the following webworker code from: https://www.html5rocks.com/en/tutorials/workers/basics/

Web page:

```<code><button onclick="sayHI()">Say HI</button>
<button onclick="unknownCmd()">Send unknown command</button>
<button onclick="stop()">Stop worker</button>
<output id="result"></output>

<script>
  function sayHI() {
    worker.postMessage({'cmd': 'start', 'msg': 'Hi'});
  }

  function stop() {
    // worker.terminate() from this script would also stop the worker.
    worker.postMessage({'cmd': 'stop', 'msg': 'Bye'});
  }

  function unknownCmd() {
    worker.postMessage({'cmd': 'foobard', 'msg': '???'});
  }

  var worker = new Worker('doWork2.js');

  worker.addEventListener('message', function(e) {
    document.getElementById('result').textContent = e.data;
  }, false);
</script>
</code>```

Then in doWork2.js:

```<code>self.addEventListener('message', function(e) {
  var data = e.data;
  switch (data.cmd) {
    case 'start':
      self.postMessage('WORKER STARTED: ' + data.msg);
      break;
    case 'stop':
      self.postMessage('WORKER STOPPED: ' + data.msg +
                       '. (buttons will no longer work)');
      self.close(); // Terminates the worker.
      break;
    default:
      self.postMessage('Unknown command: ' + data.msg);
  };
}, false);
</code>```

So when you click SayHi, the "message" event handler defined in doWork2 picks up the event first. Then it fires another "message" event which is picked up by the handler defined on the main page that prints out the message.

The flow of steps is as such.

User clicks button, raises message event.

Handler in doWork2 is executed.

Handler in doWork2 raises message event

Handler on webpage is executed

Please answer the following 2 questions:

Question 1:  In step 2. above why is the handler in doWork2 triggered, but not the handler on the page?

Question 2: In step 4 after the event is triggered from doWork2 why is the handler on the page executed, but the one in doWork2 isn't recursively executed?

答:
It turns out that there are two implementations of postMessage on two different objects.

Answer to Question 1

When calling worker.postMessage()

...the Worker interface sends a message to the worker's inner scope

And so the message event handler on the page doesn't see it.

Answer to Question 2

When calling self.postMesssage , self is the worker's global scope, which has an implementation that works as follows:

sends back information to the thread that spawned it using the
  DedicatedWorkerGlobalScope.postMessage method.

As such it doesn't recursively call itself because the message event is only visible in the thread that spawned it.

Source: https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage

Body:
Consider the following webworker code from: https://www.html5rocks.com/en/tutorials/workers/basics/

Web page:

<button onclick="sayHI()">Say HI</button>
<button onclick="unknownCmd()">Send unknown command</button>
<button onclick="stop()">Stop worker</button>
<output id="result"></output>

Then in doWork2.js:

self.addEventListener('message', function(e) {
  var data = e.data;
  switch (data.cmd) {
    case 'start':
      self.postMessage('WORKER STARTED: ' + data.msg);
      break;
    case 'stop':
      self.postMessage('WORKER STOPPED: ' + data.msg +
                       '. (buttons will no longer work)');
      self.close(); // Terminates the worker.
      break;
    default:
      self.postMessage('Unknown command: ' + data.msg);
  };
}, false);

So when you click SayHi, the "message" event handler defined in doWork2 picks up the event first. Then it fires another "message" event which is picked up by the handler defined on the main page that prints out the message.

The flow of steps is as such.

User clicks button, raises message event.

Handler in doWork2 is executed.

Handler in doWork2 raises message event

Handler on webpage is executed

Please answer the following 2 questions:

Question 1:  In step 2. above why is the handler in doWork2 triggered, but not the handler on the page?

Question 2: In step 4 after the event is triggered from doWork2 why is the handler on the page executed, but the one in doWork2 isn't recursively executed?


问:
Query the last instance with condition in Rails
In a Rails application how can I query the last instance of a particular model having multiple conditions?

```<code>class User
    has_many: tests

class TestAttempt
    belongs_to: user
    belongs_to: test

class Test
    has_many: test_attempts
</code>```

The problem here is each user can take a single test any number of times. Each test_attempt is stored in TestAttempt. But I need to query only the last attempt of a particular test. So the process is like this:

```<code>Find TestAttempt by user_id ---> Something like this ---> TestAttempt.where(user_id: user_id)
Then find the test_id's of the above query.
Then get the last instance of the TestAttempt for each Test for each User
</code>```

So my output might be something like:

```<code>user1: test_1-last-attempt-marks: 28, test_2-last-attempt-marks-30
user2: test_1-last-attempt-marks: 18, test_2-last-attempt-marks-40
</code>```

Right now I am querying the database and adding the results to the array for a particular user and then looping over each element of the array and taking the last instance of the value like this:

```<code>def get_test_marks(user_id)
    tests = Test.where(user_id: user_id).to_a
    tests.each do |test|
        #check the name and and add to array if not present, if present then delete the existing one and add new one until last for each test
    end
</code>```

Or

```<code>def get_test_marks(user_id)
    test_attempts = TestAttempt.where(user_id: user_id).select('distinct test_id, marks')
</code>```

Is there a way to query directly from database the last attempt of each test for a particular user instead of writing code in the above way?

答:
```<code>Test.all.group_by { |test|
test.user_id}.flat_map { |test, data|  data.sort_by(&:created_at).last(1)
}
</code>```

Try this updated code

Body:
In a Rails application how can I query the last instance of a particular model having multiple conditions?

class User
    has_many: tests

class TestAttempt
    belongs_to: user
    belongs_to: test

class Test
    has_many: test_attempts

The problem here is each user can take a single test any number of times. Each test_attempt is stored in TestAttempt. But I need to query only the last attempt of a particular test. So the process is like this:

Find TestAttempt by user_id ---> Something like this ---> TestAttempt.where(user_id: user_id)
Then find the test_id's of the above query.
Then get the last instance of the TestAttempt for each Test for each User

So my output might be something like:

user1: test_1-last-attempt-marks: 28, test_2-last-attempt-marks-30
user2: test_1-last-attempt-marks: 18, test_2-last-attempt-marks-40

Right now I am querying the database and adding the results to the array for a particular user and then looping over each element of the array and taking the last instance of the value like this:

def get_test_marks(user_id)
    tests = Test.where(user_id: user_id).to_a
    tests.each do |test|
        #check the name and and add to array if not present, if present then delete the existing one and add new one until last for each test
    end

Or

def get_test_marks(user_id)
    test_attempts = TestAttempt.where(user_id: user_id).select('distinct test_id, marks')

Is there a way to query directly from database the last attempt of each test for a particular user instead of writing code in the above way?

Body:
Test.all.group_by { |test|
test.user_id}.flat_map { |test, data|  data.sort_by(&:created_at).last(1)
}

Try this updated code


问:
How to get approximate float value in Python?
The value of A is

```<code>A = 0.4000070095062256
</code>```

and after that I have the below code to check the value of A

```<code>if (A == 0.400):
    print('pass')
else:
    print('Fail')
</code>```

I want to print Pass. The above code is printing Fail every time. How will i get approx value of A??

Note: In the condition I have to check the value of A with exactly equal to 0.400. and I mean to say I need approx value of A in float.

答:
You could check, if the distance to 0.4 is less than a given limit, e.g.:

```<code>if abs(A - 0.4) < 0.0001:
    print("Pass")
</code>```

Body:
The value of A is

A = 0.4000070095062256

and after that I have the below code to check the value of A

if (A == 0.400):
    print('pass')
else:
    print('Fail')

I want to print Pass. The above code is printing Fail every time. How will i get approx value of A??

Note: In the condition I have to check the value of A with exactly equal to 0.400. and I mean to say I need approx value of A in float.

Body:
You could check, if the distance to 0.4 is less than a given limit, e.g.:

if abs(A - 0.4) < 0.0001:
    print("Pass")


问:
How can I know if related data is included when using eager loading in Entity Framework?
I am working on a project that is using Repository pattern. We are using Entity Framework to retrieve data from the database. To load related data we use eager loading which means that we have to explicitly include related data.

Say that we want to have all blogs and their related posts we would have to write:

```<code>_dbContext.Blogs.Include(b => b.Posts)
</code>```

The disadvantages with this is that you can only see which related data is loaded in the repository class.

I have tried to shown an example below. Here the problem occurs in the class BlogViewModel.cs because you try to access blogs.Posts, but posts is not included in the original query. So if you are trying to get related data, one would have to check the origin of query and see if it is included.

Repository.cs:

```<code>public IEnumerable<BlogDbModel> GetBlogs()
{
    return _dbContext.Blogs.ToList();
}
</code>```

Service.cs:

```<code>public IEnumerable<BlogViewModel> GetBlogs()
{
    return _repository.Select(x => new BlogViewModel(x));
}
</code>```

BlogViewModel.cs:

```<code>public class BlogViewModel
{
    public BlogViewModel(BlogDbModel blogDbModel)
    {
        Name = blogDbModel.Name;
        Posts = blogDbModel.Posts;
    }

    public string Name { get; set; }
    public IEnumerable<Posts> Posts { get; set; }
}
</code>```

Does anyone have a smart solution to this? Is it possible give an compilation error if you are trying to access data that is not included?

Two options that I have thought about are:

Use lazy-loading instead

Always return an IQueryable from the repository

Thanks

答:
No you dont have any option to give compilation error on this context. Data either way are loaded in the run-time.

LazyLoading
Assuming your displaying Blogs, Posts, Comments in view, So you need to load everything when the page load.
When you enable lazyload and map properties that not been included in the data layer query it will load related entities

```<code>public BlogViewModel(BlogDbModel blogDbModel)
{
  Name = blogDbModel.Name;
  Posts = blogDbModel.Posts;
 }
</code>```

If you enable lazyload and do this post will be fetched using lazyload feature. What if post contains a reference to User or any other object it will load those too.
When you need everything at first place its not recommended to use lazyload because it will additional round-trip to database.

IQueryable from repository

I would say IQueryable to a viewmodel is leaky abstraction. Ideally your data layer should be performing these. Providing IQuerable<BlogDbModel> to Viewmodel is like developer able to fetch 1Blogs=>Post=>User=>Accounts1 anything related from this.

IMHO I would write data layer methods which are needed for the view.

LazyloadingEnabled = false;

```<code>public IEnumerable<BlogDbModel> GetBlogs()
{

    return _dbContext.Blogs.ToList();
}

public IEnumerable<BlogDbModel> GetBlogsAndPosts()
{

  return _dbContext.Blogs.Include("Posts").ToList();
}

//This will fetch only what is needed (You can customize to get columns what is needed)
public IEnumerable<NewCustomDTO> GetBlogsAndPostCount()
{

   return _dbContext.Blogs.Select(x=> NewCustomDTO
   {
       BlogName = x.BlogName,
       Count = x.Posts.Count(),
   });
}
</code>```

Body:
I am working on a project that is using Repository pattern. We are using Entity Framework to retrieve data from the database. To load related data we use eager loading which means that we have to explicitly include related data.

Say that we want to have all blogs and their related posts we would have to write:

_dbContext.Blogs.Include(b => b.Posts)

The disadvantages with this is that you can only see which related data is loaded in the repository class.

I have tried to shown an example below. Here the problem occurs in the class BlogViewModel.cs because you try to access blogs.Posts, but posts is not included in the original query. So if you are trying to get related data, one would have to check the origin of query and see if it is included.

Repository.cs:

public IEnumerable<BlogDbModel> GetBlogs()
{
    return _dbContext.Blogs.ToList();
}

Service.cs:

public IEnumerable<BlogViewModel> GetBlogs()
{
    return _repository.Select(x => new BlogViewModel(x));
}

BlogViewModel.cs:

public class BlogViewModel
{
    public BlogViewModel(BlogDbModel blogDbModel)
    {
        Name = blogDbModel.Name;
        Posts = blogDbModel.Posts;
    }

    public string Name { get; set; }
    public IEnumerable<Posts> Posts { get; set; }
}

Does anyone have a smart solution to this? Is it possible give an compilation error if you are trying to access data that is not included?

Two options that I have thought about are:

Use lazy-loading instead

Always return an IQueryable from the repository

Thanks

Body:
No you dont have any option to give compilation error on this context. Data either way are loaded in the run-time.

LazyLoading
Assuming your displaying Blogs, Posts, Comments in view, So you need to load everything when the page load.
When you enable lazyload and map properties that not been included in the data layer query it will load related entities

public BlogViewModel(BlogDbModel blogDbModel)
{
  Name = blogDbModel.Name;
  Posts = blogDbModel.Posts;
 }

If you enable lazyload and do this post will be fetched using lazyload feature. What if post contains a reference to User or any other object it will load those too.
When you need everything at first place its not recommended to use lazyload because it will additional round-trip to database.

IQueryable from repository

I would say IQueryable to a viewmodel is leaky abstraction. Ideally your data layer should be performing these. Providing IQuerable<BlogDbModel> to Viewmodel is like developer able to fetch 1Blogs=>Post=>User=>Accounts1 anything related from this.

IMHO I would write data layer methods which are needed for the view.

LazyloadingEnabled = false;

public IEnumerable<BlogDbModel> GetBlogs()
{

    return _dbContext.Blogs.ToList();
}

public IEnumerable<BlogDbModel> GetBlogsAndPosts()
{

  return _dbContext.Blogs.Include("Posts").ToList();
}

//This will fetch only what is needed (You can customize to get columns what is needed)
public IEnumerable<NewCustomDTO> GetBlogsAndPostCount()
{

   return _dbContext.Blogs.Select(x=> NewCustomDTO
   {
       BlogName = x.BlogName,
       Count = x.Posts.Count(),
   });
}


问:
how to unzip file with C# console application, dotnetzip library
i've to unzip the specific file to a specific folder

Im using C# visual studio express 2010 and dotnetzip library to zip

```<code>//take the zip file from sftp
Console.WriteLine("Mendownload File va_txn dari KPFS");
            Console.WriteLine("===================================");
            string remoteDirectory = "/va/";

            using (SftpClient sftp = new SftpClient(host, port, username, password))
            {
                try
                {
                    sftp.Connect();
                    var fileIn = sftp.ListDirectory(remoteDirectory);
                    foreach (var file in fileIn)
                    {
                        if (!file.Name.Equals(".") && !file.Name.Equals("..") && file.LastWriteTime.Date == DateTime.Today)
                        {
                            Console.WriteLine(file.Name);
                            Console.WriteLine("File ditemukan, selesai dikompress");

                            //code to download file
                            using (Stream file1 = File.Create(@"C:\Users\u532246\Desktop\VA\" + file.Name))
                            {
                                sftp.DownloadFile(remoteDirectory + file.Name, file1);
                            }
                        }
                    }
                }
                catch
                {

                }
                sftp.Disconnect();
            }

            //Unzip file
            string pathzip = @"C:\Users\Desktop\VA\va_for_copartner_daily.zip";
            using (ZipFile zip = new ZipFile())
            {
                zip.ExtractAll(pathzip);
            }
</code>```

The problem is , when the unzip file code running, the  unzipped file nowhere found, i dont know what im missing or wrong , maybe someone can help me fix my code ?

答:
You are not actually reading the zip file, you're just extracting an empty archive since you've not given a parameter to the ZipFile constructor.

This should do it:

```<code>//Unzip file
string pathzip = @"C:\Users\Desktop\VA\va_for_copartner_daily.zip";
using (ZipFile zip = new ZipFile.Read(pathzip))
{
    zip.ExtractAll(@"C:\Users\Desktop\VA\SomeOtherFolder");
}
</code>```

Body:
i've to unzip the specific file to a specific folder

Im using C# visual studio express 2010 and dotnetzip library to zip

//take the zip file from sftp
Console.WriteLine("Mendownload File va_txn dari KPFS");
            Console.WriteLine("===================================");
            string remoteDirectory = "/va/";

            using (SftpClient sftp = new SftpClient(host, port, username, password))
            {
                try
                {
                    sftp.Connect();
                    var fileIn = sftp.ListDirectory(remoteDirectory);
                    foreach (var file in fileIn)
                    {
                        if (!file.Name.Equals(".") && !file.Name.Equals("..") && file.LastWriteTime.Date == DateTime.Today)
                        {
                            Console.WriteLine(file.Name);
                            Console.WriteLine("File ditemukan, selesai dikompress");

                            //code to download file
                            using (Stream file1 = File.Create(@"C:\Users\u532246\Desktop\VA\" + file.Name))
                            {
                                sftp.DownloadFile(remoteDirectory + file.Name, file1);
                            }
                        }
                    }
                }
                catch
                {

                }
                sftp.Disconnect();
            }

            //Unzip file
            string pathzip = @"C:\Users\Desktop\VA\va_for_copartner_daily.zip";
            using (ZipFile zip = new ZipFile())
            {
                zip.ExtractAll(pathzip);
            }

The problem is , when the unzip file code running, the  unzipped file nowhere found, i dont know what im missing or wrong , maybe someone can help me fix my code ?

Body:
You are not actually reading the zip file, you're just extracting an empty archive since you've not given a parameter to the ZipFile constructor.

This should do it:

//Unzip file
string pathzip = @"C:\Users\Desktop\VA\va_for_copartner_daily.zip";
using (ZipFile zip = new ZipFile.Read(pathzip))
{
    zip.ExtractAll(@"C:\Users\Desktop\VA\SomeOtherFolder");
}


问:
Divide x into y parts by decreasing amount
If I had $1000(variable) and I want to split that amount up and give it to 20(variable) people, but rather than give it evenly to each person, I want to give more to the 1st person, and the 2nd person, etc.

So the 20th person gets the least, and the 5th person gets the 5th most.

How would I achieve that?

Thanks

Edit:

Formula:

```<code>int people = 20;
float prize = 1000;

float k = (2 * prize) / ((people) * (people - 1));
float sum = 0;

for (int i = 1; i < people; ++i)
{
    var personsPrize = i * k;
    sum += personsPrize;
    Console.WriteLine(personsPrize);
}
Console.WriteLine("sum = " + sum);
</code>```

答:
You owe me a beer, actually a chug of beer!!

Using Gauss distribution (N*(N+1))/2 you cannot have a slight margin over the competitors ranks, prizes have linear increase https://mathbitsnotebook.com/Algebra2/Sequences/SSGauss.html.

What you need is something that increases exponentially or with a fixed ration, I want to solve your problem with a mathematical approach, so I will use a geometric progression https://mathbitsnotebook.com/Algebra2/Sequences/SSGeometric.html

I won't add any other answer after this one, you have to build your own prize pool system!!

For Geometric Distribution formula is:

rankPrize = ((1 - distributionFactor) / (1 - distributionFactor ^
   winners) * distributionFactor ^ (rank - 1)) * prize

where
  distributionFactor - is between 0 and 1

Play around with distribution Factor and chose the correct value for your system, I've chosen 0.8 because the gap between prizes is not that big!

Here we go, fiddle link: https://dotnetfiddle.net/qmJnYd to play around and implementation:

```<code>static void GaussDistributionPricePool()
        {
            Console.WriteLine("________________________________________________________");
            Console.WriteLine("Begin Gauss distribution price pool");

            int totalPeople = 20;
            float prize = 5000;

            List<int> peopleScores = new List<int>();
            Random r = new Random();
            for (int i = 0; i < totalPeople; ++i)
            {
                peopleScores.Add(r.Next(0, 100));
            }

            var totalPeopleWithScore = peopleScores.Where(x => x > 0).Count();

            var groupedScores = peopleScores
                .Where(x => x > 0)
                .ToList()
                .GroupBy(x => x)
                .Select(grp => new
                {
                    score = grp.Key,
                    peopleScores = grp.ToList()
                })
                .OrderBy(g => g.score)
                .ToList();

            var groupCount = groupedScores.Select(x => new { count = x.peopleScores.Count() }).Select(z => z.count).Count();
            // Gauss formula. (N*(N+1))/2
            // https://mathbitsnotebook.com/Algebra2/Sequences/SSGauss.html
            float basePrizeRate = 2 * prize / totalPeopleWithScore / (totalPeopleWithScore + 1);
            Console.WriteLine("Base Price rate: " + basePrizeRate);
            float sum = 0;
            var leaderboardRank = 0;
            var totalWinners = 0;
            foreach (var positionScore in groupedScores)
            {
                var countWinner = positionScore.peopleScores.Count();
                Console.WriteLine();
                Console.WriteLine("On leaderboard rank : " + (groupedScores.Count() - leaderboardRank) + " are " + countWinner + " winners with score: " + positionScore.score);

                float positionPrizePool = 0;
                for (int i = 1; i <= positionScore.peopleScores.Count(); ++i)
                {
                    totalWinners++;
                    positionPrizePool += totalWinners * basePrizeRate;
                }
                Console.WriteLine("Prize Pool " + positionPrizePool);
                var personPoolPrize = positionPrizePool / positionScore.peopleScores.Count();
                foreach (var x in positionScore.peopleScores)
                {
                    Console.WriteLine("Winner " + totalWinners + " won: " + personPoolPrize);
                    sum += personPoolPrize;
                }
                leaderboardRank++;
            }
            Console.WriteLine();

            Console.WriteLine("Total Prize: " + sum);
            Console.WriteLine("Total Winners: " + totalPeopleWithScore);

            Console.WriteLine("End Gauss distribution price pool");
            Console.WriteLine("________________________________________________________");
        }
</code>```

Body:
If I had $1000(variable) and I want to split that amount up and give it to 20(variable) people, but rather than give it evenly to each person, I want to give more to the 1st person, and the 2nd person, etc.

So the 20th person gets the least, and the 5th person gets the 5th most.

How would I achieve that?

Thanks

Edit:

Formula:

int people = 20;
float prize = 1000;

float k = (2 * prize) / ((people) * (people - 1));
float sum = 0;

for (int i = 1; i < people; ++i)
{
    var personsPrize = i * k;
    sum += personsPrize;
    Console.WriteLine(personsPrize);
}
Console.WriteLine("sum = " + sum);

Body:
You owe me a beer, actually a chug of beer!!

Using Gauss distribution (N*(N+1))/2 you cannot have a slight margin over the competitors ranks, prizes have linear increase https://mathbitsnotebook.com/Algebra2/Sequences/SSGauss.html.

What you need is something that increases exponentially or with a fixed ration, I want to solve your problem with a mathematical approach, so I will use a geometric progression https://mathbitsnotebook.com/Algebra2/Sequences/SSGeometric.html

I won't add any other answer after this one, you have to build your own prize pool system!!

For Geometric Distribution formula is:

rankPrize = ((1 - distributionFactor) / (1 - distributionFactor ^
   winners) * distributionFactor ^ (rank - 1)) * prize

where
  distributionFactor - is between 0 and 1

Play around with distribution Factor and chose the correct value for your system, I've chosen 0.8 because the gap between prizes is not that big!

Here we go, fiddle link: https://dotnetfiddle.net/qmJnYd to play around and implementation:

static void GaussDistributionPricePool()
        {
            Console.WriteLine("________________________________________________________");
            Console.WriteLine("Begin Gauss distribution price pool");

            int totalPeople = 20;
            float prize = 5000;

            List<int> peopleScores = new List<int>();
            Random r = new Random();
            for (int i = 0; i < totalPeople; ++i)
            {
                peopleScores.Add(r.Next(0, 100));
            }

            var totalPeopleWithScore = peopleScores.Where(x => x > 0).Count();

            var groupedScores = peopleScores
                .Where(x => x > 0)
                .ToList()
                .GroupBy(x => x)
                .Select(grp => new
                {
                    score = grp.Key,
                    peopleScores = grp.ToList()
                })
                .OrderBy(g => g.score)
                .ToList();

            var groupCount = groupedScores.Select(x => new { count = x.peopleScores.Count() }).Select(z => z.count).Count();
            // Gauss formula. (N*(N+1))/2
            // https://mathbitsnotebook.com/Algebra2/Sequences/SSGauss.html
            float basePrizeRate = 2 * prize / totalPeopleWithScore / (totalPeopleWithScore + 1);
            Console.WriteLine("Base Price rate: " + basePrizeRate);
            float sum = 0;
            var leaderboardRank = 0;
            var totalWinners = 0;
            foreach (var positionScore in groupedScores)
            {
                var countWinner = positionScore.peopleScores.Count();
                Console.WriteLine();
                Console.WriteLine("On leaderboard rank : " + (groupedScores.Count() - leaderboardRank) + " are " + countWinner + " winners with score: " + positionScore.score);

                float positionPrizePool = 0;
                for (int i = 1; i <= positionScore.peopleScores.Count(); ++i)
                {
                    totalWinners++;
                    positionPrizePool += totalWinners * basePrizeRate;
                }
                Console.WriteLine("Prize Pool " + positionPrizePool);
                var personPoolPrize = positionPrizePool / positionScore.peopleScores.Count();
                foreach (var x in positionScore.peopleScores)
                {
                    Console.WriteLine("Winner " + totalWinners + " won: " + personPoolPrize);
                    sum += personPoolPrize;
                }
                leaderboardRank++;
            }
            Console.WriteLine();

            Console.WriteLine("Total Prize: " + sum);
            Console.WriteLine("Total Winners: " + totalPeopleWithScore);

            Console.WriteLine("End Gauss distribution price pool");
            Console.WriteLine("________________________________________________________");
        }


问:
Laravel 5.8 Won’t Connect to Non-Local Database
I am having an issue where a new Laravel Project (5.8) will not connect to a non-local database. I continue getting an “Access Denied for User...” error. I know that the configuration is correct because I have another project running in 5.6 connecting to the same database with the same configuration and it works. It appears that once I use a hostname other than “localhost”, it breaks. It was working locally until I attempted to connect to another non-local database.

I believe Laravel is not accepting the hostname correctly. I have recached everything as well, with no luck. The access denied error always shows the same local hostname of the machine the project is on, never the remote hostname in the env, so I assume it is trying to connect to that. Any ideas on how to fix this issue? I am stumped with no idea where to go.

Thanks in advance!

EDIT:
I know for sure there is not a configuration error, IP access error, or caching error as I have already troubleshooted all of these possible issues (it sounds like one of these issues). My env and the error are below (anything starting with "my" is the correct information that I have changed for security):

DB_CONNECTION=mysql
DB_HOST=mysql.myURL.com
DB_PORT=3306
DB_DATABASE=myDbName
DB_USERNAME=myDbUsername
DB_PASSWORD=myDbPassword
```

<pre class="lang-sql prettyprint-override"><code>SQLSTATE[HY000] [1045] Access denied for user 'myDbUsername'@'NOTmysql.myURL.com' (using password: YES) (SQL: select count(*) as aggregate from `myTable`)
</code>```

NOTmysql.myURL.com in the error actually happens to be the local hostname of the server that the website is running on, but myDbUsername is the username I set in the configuration.

答:
@IanCowan do try to connect with simple php connect script. Verify does this working for you on the same repository... just placed that php file in /public folder.

And open/browse url to that file. Don't forgot to change the config.

This is just to ensure... there is no issue at connection end.

```<code><?php
    $servername = "localhost";
    $username = "username";
    $password = "password";

    try {
        $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
        // set the PDO error mode to exception
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        echo "Connected successfully";
        }
    catch(PDOException $e)
        {
        echo "Connection failed: " . $e->getMessage();
        }
    ?>
</code>```

Body:
I am having an issue where a new Laravel Project (5.8) will not connect to a non-local database. I continue getting an “Access Denied for User...” error. I know that the configuration is correct because I have another project running in 5.6 connecting to the same database with the same configuration and it works. It appears that once I use a hostname other than “localhost”, it breaks. It was working locally until I attempted to connect to another non-local database.

I believe Laravel is not accepting the hostname correctly. I have recached everything as well, with no luck. The access denied error always shows the same local hostname of the machine the project is on, never the remote hostname in the env, so I assume it is trying to connect to that. Any ideas on how to fix this issue? I am stumped with no idea where to go.

Thanks in advance!

EDIT:
I know for sure there is not a configuration error, IP access error, or caching error as I have already troubleshooted all of these possible issues (it sounds like one of these issues). My env and the error are below (anything starting with "my" is the correct information that I have changed for security):

DB_CONNECTION=mysql
DB_HOST=mysql.myURL.com
DB_PORT=3306
DB_DATABASE=myDbName
DB_USERNAME=myDbUsername
DB_PASSWORD=myDbPassword

SQLSTATE[HY000] [1045] Access denied for user 'myDbUsername'@'NOTmysql.myURL.com' (using password: YES) (SQL: select count(*) as aggregate from `myTable`)

NOTmysql.myURL.com in the error actually happens to be the local hostname of the server that the website is running on, but myDbUsername is the username I set in the configuration.

Body:
@IanCowan do try to connect with simple php connect script. Verify does this working for you on the same repository... just placed that php file in /public folder.

And open/browse url to that file. Don't forgot to change the config.

This is just to ensure... there is no issue at connection end.

<?php
    $servername = "localhost";
    $username = "username";
    $password = "password";

    try {
        $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
        // set the PDO error mode to exception
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        echo "Connected successfully";
        }
    catch(PDOException $e)
        {
        echo "Connection failed: " . $e->getMessage();
        }
    ?>


问:
MVP in windows forms
I want to implement MVPO pattern in my windows forms application. As you know there is 1:1 means there is one presenter for one view.

So basicly we can have:

```<code>public class MainPresenter
{
       IMainView _mainView;
       public MainPresenter(IMainView mainView)
       {
             _myView = myView;
       }
}
</code>```

My question is can one presenter use other presenter so for instance:

```<code>public class MainPresenter
{
       IMainView _mainView;
       ISomeOtherPresenter _otherPresenter;
       public MainPresenter(IMainView mainView, IOtherPresenter otherPresenter)
       {
             _mainView = myView;
             _otherPresenter = otherPresenter;
       }
}
</code>```

As a reference i went through video tutorial by Robert Marquez. At his 10 video serie at 10th one he used one rpesenter inside other one

Reference link

at 35:39 you will see his MainPresenter has dependency to IHelpAboutPresenter.

To me it's logical because if HelpAboutView (form) can be opened by button from MainView it's logical MainPresenter has to have access to HelpAboutPresenter which was presented on the video. If not that way how to do so because all the people saying 1:1 and here we have 1 presenter uses other presenter.

答:
I would assert that there isn't anything inherently wrong with the approach although one could probably go about it another way.

The "main" view could be acting more along the lines of a front controller.  The pattern is more often associated with web-applications although it may still be applicable to desktop applications.  For instance, the main MDI view may be the front controller.

Typically a front controller would have some dispatching mechanism to have individual requests (such as menu clicks in a desktop application, or url-based resources in a web-based application) handled by a specific request handler.  There is therefore a slight indirection that decouples the front controller from the specific implementation.

In the case of the linked video the relationship is just a bit more coupled in that the About box request (if I understand correctly) is being handled not by a specific request handler but by the front controller.

What makes this appear odd is the fact that the front controller is implemented using the MVP pattern.

Title: MVP in windows forms

Body:
I want to implement MVPO pattern in my windows forms application. As you know there is 1:1 means there is one presenter for one view.

So basicly we can have:

public class MainPresenter
{
       IMainView _mainView;
       public MainPresenter(IMainView mainView)
       {
             _myView = myView;
       }
}

My question is can one presenter use other presenter so for instance:

public class MainPresenter
{
       IMainView _mainView;
       ISomeOtherPresenter _otherPresenter;
       public MainPresenter(IMainView mainView, IOtherPresenter otherPresenter)
       {
             _mainView = myView;
             _otherPresenter = otherPresenter;
       }
}

As a reference i went through video tutorial by Robert Marquez. At his 10 video serie at 10th one he used one rpesenter inside other one

Reference link

at 35:39 you will see his MainPresenter has dependency to IHelpAboutPresenter.

To me it's logical because if HelpAboutView (form) can be opened by button from MainView it's logical MainPresenter has to have access to HelpAboutPresenter which was presented on the video. If not that way how to do so because all the people saying 1:1 and here we have 1 presenter uses other presenter.


问:
Typescript error messages for javascript file
I only have a minified version of the javascript code below. It works as is but I needed to integrate this code inside of a typescript file. It still works pretty well at runtime but in my editor (Visual Studio Code) I got errors.

Below is the code.

```<code>!function(e){"use strict";function i(i,a){var s=i.outerWidth(!0),o={};if(!i.is(":visible")&&!n){switch(n=!0,i.addClass("ps-active-panel").css({position:"fixed",top:0,height:"100%","z-index":9999999999}),i.data(a),e("html").addClass("overflow-hidden"),e("body").addClass("overflow-hidden"),e("#eskimo-overlay").bind("touchmove",!1),e("#eskimo-overlay").fadeIn(200),a.side){case"left":i.css({left:"-"+s+"px",right:"auto"}),o.left="+="+s;break;case"right":i.css({left:"auto",right:"-"+s+"px"}),o.right="+="+s}t.animate({},a.duration),i.show().animate(o,a.duration,function(){n=!1,"function"==typeof a.onOpen&&a.onOpen()})}}var t=e("body"),n=!1;e.panelslider=function(t,n){var a=e(".ps-active-panel");n=e.extend({},{side:"left",duration:200,clickClose:!0,onOpen:null},n),a.is(":visible")&&a[0]!=t[0]?e.panelslider.close(function(){i(t,n)}):a.length&&!a.is(":hidden")||i(t,n)},e.panelslider.close=function(i){var a=e(".ps-active-panel"),s=a.data("duration"),o=a.outerWidth(!0),l={};if(a.length&&!a.is(":hidden")&&!n){switch(n=!0,a.data("side")){case"left":l.left="-="+o;break;case"right":l.right="-="+o}a.animate(l,s),t.animate({},s,function(){a.fadeOut(200),a.removeClass("ps-active-panel"),e("html").removeClass("overflow-hidden"),e("body").removeClass("overflow-hidden"),e("#eskimo-overlay").fadeOut(200),n=!1,i&&i()})}},e(document).bind("click keyup",function(i){var t=e(".ps-active-panel");"keyup"==i.type&&27!=i.keyCode||t.is(":visible")&&t.data("clickClose")&&e.panelslider.close()}),e(document).on("click",".ps-active-panel",function(e){e.stopPropagation()}),e.fn.panelslider=function(i){return this.on("click",function(t){var n=e(".ps-active-panel"),a=e(this.getAttribute("href"));n.is(":visible")&&a[0]==n[0]?e.panelslider.close():e.panelslider(a,i),t.preventDefault(),t.stopPropagation()}),this}}(jQuery);
jQuery(document).ready(function(){jQuery("body").find(".eskimo-panel-open").panelslider({side:"right",clickClose:!0,duration:400}),jQuery("body").find(".eskimo-panel-close").on("click",function(){return jQuery.panelslider.close(),!1})});
</code>```

What can be done on this code to avoid TypeScript errors in my editor ?

EDIT

For this moment, I copy/paste minified javascript code inside another TypeScript file (wrap it in panel function) and it works at runtime but got errors in my editor.

答:
If it is a minified js you can simply ignore/exclude that file in tsconfig.

tsconfig documentation link

Body:
I only have a minified version of the javascript code below. It works as is but I needed to integrate this code inside of a typescript file. It still works pretty well at runtime but in my editor (Visual Studio Code) I got errors.

Below is the code.

!function(e){"use strict";function i(i,a){var s=i.outerWidth(!0),o={};if(!i.is(":visible")&&!n){switch(n=!0,i.addClass("ps-active-panel").css({position:"fixed",top:0,height:"100%","z-index":9999999999}),i.data(a),e("html").addClass("overflow-hidden"),e("body").addClass("overflow-hidden"),e("#eskimo-overlay").bind("touchmove",!1),e("#eskimo-overlay").fadeIn(200),a.side){case"left":i.css({left:"-"+s+"px",right:"auto"}),o.left="+="+s;break;case"right":i.css({left:"auto",right:"-"+s+"px"}),o.right="+="+s}t.animate({},a.duration),i.show().animate(o,a.duration,function(){n=!1,"function"==typeof a.onOpen&&a.onOpen()})}}var t=e("body"),n=!1;e.panelslider=function(t,n){var a=e(".ps-active-panel");n=e.extend({},{side:"left",duration:200,clickClose:!0,onOpen:null},n),a.is(":visible")&&a[0]!=t[0]?e.panelslider.close(function(){i(t,n)}):a.length&&!a.is(":hidden")||i(t,n)},e.panelslider.close=function(i){var a=e(".ps-active-panel"),s=a.data("duration"),o=a.outerWidth(!0),l={};if(a.length&&!a.is(":hidden")&&!n){switch(n=!0,a.data("side")){case"left":l.left="-="+o;break;case"right":l.right="-="+o}a.animate(l,s),t.animate({},s,function(){a.fadeOut(200),a.removeClass("ps-active-panel"),e("html").removeClass("overflow-hidden"),e("body").removeClass("overflow-hidden"),e("#eskimo-overlay").fadeOut(200),n=!1,i&&i()})}},e(document).bind("click keyup",function(i){var t=e(".ps-active-panel");"keyup"==i.type&&27!=i.keyCode||t.is(":visible")&&t.data("clickClose")&&e.panelslider.close()}),e(document).on("click",".ps-active-panel",function(e){e.stopPropagation()}),e.fn.panelslider=function(i){return this.on("click",function(t){var n=e(".ps-active-panel"),a=e(this.getAttribute("href"));n.is(":visible")&&a[0]==n[0]?e.panelslider.close():e.panelslider(a,i),t.preventDefault(),t.stopPropagation()}),this}}(jQuery);
jQuery(document).ready(function(){jQuery("body").find(".eskimo-panel-open").panelslider({side:"right",clickClose:!0,duration:400}),jQuery("body").find(".eskimo-panel-close").on("click",function(){return jQuery.panelslider.close(),!1})});

What can be done on this code to avoid TypeScript errors in my editor ?

EDIT

For this moment, I copy/paste minified javascript code inside another TypeScript file (wrap it in panel function) and it works at runtime but got errors in my editor.


问:
How do I access DispatcherServlet with MockMvc?
I have a basic SpringMVC Application which is running (and mapping) fine.
Now I wanted to set up my UnitTests with MockMvc to perform get requests and stuff.
But if I run the test there is an AssertionError "Status expected: <200> but was: <404>" and my console gives warning "No mapping found for HTTP request with URI [/] in DispatcherServlet with name ''".
I get the feeling my MockMvc cant communicate with my DispatcherServlet, so how do I define this connection?

Here is my short test class:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration
public class HomeControllerTest {

  private MockMvc mvc;
  @Autowired
  private WebApplicationContext wac;

  @Before
  public void setup() throws ServletException {
    mvc = MockMvcBuilders.webAppContextSetup(wac).build();
  }

  @Test
  public void testLandingPagePath() throws Exception {
    mvc.perform(get("/")).andExpect(status().isOk());
  }
}
</code>```

So I expected MockMvc to get the location of my DispatcherServlet by default. But it actually doesn't call it for mapping.

I have my "web.xml" and "dispatcher-servlet.xml" located in "WEB-INF" folder and no extra configuration defined.

I got the feeling the problem is based on my project structure, but this is a basic eclipse "Dynamic Web Application", the tests are located in "src/test/java", parallel to "src/main/java".

I appreciate any help, since I spend last 2 hours on reading for solutions but not getting the trick.

答:
After some more time I got things right now:
There is still no way for me to access the dispatcher-servlet.xml in WEB-INF folder. I added a new "config" package to my test-package in parallel to my "controller" test package and put a copy of the dispatcher-servlet.xml in there, called "test-dispatcher-servlet.xml".

Now my test class is able to access this with

```<code>@ContextConfiguration("../config/test-dispatcher-servlet.xml")
public class HomeControllerTest {
</code>```

Hope this can help others who start with spring mvc testing :-)

Body:
I have a basic SpringMVC Application which is running (and mapping) fine.
Now I wanted to set up my UnitTests with MockMvc to perform get requests and stuff.
But if I run the test there is an AssertionError "Status expected: <200> but was: <404>" and my console gives warning "No mapping found for HTTP request with URI [/] in DispatcherServlet with name ''".
I get the feeling my MockMvc cant communicate with my DispatcherServlet, so how do I define this connection?

Here is my short test class:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration
public class HomeControllerTest {

  private MockMvc mvc;
  @Autowired
  private WebApplicationContext wac;

  @Before
  public void setup() throws ServletException {
    mvc = MockMvcBuilders.webAppContextSetup(wac).build();
  }

  @Test
  public void testLandingPagePath() throws Exception {
    mvc.perform(get("/")).andExpect(status().isOk());
  }
}

So I expected MockMvc to get the location of my DispatcherServlet by default. But it actually doesn't call it for mapping.

I have my "web.xml" and "dispatcher-servlet.xml" located in "WEB-INF" folder and no extra configuration defined.

I got the feeling the problem is based on my project structure, but this is a basic eclipse "Dynamic Web Application", the tests are located in "src/test/java", parallel to "src/main/java".

I appreciate any help, since I spend last 2 hours on reading for solutions but not getting the trick.

Body:
After some more time I got things right now:
There is still no way for me to access the dispatcher-servlet.xml in WEB-INF folder. I added a new "config" package to my test-package in parallel to my "controller" test package and put a copy of the dispatcher-servlet.xml in there, called "test-dispatcher-servlet.xml".

Now my test class is able to access this with

@ContextConfiguration("../config/test-dispatcher-servlet.xml")
public class HomeControllerTest {

Hope this can help others who start with spring mvc testing :-)


问:
What is the way to allow 2 URL ReWrites in IIS 10 that are similar?
We've had this old rule for years which takes a URL Parameter, parses value server side and renders a final page:

```<code>            <rule name="RewriteUserFriendlyURL1" stopProcessing="true">
                <match url="^([^/]+)/?$" />
                <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                </conditions>
                <action type="Rewrite" url="cities.php?id={R:1}" />
            </rule>
</code>```

Now we have a new condition where we want to do something similar but the results and processed URL Parameter need to work differently.

```<code>           <rule name="RewriteUserFriendlyURL2" stopProcessing="true">
                <match url="^([^/]+)/?$" />
                <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                </conditions>
                <action type="Rewrite" url="detail-page-friendly.php?name={R:1}" />
            </rule>
</code>```

The first rule takes the parameter and renders a page using that parameter as a variable.
The second rule takes the parameter and creates a result based on a database record.
Each uses a different PHP page to create the final page.

Because we are virtually doing the same thing in each case there is a need to figure out how to separate the two rules.

I've considered two different triggers such as making the second rule linked directly such as /pageName.php?name=something
Which then rewrites to /something
And set this rule first with a "stopProcessing="true" " so as to not move to the older rule which is looking for just a word (Parameter) without a page name.
Link from the second case would be /cityName

The thought is that in one case we look for the page name (pageName.php) and then stop looking at further rules.
IF that condition is not met we expect the second rule to do its job as it has in the past.

Is this possible ( good logic ) or should I consider some other method?

答:
According to your description, I suggest you could try to use url rewrite condition to achieve your requirement.

If you want to rewrite the url according to different query string, I suggest you could use {querystring} parameter to in your url rewrite rule.

More details, you could refer to below url rewrite rule:

```<code>        <rule name="RewriteUserFriendlyURL1" stopProcessing="true">
            <match url="^([^/]+)/?$" />
            <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                <add input="{QUERY_STRING}" pattern="name=first" />
            </conditions>
            <action type="Rewrite" url="cities.php?id={R:1}" />
        </rule>
       <rule name="RewriteUserFriendlyURL2" stopProcessing="true">
            <match url="^([^/]+)/?$" />
            <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
             <add input="{QUERY_STRING}" pattern="name=second" />
            </conditions>
            <action type="Rewrite" url="detail-page-friendly.php?name={R:1}" />
        </rule>
</code>```

Body:
We've had this old rule for years which takes a URL Parameter, parses value server side and renders a final page:

            <rule name="RewriteUserFriendlyURL1" stopProcessing="true">
                <match url="^([^/]+)/?$" />
                <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                </conditions>
                <action type="Rewrite" url="cities.php?id={R:1}" />
            </rule>

Now we have a new condition where we want to do something similar but the results and processed URL Parameter need to work differently.

           <rule name="RewriteUserFriendlyURL2" stopProcessing="true">
                <match url="^([^/]+)/?$" />
                <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                </conditions>
                <action type="Rewrite" url="detail-page-friendly.php?name={R:1}" />
            </rule>

The first rule takes the parameter and renders a page using that parameter as a variable.
The second rule takes the parameter and creates a result based on a database record.
Each uses a different PHP page to create the final page.

Because we are virtually doing the same thing in each case there is a need to figure out how to separate the two rules.

I've considered two different triggers such as making the second rule linked directly such as /pageName.php?name=something
Which then rewrites to /something
And set this rule first with a "stopProcessing="true" " so as to not move to the older rule which is looking for just a word (Parameter) without a page name.
Link from the second case would be /cityName

The thought is that in one case we look for the page name (pageName.php) and then stop looking at further rules.
IF that condition is not met we expect the second rule to do its job as it has in the past.

Is this possible ( good logic ) or should I consider some other method?

Body:
According to your description, I suggest you could try to use url rewrite condition to achieve your requirement.

If you want to rewrite the url according to different query string, I suggest you could use {querystring} parameter to in your url rewrite rule.

More details, you could refer to below url rewrite rule:

        <rule name="RewriteUserFriendlyURL1" stopProcessing="true">
            <match url="^([^/]+)/?$" />
            <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                <add input="{QUERY_STRING}" pattern="name=first" />
            </conditions>
            <action type="Rewrite" url="cities.php?id={R:1}" />
        </rule>
       <rule name="RewriteUserFriendlyURL2" stopProcessing="true">
            <match url="^([^/]+)/?$" />
            <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
             <add input="{QUERY_STRING}" pattern="name=second" />
            </conditions>
            <action type="Rewrite" url="detail-page-friendly.php?name={R:1}" />
        </rule>


问:
How to Convince management to upgrade to .Net 4.0
We developed an application using .net 2.0.
We license our software which means whenever we release a new version, we have to push out the change to all our existing clients.

No one in my group has the slightest motivation to upgrade to a newer version of .net. They simple see it as more work for our support team to deploy and argue that clients will be resistant to any change.

Can anyone point me in the direction of some argument i could present to Non programmers that might sway them.

If noting else, some argument that it is safe, and will not cause our clients any harm who already have the .net 2.0 framework on their machines?

I figure it's hopeless. I'm gonna be stuck using the .net 2.0 framework until for another 4 or 5 years i bet... perhaps longer :( help!

I really want to be able to use WCF, LINQ, WPF (possible), and the option to use the Entity Framework 4.0.!

thanks

jonathan

答:
If you really want to push this change I would simply approach it in another way.  If you are currently using Visual Studio 2010 or Visual Studio 2008 you can target the project for a specfic platform.

In a future planned update suggest the target version of the framework be changed.  Modify your requirements to require 3.5 and/or 4.0 and release the upgrade.  Everything will work exactly the same, you can also easily include the .NET Framework installer itself, depending on how you release updates.

Once you get the software to a newer version you can start to work on proposed changes.  Of course your reasons are still not valid.  You won't be able to use WPF for instance based on the fact it sounds like a WinForms application.  Unless you have a need for Linq I am not sure the reason you want to use it.

Of course you could also do your proposed changes on the side I suppose, entirely depends on how you are assigned work, might involve doing it after your 8 hours each day or on the weekends.


问:
How to automatically scan the re-uploaded files with some modification in the wildfly-10 without the server restart?
I am using wildfly-10 server. I am providing an option to Upload images or jsp files for the user in the UI and the user can make use of these files in the other section of the application later.
At any one point of time I am allowing only one entry with a particular name. If the user tries to upload file with a name that is already existing then I am trying to overwrite the existing one with the new file.

In this scenario I am facing the below problem:

I have uploaded a image with the name image1.png.
    Now if I change some other image's name to image1.png and upload it, the new image is not visible until I restart the server.

Looks like the older image has been cached by the server and it is still referring to the cache location. When I restart the server then it refreshes the cache with the new content of the file.

Is there any way that I can immediately see the changes in the UI whenever I re-upload the modified file?
I am using a custom folder to store the uploaded files in my server.
Is there way that I can enable deployment directory scan for this particular directory only?

答:
You don't have to restart the server, a redeploy of the application should work.

You can define another deployment scanner or the directory scanned by the scanner: http://wildscribe.github.io/WildFly/16.0/subsystem/deployment-scanner/scanner/index.html

Another solution would be to create overlays http://wildscribe.github.io/WildFly/16.0/deployment-overlay/index.html .

Thirdly with exploded deployments WildFly already provide the functionality you have developed: https://wildfly.org/news/2017/09/08/Exploded-deployments/ (note that all jboss-cli operations can be called using HTTP rest API)


问:
Put time limit on Jest test?
I'm running a set of tests with Jest to demonstrate Big O using two different methods for Fibonacci.

```<code>const fastFib = require('./../fastFib');
const slowFib = require('./../slowFib');

test('Fast way of getting Fibonacci of 44', () => {
  expect(fastFib(44)).toBe(701408733);
});

test('Slow way of getting Fibonacci of 44', () => {
  expect(slowFib(44)).toBe(701408733);
});
</code>```

I'm wondering if there is a way to specify the maximum length of a test? I saw you can pass a third variable for an async timeout but it doesn't seem to have any effect on normal functions:

```<code>test('Slow way of getting Fibonacci of 44', () => {
  expect(slowFib(44)).toBe(701408733);
}, 5000);
</code>```

Is there a way I can specify the maximum execution time for a function with Jest?

I will share slowFib.js for reference:

```<code>function fib(n) {
  return (n<=1) ? n : fib(n - 1) + fib(n - 2);
}

module.exports = fib;
</code>```

答:
so your test pauses because of sync execution - there is no way to interrupt that by timeout. You need to "split execution". Next version fails to me:

```<code>test('Slow way of getting Fibonacci of 44', (done) => {
  expect(slowFib(44)).toBe(701408733);
  setTimeout(done, 10); // smallest timeout possible to make different macrotask
}, 5000);
</code>```

PS I also believe this should be achievable by marking test async but have not yet figured how exactly.

[UPD] you actually may achieve your goal without using test's timeout:

```<code>test('Slow way of getting Fibonacci of 44', () => {
  const start = new Date();
  expect(slowFib(44)).toBe(701408733);
  expect(new Date() - start).toBeLessThan(5000);
});
</code>```

Title: Put time limit on Jest test?

Body:
I'm running a set of tests with Jest to demonstrate Big O using two different methods for Fibonacci.

const fastFib = require('./../fastFib');
const slowFib = require('./../slowFib');

test('Fast way of getting Fibonacci of 44', () => {
  expect(fastFib(44)).toBe(701408733);
});

test('Slow way of getting Fibonacci of 44', () => {
  expect(slowFib(44)).toBe(701408733);
});

I'm wondering if there is a way to specify the maximum length of a test? I saw you can pass a third variable for an async timeout but it doesn't seem to have any effect on normal functions:

test('Slow way of getting Fibonacci of 44', () => {
  expect(slowFib(44)).toBe(701408733);
}, 5000);

Is there a way I can specify the maximum execution time for a function with Jest?

I will share slowFib.js for reference:

function fib(n) {
  return (n<=1) ? n : fib(n - 1) + fib(n - 2);
}

module.exports = fib;

Body:
so your test pauses because of sync execution - there is no way to interrupt that by timeout. You need to "split execution". Next version fails to me:

test('Slow way of getting Fibonacci of 44', (done) => {
  expect(slowFib(44)).toBe(701408733);
  setTimeout(done, 10); // smallest timeout possible to make different macrotask
}, 5000);

PS I also believe this should be achievable by marking test async but have not yet figured how exactly.

[UPD] you actually may achieve your goal without using test's timeout:

test('Slow way of getting Fibonacci of 44', () => {
  const start = new Date();
  expect(slowFib(44)).toBe(701408733);
  expect(new Date() - start).toBeLessThan(5000);
});


问:
Find the most popular element in int[] array
```<code>int[] a = new int[10]{1,2,3,4,5,6,7,7,7,7};
</code>```

how can I write a method and return 7?

I want to keep it native without the help of lists, maps or other helpers.
Only arrays[].

答:
```<code>import java.util.HashMap;
import java.util.Map;
import java.lang.Integer;
import java.util.Iterator;
public class FindMood {
    public static void main(String [] args){
    int arrayToCheckFrom [] = {1,2,4,4,5,5,5,3,3,3,3,3,3,3,3};
    Map map = new HashMap<Integer, Integer>();
    for(int i = 0 ; i < arrayToCheckFrom.length; i++){
    int sum = 0;
      for(int k = 0 ; k < arrayToCheckFrom.length ; k++){
          if(arrayToCheckFrom[i]==arrayToCheckFrom[k])
          sum += 1;
      }
      map.put(arrayToCheckFrom[i], sum);
    }
    System.out.println(getMaxValue(map));
}
  public static Integer getMaxValue( Map<Integer,Integer> map){
        Map.Entry<Integer,Integer> maxEntry = null;
        Iterator iterator = map.entrySet().iterator();
        while(iterator.hasNext()){
            Map.Entry<Integer,Integer> pair = (Map.Entry<Integer,Integer>) iterator.next();
            if(maxEntry == null || pair.getValue().compareTo(maxEntry.getValue())>0){
                maxEntry = pair;
            }
        }
        return maxEntry.getKey();
    }
}
</code>```

Body:
int[] a = new int[10]{1,2,3,4,5,6,7,7,7,7};

how can I write a method and return 7?

I want to keep it native without the help of lists, maps or other helpers.
Only arrays[].


问:
How to detect a link click with JavaScript/jQuery in a iFrame?
How can I detect a link click inside a iFrame?

The Frame source changes a lot of times and I need to detect all link click inside the iFrame.

I try that already: Javascript - click link in iframe

JS:

```<code>$("#Source a").click();
</code>```

HTML:

```<code><iframe src="" name="Source" id="Source" scrolling="" frameborder="0" title="Anzeigebereich"></iframe>
</code>```

答:
use post message, for communicaton between frames, also support different domains

post message doc

Body:
How can I detect a link click inside a iFrame?

The Frame source changes a lot of times and I need to detect all link click inside the iFrame.

I try that already: Javascript - click link in iframe

JS:

$("#Source a").click();

HTML:


问:
PyAudio failed to install on Windows 10
When I am trying to install PyAudio using

pip install pyaudio
```
<p>I get this error:</p>
<pre class="lang-none prettyprint-override"><code>C:\Users\pankajkaun>pip install pyaudio
Collecting pyaudio
  Using cached https://files.pythonhosted.org/packages/ab/42/b4f04721c5c5bfc196ce156b3c768998ef8c0ae3654ed29ea5020c749a6b/PyAudio-0.2.11.tar.gz
Installing collected packages: pyaudio
  Running setup.py install for pyaudio ... error
    Complete output from command c:\users\pankajkaun\desktop\python\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\PANKAJ~1\\AppData\\Local\\Temp\\pip-install-pw8_ueh5\\pyaudio
\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\PANKAJ~1\AppData\Local\Temp
\pip-record-eru_9orv\install-record.txt --single-version-externally-managed --compile:
    running install
    running build
    running build_py
    creating build
    creating build\lib.win-amd64-3.7
    copying src\pyaudio.py -> build\lib.win-amd64-3.7
    running build_ext
    building '_portaudio' extension
    creating build\temp.win-amd64-3.7
    creating build\temp.win-amd64-3.7\Release
    creating build\temp.win-amd64-3.7\Release\src
    C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.16.27023\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -DMS_WIN64=1 -Ic:\users\pankajkaun\desktop\python\include -Ic:\users\pankajkaun\desktop\python\
include "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.16.27023\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt" "-
IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\winrt" "-IC:
\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\cppwinrt" /Tcsrc/_portaudiomodule.c /Fobuild\temp.win-amd64-3.7\Release\src/_portaudiomodule.obj
    _portaudiomodule.c
    c:\users\pankajkaun\desktop\python\include\pyconfig.h(117): warning C4005: 'MS_WIN64': macro redefinition
    src/_portaudiomodule.c: note: see previous definition of 'MS_WIN64'
    src/_portaudiomodule.c(29): fatal error C1083: Cannot open include file: 'portaudio.h': No such file or directory
    error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\BuildTools\\VC\\Tools\\MSVC\\14.16.27023\\bin\\HostX86\\x64\\cl.exe' failed with exit status 2

    ----------------------------------------
Command "c:\users\pankajkaun\desktop\python\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\PANKAJ~1\\AppData\\Local\\Temp\\pip-install-pw8_ueh5\\pyaudio
\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record
C:\Users\PANKAJ~1\AppData\Local\Temp\pip-record-eru_9orv\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\PANKAJ~1\AppData\Local\Temp\pip-install-pw8_ueh5\pyaudio\
</code>```

Any idea what's going on in here?

答:
Try this (in admin mode command prompt):

```<code>pip install pipwin
pipwin install pyaudio
</code>```

pipwin is like pip, but it installs precompiled Windows binaries provided by Christoph Gohlke. Saves you a lot of googling and manual downloading.

Title: PyAudio failed to install on Windows 10

Body:
When I am trying to install PyAudio using

pip install pyaudio

I get this error:

C:\Users\pankajkaun>pip install pyaudio
Collecting pyaudio
  Using cached https://files.pythonhosted.org/packages/ab/42/b4f04721c5c5bfc196ce156b3c768998ef8c0ae3654ed29ea5020c749a6b/PyAudio-0.2.11.tar.gz
Installing collected packages: pyaudio
  Running setup.py install for pyaudio ... error
    Complete output from command c:\users\pankajkaun\desktop\python\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\PANKAJ~1\\AppData\\Local\\Temp\\pip-install-pw8_ueh5\\pyaudio
\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\PANKAJ~1\AppData\Local\Temp
\pip-record-eru_9orv\install-record.txt --single-version-externally-managed --compile:
    running install
    running build
    running build_py
    creating build
    creating build\lib.win-amd64-3.7
    copying src\pyaudio.py -> build\lib.win-amd64-3.7
    running build_ext
    building '_portaudio' extension
    creating build\temp.win-amd64-3.7
    creating build\temp.win-amd64-3.7\Release
    creating build\temp.win-amd64-3.7\Release\src
    C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.16.27023\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -DMS_WIN64=1 -Ic:\users\pankajkaun\desktop\python\include -Ic:\users\pankajkaun\desktop\python\
include "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.16.27023\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt" "-
IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\winrt" "-IC:
\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\cppwinrt" /Tcsrc/_portaudiomodule.c /Fobuild\temp.win-amd64-3.7\Release\src/_portaudiomodule.obj
    _portaudiomodule.c
    c:\users\pankajkaun\desktop\python\include\pyconfig.h(117): warning C4005: 'MS_WIN64': macro redefinition
    src/_portaudiomodule.c: note: see previous definition of 'MS_WIN64'
    src/_portaudiomodule.c(29): fatal error C1083: Cannot open include file: 'portaudio.h': No such file or directory
    error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\BuildTools\\VC\\Tools\\MSVC\\14.16.27023\\bin\\HostX86\\x64\\cl.exe' failed with exit status 2

    ----------------------------------------
Command "c:\users\pankajkaun\desktop\python\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\PANKAJ~1\\AppData\\Local\\Temp\\pip-install-pw8_ueh5\\pyaudio
\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record
C:\Users\PANKAJ~1\AppData\Local\Temp\pip-record-eru_9orv\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\PANKAJ~1\AppData\Local\Temp\pip-install-pw8_ueh5\pyaudio\

Any idea what's going on in here?

Body:
Try this (in admin mode command prompt):

pip install pipwin
pipwin install pyaudio

pipwin is like pip, but it installs precompiled Windows binaries provided by Christoph Gohlke. Saves you a lot of googling and manual downloading.


问:
In place reinitialization of objects
I'm working on an embedded system, where memory is scarce, and more importantly, since there's a soft realtime constraint (i.e. it's a bug if we don't make the deadline, but no one dies), I cannot use dynamic memory allocation.

However, there's the occasional need to re-initialize a subsystem, and there's been a number of bugs related to not-quite-everything getting either cleaned up or reset correctly. This is of course exactly the problem that constructors and destructors are supposed to solve, but since we don't allocate dynamically, we can't use the idiom where we'd destruct the object and then allocate a new one from scratch (mostly the objects of relevance here are globals).

So in the end there's usually setup code in a constructor, and a reinitialize -type function, which resemble each other but are not identical, since the reinitialize function also does a lot of what a destructor would do.

One way out that I'm thinking of is to write a "renew" -template (this is just a draft, may contain erors and possibly not complet):

```<code>template<typename T, typename .. Args>
void renew(T & obj, Args&&... args) {
  obj.~T();
  new(&obj) T(std::forward<Args>(args)...);
}
</code>```

which could be used to reinitialize non-dynamically alloctated variables. So for example

```<code>A a{17};
... //Do something with a
renew(a, 14);
...//work with the new a, no need to reallocate memory
</code>```

This would allow getting some of the advantages of constructors and destructors (primarily single way to initialize and deinitialize an object) without dynamic memory allocation. Note that the usage above is simplified, in practice this would mostly be used in very specific points in the main loop and on global objects representing the actual physical subsystems.

Question: is this a sensible way of going about it? Or is there a better alternative?

There's a very similar question here Calling a constructor to re-initialize object. I'm asking much the same thing but specifically in context of embedded programming, where I can't do things the usual way with dynamic allocation.

答:
Dynamic memory allocation and constructors and destructors are completely unrelated.

If you are using new or delete (like in your renew function), you are using dynamic memory allocation.

A constructor or destructor does not always mean you are dynamically allocating memory.

The 'renew' function should probably be implemented in the operator= of the class, not as an external function, so:

```<code>A a{17}
...
a = 14;
...
</code>```

Example of what you should do:

```<code>class TwoInts
{
private:
    int int1;
    int int2;
public:
    TwoInts(int a = 6, int b = 7): int1(a), int2(b) {}
    TwoInts(const TwoInts& other): int1(other.int1), int2(other.int2) {}

    TwoInts& operator=(TwoInts& other)
    {
        a = other.a;
        b = other.b;
    }
};

TwoInts i(16);
//do stuff
i = TwoInts(68, 14);
//do stuff
</code>```

The above code does not do any memory allocation.

Title: In place reinitialization of objects

Body:
I'm working on an embedded system, where memory is scarce, and more importantly, since there's a soft realtime constraint (i.e. it's a bug if we don't make the deadline, but no one dies), I cannot use dynamic memory allocation.

However, there's the occasional need to re-initialize a subsystem, and there's been a number of bugs related to not-quite-everything getting either cleaned up or reset correctly. This is of course exactly the problem that constructors and destructors are supposed to solve, but since we don't allocate dynamically, we can't use the idiom where we'd destruct the object and then allocate a new one from scratch (mostly the objects of relevance here are globals).

So in the end there's usually setup code in a constructor, and a reinitialize -type function, which resemble each other but are not identical, since the reinitialize function also does a lot of what a destructor would do.

One way out that I'm thinking of is to write a "renew" -template (this is just a draft, may contain erors and possibly not complet):

template<typename T, typename .. Args>
void renew(T & obj, Args&&... args) {
  obj.~T();
  new(&obj) T(std::forward<Args>(args)...);
}

which could be used to reinitialize non-dynamically alloctated variables. So for example

A a{17};
... //Do something with a
renew(a, 14);
...//work with the new a, no need to reallocate memory

This would allow getting some of the advantages of constructors and destructors (primarily single way to initialize and deinitialize an object) without dynamic memory allocation. Note that the usage above is simplified, in practice this would mostly be used in very specific points in the main loop and on global objects representing the actual physical subsystems.

Question: is this a sensible way of going about it? Or is there a better alternative?

There's a very similar question here Calling a constructor to re-initialize object. I'm asking much the same thing but specifically in context of embedded programming, where I can't do things the usual way with dynamic allocation.

Body:
Dynamic memory allocation and constructors and destructors are completely unrelated.

If you are using new or delete (like in your renew function), you are using dynamic memory allocation.

A constructor or destructor does not always mean you are dynamically allocating memory.

The 'renew' function should probably be implemented in the operator= of the class, not as an external function, so:

A a{17}
...
a = 14;
...

Example of what you should do:

class TwoInts
{
private:
    int int1;
    int int2;
public:
    TwoInts(int a = 6, int b = 7): int1(a), int2(b) {}
    TwoInts(const TwoInts& other): int1(other.int1), int2(other.int2) {}

    TwoInts& operator=(TwoInts& other)
    {
        a = other.a;
        b = other.b;
    }
};

TwoInts i(16);
//do stuff
i = TwoInts(68, 14);
//do stuff

The above code does not do any memory allocation.


问:
Jenkins jobs not working after revoking Distribution certificate in Remote Machine
I have been facing an issue with Jenkins in building my iOS jobs. Recently our distribution certificate has been expired and we have revoked it and imported the same cert into Remote Machine. Since that moment my jenkins jobs are failing at the compile stage itself. Below is the error i'm getting from jenkins console. </p>

```<code>  /Users/jenkins/Library/Developer/Xcode/DerivedData/Companion-
  dtiiwydzoavsrybgsztwqribsxtx/Build/Products/Release-
  iphoneos/sample.app/Frameworks/KSCrash.framework:
  errSecInternalComponent
  Command PhaseScriptExecution failed with a nonzero exit code

** BUILD FAILED **

 The following build commands failed:
PhaseScriptExecution [CP]\ Embed\ Pods\ Frameworks
/Users/jenkins/Library/Developer/Xcode/DerivedData/Companion-
dtiiwydzoavsrybgsztwqribsxtx/Build/Intermediates.noindex/
Companion.build/Release-
iphoneos/SampleProject.build/Script-15FB268A228A7C3900925F65.sh
</code>```

<p>Do i need to add that new certificate some where else ? What might be the issue ? Any help is appreciated. </p>

答:
This has solved my problem https://stackoverflow.com/a/52221673/1025976.

Solution for errSecInternalComponent error is : Go to Keychain -> My Certificates -> Select your Development or Distribution certficiate -> Expand it and double click on the private key -> Select "Allow all applications to access them" and save changes. This should solve the problem.

Body:
I have been facing an issue with Jenkins in building my iOS jobs. Recently our distribution certificate has been expired and we have revoked it and imported the same cert into Remote Machine. Since that moment my jenkins jobs are failing at the compile stage itself. Below is the error i'm getting from jenkins console.

  /Users/jenkins/Library/Developer/Xcode/DerivedData/Companion-
  dtiiwydzoavsrybgsztwqribsxtx/Build/Products/Release-
  iphoneos/sample.app/Frameworks/KSCrash.framework:
  errSecInternalComponent
  Command PhaseScriptExecution failed with a nonzero exit code

** BUILD FAILED **

 The following build commands failed:
PhaseScriptExecution [CP]\ Embed\ Pods\ Frameworks
/Users/jenkins/Library/Developer/Xcode/DerivedData/Companion-
dtiiwydzoavsrybgsztwqribsxtx/Build/Intermediates.noindex/
Companion.build/Release-
iphoneos/SampleProject.build/Script-15FB268A228A7C3900925F65.sh

Do i need to add that new certificate some where else ? What might be the issue ? Any help is appreciated.


问:
.NET obfuscation tools/strategy
My product has several components: ASP.NET, Windows Forms App and Windows Service. 95% or so of the code is written in VB.NET.

For Intellectual Property reasons, I need to obfuscate the code, and until now I have been using a version of dotfuscator which is now over 5 years old. I'm thinking it is time to move to a new generation tool. What I'm looking for is a list of requirements which I should consider when searching for a new obfuscator.

What I know I should look for so far:

Serialization/De-serialization. In my current solution, I simply tell the tool not to obfuscate any class data members because the pain of not being able to load data which was previously serialized is simply too big.

Integration with Build Process

Working with ASP.NET. In the past, I have found this problematic due to changing .dll names (you often have one per page) - which not all tools handle well.

答:
I've recently tried piping the output of one free obfuscator into the another free obfuscator - namely Dotfuscator CE and the new Babel obfuscator on CodePlex.  More details on my blog.

As for serialization, I've moved that code into a different DLL and included that in the project. I reasoned that there weren't any secrets in there that aren't in the XML anyway, so it didn't need obfuscation. If there is any serious code in those classes, using partial classes in the main assembly should cover it.

Title: .NET obfuscation tools/strategy

LastEditorDisplayName: Keith

OwnerDisplayName: harriyott

ContentLicense: CC BY-SA 2.5


问:
Cross-Origin Request Blocked
So I've got this Go http handler that stores some POST content into the datastore and retrieves some other info in response. On the back-end I use:

```<code>func handleMessageQueue(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Access-Control-Allow-Origin", "*")
    if r.Method == "POST" {

        c := appengine.NewContext(r)

        body, _ := ioutil.ReadAll(r.Body)

        auth := string(body[:])
        r.Body.Close()
        q := datastore.NewQuery("Message").Order("-Date")

        var msg []Message
        key, err := q.GetAll(c, &msg)

        if err != nil {
            c.Errorf("fetching msg: %v", err)
            return
        }

        w.Header().Set("Content-Type", "application/json")
        jsonMsg, err := json.Marshal(msg)
        msgstr := string(jsonMsg)
        fmt.Fprint(w, msgstr)
        return
    }
}
</code>```

In my firefox OS app I use:

```<code>var message = "content";

request = new XMLHttpRequest();
request.open('POST', 'http://localhost:8080/msgs', true);

request.onload = function () {
    if (request.status >= 200 && request.status < 400) {
        // Success!
        data = JSON.parse(request.responseText);
        console.log(data);
    } else {
        // We reached our target server, but it returned an error
        console.log("server error");
    }
};

request.onerror = function () {
    // There was a connection error of some sort
    console.log("connection error");
};

request.send(message);
</code>```

The incoming part all works along and such. However, my response is getting blocked. Giving me the following message:

```<code>Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/msgs. This can be fixed by moving the resource to the same domain or enabling CORS.
</code>```

I tried a lot of other things but there is no way I can just get a response from the server. However when I change my Go POST method into GET and access the page through the browser I get the data that I want so bad. I can't really decide which side goes wrong and why: it might be that Go shouldn't block these kinds of requests, but it also might be that my javascript is illegal.

答:
You have to placed this code in application.rb</p>

```<code>config.action_dispatch.default_headers = {
        'Access-Control-Allow-Origin' => '*',
        'Access-Control-Request-Method' => %w{GET POST OPTIONS}.join(",")
}
</code>```

Title: Cross-Origin Request Blocked

Body:
So I've got this Go http handler that stores some POST content into the datastore and retrieves some other info in response. On the back-end I use:

func handleMessageQueue(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Access-Control-Allow-Origin", "*")
    if r.Method == "POST" {

        c := appengine.NewContext(r)

        body, _ := ioutil.ReadAll(r.Body)

        auth := string(body[:])
        r.Body.Close()
        q := datastore.NewQuery("Message").Order("-Date")

        var msg []Message
        key, err := q.GetAll(c, &msg)

        if err != nil {
            c.Errorf("fetching msg: %v", err)
            return
        }

        w.Header().Set("Content-Type", "application/json")
        jsonMsg, err := json.Marshal(msg)
        msgstr := string(jsonMsg)
        fmt.Fprint(w, msgstr)
        return
    }
}

In my firefox OS app I use:

var message = "content";

request = new XMLHttpRequest();
request.open('POST', 'http://localhost:8080/msgs', true);

request.onload = function () {
    if (request.status >= 200 && request.status < 400) {
        // Success!
        data = JSON.parse(request.responseText);
        console.log(data);
    } else {
        // We reached our target server, but it returned an error
        console.log("server error");
    }
};

request.onerror = function () {
    // There was a connection error of some sort
    console.log("connection error");
};

request.send(message);

The incoming part all works along and such. However, my response is getting blocked. Giving me the following message:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/msgs. This can be fixed by moving the resource to the same domain or enabling CORS.

I tried a lot of other things but there is no way I can just get a response from the server. However when I change my Go POST method into GET and access the page through the browser I get the data that I want so bad. I can't really decide which side goes wrong and why: it might be that Go shouldn't block these kinds of requests, but it also might be that my javascript is illegal.

Body:
You have to placed this code in application.rb

config.action_dispatch.default_headers = {
        'Access-Control-Allow-Origin' => '*',
        'Access-Control-Request-Method' => %w{GET POST OPTIONS}.join(",")
}


问:
Strawberry Perl - Search and replace in Windows
I am trying to execute the following command:

perl -pi -e 's,vaadin-element,color-picker,g' *.* demo/* test/* src/* theme/*/*

(following this document)

Unfortunately it seems that the window distribution of pearl I use has some issues with the command, as I get the following error:

```<code>Can't open *.*: Invalid argument.
Can't open demo/*: Invalid argument.
Can't open test/*: Invalid argument.
Can't open src/*: Invalid argument.
Can't open theme/*/*: Invalid argument.
</code>```

Any suggestions on how to fix that?
Thank you in advance!

Disclaimer: I never used pearl before and have absolutely no experience.

答:
In unix systems, the shell expands globs and passes the file names to the program.

```<code>$ perl -e'CORE::say for @ARGV' *
file1
file2
</code>```

The Windows shell, on the other hand, passes the values as is, and leaves it up to the program to treat them as globs if so desired.

```<code>>perl -e"CORE::say for @ARGV" *
*
</code>```

You can perform the globbing as follows:

```<code>>perl -MFile::DosGlob=glob -e"BEGIN { @ARGV = map glob, @ARGV } CORE::say for @ARGV" *
file1
file2
</code>```

The BEGIN block isn't generally needed, but it will ensure the globing once and early enough when using -n (which is implied by -p).

The -MFile::DosGlob=glob makes glob have Windows-like semantics. For example, it causes *.* to match all files, even if they don't contain ..

Integrated:

```<code>perl -i -MFile::DosGlob=glob -pe"BEGIN { @ARGV = map glob, @ARGV } s,vaadin-element,color-picker,g" *.* demo/* test/* src/* theme/*/*
</code>```

Body:
I am trying to execute the following command:

perl -pi -e 's,vaadin-element,color-picker,g' *.* demo/* test/* src/* theme/*/*

(following this document)

Unfortunately it seems that the window distribution of pearl I use has some issues with the command, as I get the following error:

Can't open *.*: Invalid argument.
Can't open demo/*: Invalid argument.
Can't open test/*: Invalid argument.
Can't open src/*: Invalid argument.
Can't open theme/*/*: Invalid argument.

Any suggestions on how to fix that?
Thank you in advance!

Disclaimer: I never used pearl before and have absolutely no experience.

Body:
In unix systems, the shell expands globs and passes the file names to the program.

$ perl -e'CORE::say for @ARGV' *
file1
file2

The Windows shell, on the other hand, passes the values as is, and leaves it up to the program to treat them as globs if so desired.

>perl -e"CORE::say for @ARGV" *
*

You can perform the globbing as follows:

>perl -MFile::DosGlob=glob -e"BEGIN { @ARGV = map glob, @ARGV } CORE::say for @ARGV" *
file1
file2

The BEGIN block isn't generally needed, but it will ensure the globing once and early enough when using -n (which is implied by -p).

The -MFile::DosGlob=glob makes glob have Windows-like semantics. For example, it causes *.* to match all files, even if they don't contain ..

Integrated:

perl -i -MFile::DosGlob=glob -pe"BEGIN { @ARGV = map glob, @ARGV } s,vaadin-element,color-picker,g" *.* demo/* test/* src/* theme/*/*