Why is my scoreList empty even though I've appended values to it? Runtime when code tries to max list

Question: I'm making a program that allows you to play connect 4 against my program. Here's everything that's going on in the shell:
b = board(7,6)
aiPlayer = player("X", 3)
b.playGameWith(aiPlayer)

| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
---------------
 0 1 2 3 4 5 6

O's choice: 3

Traceback (most recent call last):
  File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 1, in <module>
    # Used internally for debug sandbox under external interpreter
  File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 184, in playGameWith
  File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 225, in nextMove
  File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 214, in scoresFor
  File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 214, in scoresFor
  File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 220, in scoresFor
ValueError: max() arg is an empty sequence

b is the object I make in the shell from the board class. aiPlayer is the player object.
Here's the relevant code:
class board: # i have other methods too but didn't want to clutter
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.data = []

        for row in range(self.height):
            boardRow = []
            for col in range (self.width):
                boardRow += [' ']
            self.data += [boardRow]

    def __repr__(self):
        s = ''
        for row in range( self.height ):
            s += '|'
            for col in range ( self.width ):
                s += self.data[row][col] + '|'
            s += '\n'

        i = -1
        for col in range( (self.width * 2) + 1 ):
            s += "-"
        s+= '\n'
        s+= " "
        for col in range( self.width ):
            i += 1
            s += str(i) + " "
        return s

     def playGameWith(self, aiPlayer):
        winner = False
        if aiPlayer.ox == "X" or aiPlayer.ox == "x":
            firstMove = "O"
        else:
            firstMove = "X"
        while(winner == False):
            print "\n", self, "\n"

            if firstMove == "X":
                humanMove = int(raw_input("X's choice: "))  # get user input for column choice
                while(self.allowsMove(humanMove) == False): # ensure the user is selecting a valid column
                    humanMove = int(raw_input("\n" + "Invalid 'X' move, please try again: "))
                self.addMove(humanMove, "X")
                if (self.winsFor("X") == True):
                    message = "X wins -- Congratulations!"
                    break

                elif (self.isFull() == True):
                    message = "Looks like we got ourselves a tie."
                    break

            else:
                humanMove = int(raw_input("O's choice: "))
                while(self.allowsMove(humanMove) == False): # ensure the user is selecting a valid column
                    humanMove = int(raw_input("\n" + "Invalid 'O' move, please try again: "))
                self.addMove(humanMove, "O")
                if (self.winsFor("O") == True):
                    message = "O wins -- Congratulations!"
                    break

                elif (self.isFull() == True):
                    message = "Looks like we got ourselves a tie."
                    break

            AI_Move = aiPlayer.nextMove(b) # here's where problems start. line 184
            self.addMove(AI_Move, aiPlayer.ox)

class player:
    def __init__(self, ox, ply):
        self.ox = ox
        self.ply = ply

    def scoresFor(self, b, ox, ply):
        scoreList = []
        opScoreList = []
        for col in range(b.width):
            if b.allowsMove(col):
                b.addMove(col, ox)

                if b.winsFor(ox) == True:
                    scoreList.append(100)

                elif ply == 1:
                    scoreList.append(50)

                else:
                    if ox == "X" or ox == "x":
                        ox = "O"
                    else:
                        ox = "X"
                    opScoreList = self.scoresFor(b, ox, ply-1) # line 214

                b.delMove(col)
            else:
                scoreList.append(-1)
        scoreList.append(100 - max(opScoreList)) # line 220
        return scoreList

    def nextMove(self, board):
        moveList = self.scoresFor(b, self.ox, self.ply) # line 225
        bestMove = moveList.index((max(moveList)))
        return bestMove

Comment: Can you attach a full stack trace of the exception that's happening? That way, we can see what line it happens on and such.
Comment: Some other context would be good too.  For instance, is the `b` argument in your `moveList = self.scoresFor(b, self.ox, self.ply)` a global variable?  or should it be `board`?
Comment: I suspect the problem is with `scoreList.append(100 - max(opScoreList))`.
Comment: I tried commenting out the     scoreList.append(100 - max(opScoreList)) line and I still had an error.
Answer: self.scoresFor(b, ox, ply-1)

or
self.scoresFor(b, self.ox, self.ply)

Return an empty list. Try putting some trace output in your code and figure out why. It's impossible to say without more context.


Get context of newly started activity via startActivityForResult

Question: I am starting an activity via startActivityForResult. Is there any way to get the instance or context of the newly started activity? Thanks.
Comment: What do you mean context of a newly started activity. If its an activity it has a Context.
Answer: Not that I'm aware of.
When an activity starts another activity, it can pass data to it (call this upstream). When the activity is done, it can return data to the caller (call this downstream). The upstream and downstream communication only happens at the point of invocation and termination respectively.
You seem to need the context of the called activity in the caller. Most likely the calling activity will be put in the "Paused" state when the called activity starts. Even if you were to manage to make the called activity to set the context object to some variable they both can share (e.g. via the global application object), there is no guarantee that the calling activity will be around to make use of the context.
Comment: ok, I had the same feeling, but wasn't sure. Thanks to confirm it.


Ubuntu how to change CPU max MHz?

Question: Screenshot of terminal
Hi i have set my cpu frequency to 3900 MHz in my bios however on the lscpu in the terminal it is showing different values? is there a way to change this I have no idea as im new to using linux and ubuntu.
Comment: You don't say what version Ubuntu, or hardware description...
Answer: Your processor should use the intel_pstate CPU frequency scaling driver by default.
You can change the maximum CPU frequency to 3.9 GHz via:
echo 3900000 | sudo tee /sys/devices/system/cpu/cpufreq/policy*/scaling_max_freq

or via:
echo 76 | sudo tee /sys/devices/system/cpu/intel_pstate/max_perf_pct

(Rounding might require 77%)
Neither method will persist through re-boot. What you want is very close to just disabling turbo, 3.8 GHz, so you could do that in BIOS. If you want to do it from the OS, which would be non-persistent:
echo 1 | sudo tee /sys/devices/system/cpu/intel_pstate/no_turbo

This answer uses primitive commands. Others might give answers that use higher level tools to do the same thing.
EDIT: Actually, it looks as though you might already have turbo disabled in the BIOS, in which case you will not be able to get to 3.9 GHz. Do this:
grep . /sys/devices/system/cpu/intel_pstate/no_turbo/*

to see your current operating parameters.
Answer: Go to https://extensions.gnome.org/# and search for "CPU freq"...
Note: Understand that setting your CPU frequency too high might cause it to overheat, and/or the fans to be less than silent. It may also effect your battery life. Overclocking the CPU or RAM can cause other problems.

Ubuntu how to change CPU max MHz?


Where's my [Classified]?

Question: As indicated by this question I bought the Potato Sack bundle a scant few days before Portal's release. Rather than buying the Potato Sack alone, I instead bought it bundled with Portal 2, as listed here.
I've been playing a bit of TF2 after spending all of yesterday selfishly swiping potatos, and though I played for about an hour, I did not get either the [Classified] potato hat (gained by purchasing the potato sack), nor the Portal 2 companion cube pin (which should be given out to anyone who purchases Portal before the 19th - I purchased the bundle on the 16th)
What gives? Do I have to do something additional to claim my [Classified] and companion cube pins? (On the other hand, The Resurrection Association Pin, earned for playing every game in the potato sack, has been earned).
Comment: Just wait, it happens more or less with every promotional items. Hat .delivery is slow, they are probably "hand-made"
Answer: I would check again following today's update.
Also, try visiting the Mann Co. store once, even if you aren't buying anything.
Comment: That worked for me. I received my companion cube pin after visiting the Mann Co. store.
Answer: It took me a few days to get my [Classified] after they I purchased the bundle (though I purchased it as soon as I knew it gave a hat); you should get yours eventually.
Comment: The potato hat wasn't in TF2 yet when the Potato Bundle was announced as having a TF2 hat, so there's a good reason you didn't get it immediately.
Comment: I didn't get it for a few days after it was included, either.

Where's my [Classified]?


EventHub PartitionContext Class Design

Question: I am trying to test my implementation of the IEventProcessor. However, I am having a hard time, because it is impossible to actually mock the PartitionContext class (https://msdn.microsoft.com/en-us/library/microsoft.servicebus.messaging.partitioncontext.aspx).
For example, I can not verify if the CheckpointAsync() method has been called correctly, because the ICheckpointer interface is internal and the actual method is not virtual.
Furthermore, I can not inject my own ICheckpointManager instance, because the constructor which allows this, is internal.
What is the design decisions in making everything internal, which would allow me to mock this class?
Either this is really bad design or I am missing something.
Answer: Yes, it is a lot of work to test this. Here's what to do.
So you create a wrapper:
public interface ICheckPointer
{
    Task CheckpointAsync(PartitionContext context);
}

public class CheckPointer : ICheckPointer
{
    public Task CheckPointAsync(PartitionContext context)
    {
        return context.CheckpointAsync();
    }
}

In your unit test method you can now mock the interface and check whether CheckPointAsync is called.
Your implementation of IEventProcessor now should accept an instance of ICheckPointer:
public class SampleEventProcessor : IEventProcessor
{
    private ICheckPointer checkPointer;

    public SampleEventProcessor(ICheckPointer checkPointer)
    {
        this.checkPointer = checkPointer;
    }

    public Task OpenAsync(PartitionContext context)
    {
        return Task.FromResult<object>(null);
    }

    public async Task ProcessEventsAsync(PartitionContext context, IEnumerable<EventData> events)
    {
        ...

        await checkPointer.CheckpointAsync(context);
    }

    public async Task CloseAsync(PartitionContext context, CloseReason reason)
    {
        return Task.FromResult<object>(null);
    }
}

You will need an implementation of IEventProcessorFactory to inject the ICheckPoint interface:
internal class SampleEventProcessorFactory : IEventProcessorFactory
{
    private readonly ICheckPointer checkPointer;

    public SampleEventProcessorFactory (ICheckPointer checkPointer)
    {
        this.checkPointer = checkPointer;
    }

    public IEventProcessor CreateEventProcessor(PartitionContext context)
    {
        return new SampleEventProcessor(checkPointer);
    }
}

and you create the EventProcessor like this:
await host.RegisterEventProcessorFactoryAsync(new SampleEventProcessor(new CheckPointer()));

in the unit test you could now do something like (based on NSubstitute):
var mock = Substitute.For<ICheckPointer>();
var sample = new SampleEventProcessor(mock);
await sample.ProcessEventsAsync(new PartitionContext(), null);
mock.Received().CheckPointAsync(Arg.Any<PartitionContext>());

Warning: did not compile the code so there could be some syntax errors. At least it should give you a basic idea of how to proceed.
Comment: "new PartitionContext()" causes a compilation error because the constructor is apparently not public.
Comment: @Dudeman3000 It was at the time the question is posted, see [the docs](https://learn.microsoft.com/en-us/dotnet/api/microsoft.servicebus.messaging.partitioncontext.-ctor?view=azure-dotnet#Microsoft_ServiceBus_Messaging_PartitionContext__ctor). What NuGet package are you using?
Comment: Apologies, I'm working with the PartitionContext in the Microsoft.Azure.EventHubs.Processor namespace. I'm using NuGet package v2.0.1. Looking at the [docs](https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.eventhubs.processor.partitioncontext?view=azure-dotnet-legacy&viewFallbackFrom=azure-dotnet) it appears that there is no version that offers a public empty constructor. I've attempted to use the available constructor but was unable to mock or instantiate the required EventProcessorHost parameter.
Answer: A fairly new addition to the Azure.Messaging.EventHubs library is EventHubsModelFactory, it has some helpful static methods for unit testing.
ParitionContext partitionCtx = EventHubsModelFactory.PartitionContext(partitionId);

Comment: Hi W. Poust, thanks for your post. Can you update your answer explaining more clearly how this answers the original question?

EventHub PartitionContext Class Design


Why does some polyurethane need to be wiped off, and what happens if I don't?

Question: So, I stupidly applied some polyurethane to my project without reading the instructions on the can.  After it was dry several hours later, I finally read the instructions, and to my horror, I saw it said something like this:

Let sit for 30 minutes, then wipe off with lint-free reg.  Do not let the finish dry without wiping it off.

So, erm, now what do I do?  Did I ruin my project (it still looks perfectly fine..)?  Why does it need to be wiped off, and what are the consequences if I don't!?
Comment: Is this straight polyurethane, or polyurethane/stain combo?
Comment: @Tester101: Not sure what it was.  It wasn't straight polyurethane, but it definitely contained it.
Answer: There's a chance you were using wiping varnish or a "tung oil finish" (not really tung oil). It's basically thinned down poly that can be left on in a thick coat, or the excess can be wiped off after a coat is applied.
The warning to not let the finish dry without wiping is probably good advice to eliminate the possibility of runs and drips.
Popular Woodworking has a good article on the history of wiping varnish.
Comment: wiping the excess off also produces thinner coats, which may be desirable depending on the look you're trying to achieve. With poly, too many thick coats will make the wood look 'plasticy'. If you apply the same amount of thinner coats, you'll get the same smooth finish without the extra build up.
Comment: It's just to avoid runs/drips?  So forgetting to wipe it off won't, say, ruin the wood, or leave it permanently oily?
Comment: Disclaimer: Learned about 'wiping varnish' for the first time today via Google. Before your question, I'd never heard about wiping off a poly coat after application.
Comment: @BlueRaja-DannyPflughoeft From what I can tell, if that's what you're using, then yes - it's just to avoid runs and drips. It may also help eliminate brush strokes.


Is a surjective function with the same finite domain and finite codomain automatically bijective?

Question: I have a particular question I am trying to solve.
True or false.  Any surjective (onto) function $f:x \rightarrow x$ where $x$ is finite, must be bijective.
Since $x$ is finite, and since the domain and codomain are both the same, I am tempted to argue true, because I don't see how else each element in x could be hit.  Am I wrong?
Comment: Yes, it's true. It's one of the distinguishing features of finite sets.
Comment: You're welcome; glad to help!
Comment: You're argument is right, you can make it formal by induction if you feel like it!
Answer: You are correct, as the comments point out. Two quick comments:
(1) You don't need induction, although you can use it if you want to. Given a map $f: X\rightarrow X$ which is surjective but not injective, you can build an injection of $\mathbb{N}$ into $X$ (fun exercise), so $X$ couldn't have been finite.
(2) Very weirdly, the converse need not hold (unless we assume the axiom of choice): it is consistent with ZF, the axioms of set theory minus choice, that there are infinite sets $X$ such that any onto map $X\rightarrow X$ must be a bijection. Such sets are called Dedekind-finite.
Answer: Yes because given $f:X \rightarrow X$ with $X$ finite:

Let $n = |X|$
Let $x$ and $x'$ be such that $f(x) = f(x')$
If $x \neq x'$ then $|f(X)| \leq n - 1$
In which case $f$ would not be surjective
Answer: Let $|x| = n \in   \mathbb{N} $. For every $a\in   x$,
define $g(a)=|f^{-1}(\left \{  a\right \})|$, i.e. $g(a)$ is pre-image of the singleton set $\left \{  a\right \}$ under $f$. By surjectivity of $f$, we know that $\forall y\in  x \ \ g(y)\neq 0$. Now define:
$A=\left \{g(x):x\in x  \right \}$. As $x$ is finite $A$ has the minimal element, say m. Now we know that (under assumption that $f$ is well-defined) that every element of $x$ is mapped to exactly one element of x, so in particular:
$ n*m\Leftarrow n \Rightarrow m=1$, as $m\neq  0$. Similar argument for $\mathbb{E}(A)$ (Average value of elements of $A$) shows that average value equals to the value of minimal element, so all elements of $A$ are equal to $1$, so $f$ it's both injective and surjective, and the result follows.


Javascript Array of objects - how do i loop through and get the object values

Question: Im having some issues creating an array of objects in javascript
Please see my code below and tell me where im going wrong..
I simply want to loop through and access the values

Comment: what do you mean by "view the object"? Do you mean how can you perform `alert` with its properties?
Comment: yes, access its properties :)
Answer: The for .. in .. works different in javascript than in some other languages. Instead of the object, you will get the key. In your array therefore you'll get the index.
For iterating over arrays, just use an index-based array to avoid hassle:
for (var ix = 0; ix < myArray.length; ix++) {
    var obj = myArray[ix];

    alert(obj.name);
}

If you really want to use the for .. in .. syntax, use this:
var a = ['jan', 'klaas'];
for(var key in a) {
    if (a.hasOwnProperty(key)) {
        console.log(a[key].name);
    }
}

Answer: -                for (obj in myArray) {
-                    // do i need to cast ?? how can i view the object ??
-                    alert(obj + " - ");
-                }

+                for (var i = 0; i < myArray.length; i++) {
+                    var obj = myArray[i];
+                    // do i need to cast ?? how can i view the object ??
+                    alert(JSON.stringify(obj, null, '  '));
+                }


How to replace phpunit assertion message?

Question: How do I replace an assertion error message? If I call $this->assertTrue(false, 'message'), it will display both the string "message" and also another message stating that false is not true. How do I get it to only output the message that I chose? Is this even possible?
Comment: Because so far, the only way I can find to define a custom assertion with a custom message, is to write a class that extends PHPUnit_Framework_Constraint - which is annoying, when I can just use one of the existing constraints by preprocessing the parameters.
Comment: I'm wondering the reason you need this for. Are you maybe using the same assertion type for all the checks? `Like assertTrue($a == $b)`.
Answer: code-crutch which comes to my mind when I faced the same problem:
public function assertTrue($condition, $message = '')
{
    if (!$condition) $this->fail($message);
}

Comment: It's wrong to do that because if the method does not fail, it does not count as an assertion, and you may have some risky test, and a wrong total of assertions at the end.
Answer: With PHPUnit 6 you must have got one assertion at least, so i suggest a little edited @avolkov answer:
public function assertTrue($condition, $message = '')
{

    if (!$condition){
      $this->fail($message); //This will cause test fail with your message
    }
    else{
      $this->anything(); //This will eliminate error which says that your test doesn't have assertion
    }
}

Answer: It's not possible.
Why would you want to do so? Never encountered a case in which the default message is not helpful in any way. The custom message should add information, not replace the default one.
Comment: Because if I want to define a custom assertion, I can't wrap an existing one (e.g. assertThat) because it will product it's own message. since everything comes down to an assertTrue in the end, you get messages like "Failed asserting that X has property Y. Failed asserting that false is true", which is annoying and not helpful.
Comment: Wouldn't the assertion response message for that just be "Object does not match expected NULL"? that doesn't seem helpful to include - your example appears to be a good case for when you would WANT to ignore the default message.
Comment: This depends on each one's opinion but let me show a real example: $this->assertNull($this->router->match($url), "URL '{$url}' matched and should have not"); In this example, I will see the normal error, showing me WHAT was really returned, which is helpful, and my custom error message that helps understanding WHY it's not ok. EDIT: this goes inside a custom assertion called assertUrlDoesNotMatch($url)


How to combine two arrays without overwriting the keys

Question: I am having two arrays with the same key . How can I combine those two arrays without overwriting the keys of first array.
I tried using array_merge() function , + operation
These are the two arrays:
Array ( [1] => 1 ) Array ( [1] => 0 )

I want the output to be like
array( [1] => 1 , [1] => 0)

Comment: Your expected output is impossible, 2 rows in your array cannot contain the same key. Tell me, if you want that output, how would you retrieve the value of the 2nd row?
Comment: you cant have duplicate keys in array
Comment: Output can't be `array( [1] => 1 , [1] => 0)` - you can't have two same keys (1) in your array.
Comment: This is obviously an XY problem. Explain *why* you want to have an array with duplicate keys and it is likely that someone here can explain the proper way to solve the problem.
Comment: You can't have multiple same keys, but you can definitely have multiple values for a key since you want to preserve them.
Comment: in a single dimensional array  2 or more keys cannot be same. See here:-https://3v4l.org/fevRo
Comment: Fifth times a charm... ***You can't have an array with the same keys...*** In all seriousness, consider having nested arrays and then you can have the same keys: `[ 0 => [ 1 => 1 ], 1 => [ 1 => 1 ] ]` and then you'd go `$arr[0][1]` or `$arr[1][1]`.
Comment: Has anyone mentioned that array keys must be unique???
Answer: You can't have duplicate keys in an array.
What you can do is build an array of object with different keys: 0,1,2,3,4,etc. but with sub objects which will make access to the same object property.
// for istance in this case you end up having an array
// with 5 objects with a property named "key" with a value
$arrayOfObjects = [];
$arrayOfObjects[] = (object)["key"=>"value0"];
$arrayOfObjects[] = (object)["key"=>"value1"];
$arrayOfObjects[] = (object)["key"=>"value2"];
$arrayOfObjects[] = (object)["key"=>"value3"];
$arrayOfObjects[] = (object)["key"=>"value4"];
// to return the value $arrayOfObjects[4]->key

Comment: Why not just a simple array of arrays?
Comment: From his post i assumed he needed a "constant" key to access, with a variable value. Using array of arrays would require 2 Dynamic indexes, which would be against his "concept". That's just an assumption i made while reading it


How to find Full list of Facebook ID and names of Cities from Facebook Marketing API

Question: How can I use the Facebook Ads API to find a comprehensive list of all the cities that can be targeted for ads, and what parameters should I use in my request to ensure that I receive accurate and up-to-date information?
I tested the following parameter in Facebook Graph API Explorer, and its returned an empty Result, but it displays a complete list of countries when I change location_types=['country']
search?location_types=["city"]&transport=cors&type=adgeolocation

Is there a CSV for all the geolocation details for Facebook? How can I get a List of all cities Facebook Ads GeoLocation has?
Comment: I don't know if they provide a full list anywhere, but you can search for cities using https://developers.facebook.com/docs/marketing-api/audiences/reference/targeting-search#cities
Answer: You can try calling the targetingsearch endpoint in the Graph API explorer with the following fields:

type: set to adgeolocation to search for geographic locations.
location_types: set to city to retrieve cities.
limit: set to a high number to retrieve all the cities (e.g., 10000).
fields: specify the fields you want to retrieve (e.g., name, country_code).

Following is an example search path you can try
/act_{ad_account_id}/targetingsearch?location_types=["city"]&type=adgeolocation&limit=10000&fields["name,country_code"]
Make sure you're using a user access token or a page access token with ads_management permission. Also you need to replace {ad_account_id} with the ID of the ad account you want to retrieve targeting information for.
I do not think Facebook provides a CSV of all geolocations but you can use the JSON response from above to convert to CSV using free tools online such as this one - https://data.page/json/csv


Better pattern to detect web3 default account when using metamask

Question: Context: I want to use blockies to render an identicon on the page, i get the defaultAccount from web3, for this, the user has to be logged on to metamask with a selected address from his wallet.
The problem: the web app seems to not detect the web3 object on the load event of the page, wchih is the recommended place to detect it.
The code: below is inspired from recommendations at:
https://github.com/MetaMask/metamask-plugin/issues/1158
https://github.com/MetaMask/faq/blob/master/DEVELOPERS.md#partly_sunny-web3---ethereum-browser-environment-check
I keep having intermittent behaviour, sometimes web3 is there and sometimes it is not, the only solution I can think of is to have a timer, but that seems to me a bit too simplistic, I would prefer something more elegant.
Question: Is there a better solution to detect the defaultAccount from web3 when the page loads?
 function startApp() {
        GenerateIdenticon();
}

window.addEventListener('load', function () {

// Checking if Web3 has been injected by the browser (Mist/MetaMask)
if (typeof web3 !== 'undefined') {

    // Use Mist/MetaMask's provider
    window.web3 = new Web3(web3.currentProvider);
    if (web3.currentProvider.isMetaMask === true) {
        if (typeof web3.eth.defaultAccount === 'undefined') {
            document.body.innerHTML = '
Oops! Your browser does not support Ethereum Ðapps.
';
        }
        else {
            startApp();
        }
    }
    else {
         alert('No web3? Please use google chrome and metamask plugin to enter this Dapp!', null, null);
        // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
       window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}

Answer: function _Connect(callback){
    if(typeof web3 !== 'undefined') {
          web3 = new Web3(window.web3.currentProvider);
          web3.version.getNetwork((err, netId) => {
              switch (netId) {
                case "1":
                    callback('Switch Network', null);
                  break
                case "2":
                  console.log('This is the deprecated Morden test network.');
                  callback('Switch Network', null);
                  break
                case "3":
                    console.log('Connected to the ropsten test network.');
                    web3.eth.defaultAccount = web3.eth.accounts[0];
                    if(!web3.eth.defaultAccount){
                        console.log('Log into metamask');
                        _Connect(callback);
                    }else{
                                                    // Success
                        console.log(`Web3 ETH Account: ${web3.eth.defaultAccount}`);
                        callback(false, web3.eth.defaultAccount);
                    }
                  break
                default:
                  console.log('This is an unknown network.');
                  callback('Switch Network', null);
              }
            });
        } else {
          console.log(`Failed: Web3 instance required, try using MetaMask.`);
          callback('Install Metamask', null);
        }
}

Comment: logging into metamask doesn't cause a page refresh so I use recursion to keep checking if they have logged in. All other actions that end up invoking the callback are states that if a user takes actions will cause a page refresh and start the _Connect function again.
Answer: There is a delay when Chrome inserts the MetaMask Web3 library so the timeout is necessary (1 second timeout should be enough).
After the timeout, you check if the web3 global object exists and then read the default account.
If it doesn't exist, then insert your own web3 object.


Limit of density of $X\sim\text{Gamma}(\alpha,\alpha/\mu)$ as $\alpha\to\infty$

Question: We are given a gamma random $X\sim\text{Gamma}(\alpha,\beta)$ where $\beta=\alpha/\mu$. Then $\mathbb{E}[X]=\mu$ and the pdf of $X$ is
\begin{equation}
f_{X}(x)=\frac{(\alpha/\mu)^{\alpha}}{\Gamma(\alpha)}x^{\alpha-1}e^{-\alpha x/\mu}.
\end{equation}
What is $\lim_{\alpha\to\infty}f_{X}(x)$?

By central limit theorem, I suspect the solution is
\begin{equation}
\lim_{\alpha\to\infty}f_{X}(x)=\delta(x-\mu).
\end{equation}
Comment: Look at the variance as a function of $\alpha$ and $\mu$.
Comment: @heropup Right. $\mathrm{var}[X]=\mu^{2}/\alpha$ so as $\alpha\to\infty$ we end up with a r.v. with $\mathbb{E}[X]=\mu$ and $\mathrm{var}[X]=0$ which means $X\sim\delta(x-\mu)$.  I was more interested in solving the limit directly, i.e. computing $\lim_{\alpha\to\infty}f_{X}(x)$.
Answer: \begin{equation}
f_{X}(x)=\frac{(\alpha/\mu)^{\alpha}}{\Gamma(\alpha)}x^{\alpha-1}e^{-\alpha x/\mu}\Rightarrow \ln f_X(x)=\alpha\ln(\alpha/\mu)-\ln\Gamma(\alpha)+(\alpha-1)\ln x-\frac{\alpha x}{\mu}\ .
\end{equation}
Use Stirling's approximation for the Gamma function
$$
\ln\Gamma(\alpha)\sim (\alpha-1/2)\ln\alpha-\alpha+\ln(2\pi)/2
$$
to conclude that
$$
\ln f_X(x)\sim \alpha(1+\ln (x/\mu)-x/\mu)+(1/2)\ln\alpha+\ldots
$$
Therefore, all depends on the combination $1+\ln(x/\mu)-x/\mu$. If it is $=0$ (which happens when $x=\mu$), then $\ln f_X(x)\sim (1/2)\ln\alpha\to\infty$ as $\alpha\to\infty$. If it is not equal to zero, then we know it is always negative (let's call this coefficient $-|\gamma|$), therefore $f_X(x)\sim e^{-a |\gamma|}\to 0$. So indeed $f_X(x)=\delta(x-\mu)$ (which is $=\infty$ if $x=\mu$ and $0$ otherwise).


Displaying folder contents in ComboBox/Dropdown-List

Question: There is a folder of "profile" files and I want the user to see and select one of those profiles in a dropdown list. The user can select one of those profiles fine, but in the dropdown list not the file names are shown, the paths to those files is shown.
The code I have so far is from this stackoverflow question I found online:
string[] files = Directory.GetFiles(@"[path]");

try
{
    foreach (string file in files)
    {
        Profile_ComboBox.Items.Add(file);
    }
}
catch (Exception ex)
{
    MessageBox.Show("Fehler: " + ex);
}

When opening the dropdown list, [path] is shown in each entry. When selecting one of the entries by clicking on it, the name of the file is shown.
I already tried using .AddRange(files) but I got the same results.
(Using VS Community 2019, .NET Framework 3.1)
Comment: This doesn't quite make sense to me. Is this exactly the code you are using? What is the purpose of `Directory.GetFiles(@"[path])`? What is *[path]* here?
Comment: @JonathanWood `[path]` is the placeholder I made instead of writing the full path in there because it is quite extensive
Comment: That's what I figured until you said you were getting *[path]* displayed in the list. Step through the code. What is `file` in the loop?
Comment: A string the foreach-loop is looking for in the string array `files`
Comment: That doesn't sound to me like you stepped through the code at all. And that's not what I was asking.
Comment: Can you please clearly state what the question is?
Comment: Your "question" did not contain a single question mark, so I think it is fair to ask to clearly state the question.  If you would have asked your question in a more concise way, we could have flagged it as a duplicate and you could read the tons of answers that already exist on this subject.
Answer: For me your code shows the path of the files because the "GetFile" method returns a string array that contains the full path of the files, not only the names.
If you need only the names, in the "foreach" loop you probably need to call the Path.GetFileName method (or even better, the GetFileNameWithoutExtension)


UIDeviceOrientationPortrait , ios 6 & 7 , InterfaceOrientation

Question: i have this code i want to go to another uiview but i want to have showing this view (second view) in portrait mode only and the notification in first view doesn't work in second view  ;
is there any way to change the for this
<code>   [[NSNotificationCenter defaultCenter] removeObserver:self];

    view2 *viewController = [[[view2 alloc] init] autorelease];
    UINavigationController *navController = [[[UINavigationController alloc] initWithRootViewController:viewController] autorelease];

    viewController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentModalViewController:navController animated:NO];
</code>
i want exactly one function same this  code in ios >6
<code>- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {

    return NO;
}
</code>
Answer: Try subclassing the UINavigationController and override the following methods :
<code>- (BOOL)shouldAutorotate
{
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}
</code>
Comment: That's strange!
Have you created the instance of new custom Navigation controller as below :

    UINavigationController *navController = [[[CustomNavigationController alloc] initWithRootViewController:viewController] autorelease];
Comment: Yes , but how can i go to other navigation controler with codes


How can I change Python version of pip3

Question: I have the following situation:

Python version is 3.8.2, but Python version of pip3 is 3.9. How can I change it?
Comment: You probably have multiple python installations.
You can check the executable path with `which pip3` and `which python3` and you will see that they have a different location.

your PATH variable defines which python installation is picked first, you can check that with `echo $PATH`, what comes first is used first
Comment: Never use the `pip`, `pip3`, etc. scripts. Instead always call _pip_'s executable module for a specific Python interpreter explicitly: `pythonX.Y -m pip ...`. -- https://snarky.ca/why-you-should-use-python-m-pip/
Answer: As the comments have already said, it looks like you have 2 python versions installed, so you either want to uninstall one of them or use python3.8 -m pip instead of just pip3

How can I change Python version of pip3


A List<> of Func<>s, compile error with generic return type, but why?

Question: This is a bit of a lengthy question, so please bear with me.
I need to create a mapping between a set of strings and corresponding generic method calls for each string. However I've run into a compile issue, explained lower down.
In my scenario I am using a Dictionary<>, but the issue exists equally for a List<>. For simplicity I'm using a List<> in the example below.
Consider these three classes:
public abstract class MyBase { /* body omitted */  }
public class MyDerived1 : MyBase { /* body omitted */  }
public class MyDerived2 : MyBase { /* body omitted */  }

And a method in some other class:
public class Test
{
    public T GetT<T>() where T : MyBase { /* body omitted */ }
}

In another class, I can declare a List<Func<MyBase>> like this:
public class SomeClass
{
    public void SomeFunc()
    {
        var test = new Test();

        var list1 = new List<Func<MyBase>>
            {
                test.GetT<MyDerived1>,
                test.GetT<MyDerived2>
            };
    }
}

This is all fine and well.
But, what if I want to have a function that return a generic class like this:
public class RetVal<T> where T : MyBase { /* body omitted */ }

public class Test
{
    public RetVal<T> GetRetValT<T>() where T : MyBase
    {
        return null;
    }
}

And I want to create an equivalent List<> using this function. i.e. a List>>?
public class Class1
{
    public void SomeFunc()
    {
        var test = new Test();

        var list2 = new List<Func<RetVal<MyBase>>>
            {
                test.GetRetValT<MyDerived1>, // compile error
                test.GetRetValT<MyDerived2> // compile error
            };
    }
}

I get compile errors of Expected a method with 'RetVal<MyBase> GetRetValT()' signature.
So, is there any way around this, or is there an alternative approach that I can use for creating my string...generic method call mappings?
Comment: It's a variance issue. Basically, a `RetVal` *isn't* a `RetVal`. More details when I have time.
Comment: What @JonSkeet said is true. It's a law in C#. If you want to slot `RetVal`'s MyDerived to `RetVal`'s MyBase, you have to make the `RetVal` accept an untyped generic too, i.e. `RetVal`. See an example here: http://www.ienablemuch.com/2012/05/generics-object-orientation-untyped.html
Comment: I may be entirely off-base on this, but wouldn't the very idea of returning a generic violate the notion that the generic has to (eventually) resolve to something the compiler knows about at compile time? That is, the reason the compiler throws that very error is that it expects you to provide the method that can return a specific type (which I realize is opposite what you're trying to do). Just an observation, as I said, may be way off base here...
Comment: @DavidW: Not sure I understand what you're saying. Are you saying that a `Func` should not be castable to a `Func`?
Comment: Just as the previous two commenters said (much more efficiently than I), RetVal isn't a RetVal, even though we understand in the OP's hierarchy MyDerived is a MyBase.
Answer: C# only allows covariance on interfaces. That means you cannot cast a RetVal<MyDerived1> to a RetVal<MyBase> automatically. If RetVal should be covariant, create an interface for it, like so:
public interface IRetVal<out T>
{

}
public class RetVal<T> : IRetVal<T> where T : MyBase { /* body omitted */ }

public class Test
{
    public IRetVal<T> GetRetValT<T>() where T : MyBase
    {
        return null;
    }
}

Then this code will work:
    var list2 = new List<Func<IRetVal<MyBase>>>
        {
            test.GetRetValT<MyDerived1>,
            test.GetRetValT<MyDerived2>
        };

Comment: Issues if you use `dataSources = new List>>` in ***another AppDomain***: `AppDomain.Create`
Comment: @Kiquenet: I don't understand your comment. Can you clarify?
Answer: The problem is the classic covariance/contravariance of generics.  You are assuming that because MyDerived1 and MyDerived2 inherit from MyBase, that a RetVal<MyDerived1> inherits from RetVal<MyBase>, and it doesn't.
The easiest way to fix this is probably to change the code to:
var list2 = new List<Func<RetVal<MyBase>>>
        {
            () => (MyBase)test.GetRetValT<MyDerived1>,
            () => (MyBase)test.GetRetValT<MyDerived2>
        };

or better yet, as JS points out in comments, just change RetVal<T> to be covariant if possible:
public interface IRetVal<out T> { ... }

public class RetVal<T> : IRetVal<T> { ... }

Comment: Not quite - in C# 4, `Func` *is* covariant in T, which is why the first example works. It's `RetVal` which isn't covariant here.
Comment: Right, sorry...  Will straighten that out
Answer: Generic type parameters for classes cannot be covariant, but they can be covariant for interfaces.  You can do what you want with an interface IRetVal<T> instead of the class RetVal<T>, if the type parameter is declared as covariant.  In order to declare an interface type parameter as covariant, it must be used only in "output" positions.
To illustrate, this code will not compile:
interface IRetVal<out T>
{
    T Value { get; }
    void AcceptValue(T value);
}

To get the code to compile, you must either remove the out modifier from the type parameter, or remove the AcceptValue method (because it uses T for a parameter: an input position).
With the IRetVal<out T> interface, you can do this:
public class MyBase { }
public class MyDerived1 : MyBase { }
public class MyDerived2 : MyBase { }

public interface IRetVal<out T> where T : MyBase { /* body omitted */ }

public class Test
{
    public IRetVal<T> GetRetValT<T>() where T : MyBase
    {
        return null;
    }
}

public class Class1
{
    public void SomeFunc()
    {
        var test = new Test();

         var list = new List<Func<IRetVal<MyBase>>>
        {
            test.GetRetValT<MyDerived1>,
            test.GetRetValT<MyDerived2>
        };
    }
}

Answer: I had a similar issue just recently.
C# does not support return type covariance for the purposes of interface implementation or virtual method overrding. See this question for details:
Does C# support return type covariance?.
You may be able to hack this, my doing:
public RetVal<R> GetRetValT<T,R>() where T : MyBase where R : MyBase
{
    return null;
}

//Then, change this to:
test.GetRetValT<MyDerived1, MyBase>


Why cannot I read a file line by line in a Perl script?

Question: I have a Perl script, which has to read a file line by line.
Line in the file:
0060|9592014|A001-9592014-0060|82769|NOVARTIS PHARMA SERVICES AG        BASEL|51671|NOVARTIS AG|A+|SWITZERLAND|Guarantees Issued|12/31/2016|12/31/2016|0|0|0|0|0|0|0|0|0|29014.0967835279993469339764885601502052|0||||0|1|550.3648|32541||.32|SUIG|OLEG|AAA||||||END|

I need to get only 32 fields, the first 32.
open (PRISM, "$infile") or die "Can't open $infile\n";
while (my $file_line = <PRISM>)
{
  last if ($file_line=~/^PRISMEXP/);
  next if ($file_line=~/^(\s)*$/);  # Skip blank lines
  print "LINE: $file_line\n";    # This line doesn't print anything
  my @field = (split /\|/, $file_line[0-32]);
  print "$field[0]\n";  #This line doesn't print anything
}

And as you can see, this part of code doesn't read the file and doesn't print anything. Why? Where is my mistake?
Comment: If this is a proper csv file, you might be best off using `Text::CSV` to parse it.
Comment: If you had `use strict` turned on, you could never have made this mistake. The statement `$file_line[0-32]` is -- besides not being an array slice --  trying to take a value from the *array* `@file_line`, which does not exist. Which `strict` would have told you.
Comment: What's the content of `$infile`? If the first line begins with `PRISMEXP` you will never print anything.
Answer: Where you have WHILE you should have while.
Also, your blank line check should have =~, not =.
Your split uses $file_line[0-32] is the same thing as $file_line[-32], which is the 32nd element from the end of @file_line, but you haven't set that array anywhere; I'm guessing that should be substr($file_line,0,32).
Or, if you only want the first 32 fields, it should be:
my @field;
@field[0..31] = split /\|/, $file_line;

Always use use strict; use warnings;. It would have caught the last error, and likely the second error too.
Comment: I have while, I corrected it. reading is not working
Comment: I did it, still not working. Should I use $_ ?
Comment: @TLP: How is `0-32` interpreted as  `-2`?
Comment: @ikegami Yes, I ran some test code where I used `0 - 2`, after which I edited the comment, hence the mistake. I will delete my comment as well.
Answer: Here are some notes on your program that should help you improve your success rate

Always use strict and use warnings at the top of every Perl program, if you haven't done that already
Use lexical file handles, like my $prism_fh instead of global bareword file handles like PRISM
Don't put scalar variables inside double quotes. At best it will make no difference, and at worst you will get a completely different string
Always put the $! variable in your die string when checking the status of open calls. It will tell you why the open failed. Also, perl will add the source file name and line number to the output of die unless you put a newline on the end of your string, so don't do that if you want to know where in your code the error occurred
It is often better to use the default variable $_ when reading from a file. Many operators use it as their default parameter, making for more concise and tidy code
Don't forget unless. You can more cleanly check whether a line contains non-blanks by using next unless $file_line =~ /\S/
If you don't chomp the input lines then there is no need to put a newline on the end when you print the output
You need to split lines before you can select fields from the input $file_line[0-32] isn't valid Perl

Here's your Perl code refactored so that it prints the first 32 pipe-separated fields. I hope it is obvious that it needs a preamble that does use strict and use warnings and defines $infile.
open my $prism_fh, '<', $infile or die qq{Can't open "$infile": $!\n};

while (<$prism_fh>) {
  next unless /\S/;
  last if /^PRISMEXP/;
  chomp;
  my @fields = (split /\|/);
  print join('|', @fields[0 .. 31]), "\n";
}

output
0060|9592014|A001-9592014-0060|82769|NOVARTIS PHARMA SERVICES AG        BASEL|51671|NOVARTIS AG|A+|SWITZERLAND|Guarantees Issued|12/31/2016|12/31/2016|0|0|0|0|0|0|0|0|0|29014.0967835279993469339764885601502052|0||||0|1|550.3648|32541||.32

Update
Instead of splitting and recombining, you could use a regular expression to grab the first 32 pipe-separated fields, like this
while (<$prism_fh) {
  next unless /\S/;
  last if /^PRISMEXP/;
  chomp;
  print $1, "\n" if /^((?:[^|]*\|){31}[^|]*)/;
}

The output is identical to that of the program above.
Comment: @G.Cito: It shouldn't matter which is faster unless one of them is too slow for your needs. You should choose the solution that is most clear to you.
Comment: Another excellent response thanks for your contributions!  I'm assuming the regexp version here is faster because it avoids two function calls (`split` and `join`) which are higher overhead for the compiler compared to the super optimized regex engine.
Answer: Because of the line:
last if ($file_line=~/^PRISMEXP/);

If the first line of $infile begins with PRISMEXP you will never print anything.
You have also to change the line:
my @field = (split /\|/, $file_line[0-32]);

to:
my @field = (split /\|/, $file_line)[0..32];

Comment: I have 100 lines pipe delimeter in the file, which I open and try to read from the file line by line using only 32 fields (32|333|ee and so on. All amount of fields are 44. I need only first 32.
Comment: when I print $_, it works. Now I have to cut only 32 fields.How can I do it?
Comment: @user2843135: Edit your question and add an extract of your input file.
Comment: Thanks a lot all of you. I will use it. The only problem is that I only change the existing program, made 15 years ago, and the boss doesn't want to change what is working  very long time. But thank you anyway. Everything was very helpfull.


TypeError seneca indexof if not a function during respond

Question: I have written a simple action which connects to mongo db using seneca-mongo store module, execute a list query and get the results. I can see that the query was successful and the correct results were fetched. When I try to send these results back to the client, the respond call errors out with following message and stack trace.
ERROR       act     root$           OUT             cmd:getparams,role:diff 11      {cmd:getparams,role:diff,payload:{id:scalaScan}}    ENTRY    (dqk22) -       seneca: Action cmd:getparams,role:diff callback threw: k.indexOf is not a function.     act_callback    {message:k.indexOf is not a function,pattern:cmd:getparams,role:diff,instance:Seneca/0.7.2/d0twcki9cmxg/1485517      TypeError: k.indexOf is not a function
    at /scratch/DiffAnalyzer/node_modules/seneca/node_modules/seneca-web/web.js:851:13
    at Function.forEach (/scratch/DiffAnalyzer/node_modules/lodash/dist/lodash.js:3298:15)
    at Object.defaultmodify [as modify] (/scratch/DiffAnalyzer/node_modules/seneca/node_modules/seneca-web/web.js:850:7)
    at respond (/scratch/DiffAnalyzer/node_modules/seneca/node_modules/seneca-web/web.js:654:22)
    at Seneca.<anonymous> (/scratch/DiffAnalyzer/node_modules/seneca/node_modules/seneca-web/web.js:401:7)
    at act_done (/scratch/DiffAnalyzer/node_modules/seneca/seneca.js:1554:16)
    at /scratch/DiffAnalyzer/node_modules/gate-executor/gate-executor.js:127:20
    at Seneca.<anonymous> (/scratch/DiffAnalyzer/analyze.js:613:5)
    at act_done (/scratch/DiffAnalyzer/node_modules/seneca/seneca.js:1554:16)
    at /scratch/DiffAnalyzer/node_modules/gate-executor/gate-executor.js:127:20
    at /scratch/DiffAnalyzer/node_modules/seneca-mongo-store/mongo-store.js:329:21
    at /scratch/DiffAnalyzer/node_modules/mongodb/lib/mongodb/cursor.js:271:33
    at /scratch/DiffAnalyzer/node_modules/mongodb/lib/mongodb/cursor.js:778:35
    at Cursor.close (/scratch/DiffAnalyzer/node_modules/mongodb/lib/mongodb/cursor.js:1009:5)
    at Cursor.nextObject (/scratch/DiffAnalyzer/node_modules/mongodb/lib/mongodb/cursor.js:778:17)
    at Cursor.each (/scratch/DiffAnalyzer/node_modules/mongodb/lib/mongodb/cursor.js:264:12)

The action that I have written is
seneca.add("role:diff,cmd:getparams", function(msg, respond) {
    seneca.ready(function() {
        var collection = seneca.make$("paramStore");
        var f = msg.payload;

        seneca.log.info("Filter", f);
        collection.list$(f, function(err, ob) {
            if (err) {
                seneca.log.error(err);
                respond(err);
            } else {
                seneca.log.info("Result", ob);
                respond(null, ob);
            }
        });
    });
});

The same piece of code was working and now I am getting this error. Not sure what changed. Any help/suggestions are greatly appreciated.
Answer: The issue I was facing was because of this bit of code in the module's js file
if( _.isObject( result.out ) ) {
    _.each(result.out,function(v,k){
      if(~k.indexOf('$') && 'http$' !== k) {
        delete result.out[k]
      }
    })

The _.each function is meant to parse a JSON object, where in my case the out was actually a JSON array. Wrapping the array into an object resolved it.


SSO lags behind the HTTP Module I user for security in ASP.NET

Question: We currently have an HTTP Module in our assorted web (mostly web forms) applications that handles authentication, page access, and menu construction. We are trying to introduce SSO, but are finding that we cannot predict the order in which modules (or their events) execute.  As a result, the Request Header values that SSO populates (such as username)http are often populated after our Security module initially executes.
I would hate to move the code to the master pages.  Or, I guess more accurately, into a class called by the master pages, but I don't see another reasonable option. I need something that fires AFTER SSO does its thing.
I am looking for an alternative to using a module. Something that still provides a generally centralized passthrough/hub for controlling traffic.  The only thing I have been able to come up with is a master page call, which does not let me manage non-aspx resources, but it may be the best I can do.
Comment: Possible duplicate of [How is the order of execution for HttpModules determined?](https://stackoverflow.com/questions/2427451/how-is-the-order-of-execution-for-httpmodules-determined)
Comment: I have moved way past the point where I am trying to dictate the execution order of modules. That isn't going to happen.  I am looking for an alternative to using a module, but something that still provides a generally centralized passthrough/hub for controlling traffic.
Answer: If for some reason you can't coax your modules to execute in order via config, you can force them to execute in order via code.
First, remove the problem modules from config.
Then, add a single new module to config. You will have to write this module. The module should call the other modules in the desired order. For example:
class MyModuleChain : IHttpModule
{
    private IHttpModule _module1 = new Module1();
    private IHttpModule _module2 = new Module2();

    public void Init(HttpApplication application)
    {
        application.BeginRequest += new EventHandler(Application_BeginRequest);
        application.EndRequest += new EventHandler(Application_EndRequest);
    }

    public void Application_BeginRequest(object source, EventArgs e)
    {
        //Call the modules in a fixed order
        _module1.Application_BeginRequest(source, e);
        _module2.Application_BeginRequest(source, e);
    }

    public void Application_EndRequest(object source, EventArgs e)
    {
        //Call the modules in a fixed order
        _module1.Application_EndRequest(source, e);
        _module2.Application_EndRequest(source, e);
    }

    public void Dispose()
    {
        _module1.Dispose();
        _module2.Dispose();
    }
}

You may have to implement more event handlers if they are needed by the dependent modules.
Comment: That's an interesting idea, John.  I wonder if that would force synchronous-ness onto something that IIS handles asynchronously. I will sleep on it.  Thanks for the thought.
Answer: I was trying to solve the wrong problem. I was trying to make the current Security HTTPModule work in conjunction with SSO (Siteminder).  The problem was that the existing code was designed at a time that it was both the authenticator of user identity and the authorizer of resource requests based on that identity.  Not that we are giving up that first role, we have to move our authorization code into the appropriate event -- after SSO has set the request values -- PostAcquireRequestState. Placing the authorization code there solves all of our problems.  To misquote the Bard, the fault is not in the code, but in ourselves.


Pauli-Z gate clarification

Question: In this following document:
https://people.cs.umass.edu/~strubell/doc/quantum_tutorial.pdf
Page 16 says the following about
Pauli Z gate
However the right-hand most (ket-bra) side of the equation doesn't seem to evaluate to the 2x2 matrix. Is this a typo in the document or am I doing something wrong?
<code>|1><0| = [0 0
          1 0]          ---- (1)
|0><1| = [0 1           ---- (2)
          0 0]

(1) - (2) = [0 -1
             1  0]

```
</code>
Answer: $\newcommand{\ket}[1]{\left|#1\right>}\newcommand{\bra}[1]{\left<#1\right|}$
Looks like a typo while copying from $X$ and $Y$ pauli matrices.
It should be $$\ket{0}\bra{0} - \ket{1}\bra{1}$$

Pauli-Z gate clarification


Sound indicator + control disappeared in Shell

Question: The sound indicator in the Gnome Shell panel sometimes disappears, I didn't notice any action from my side that may have triggered it. When I open the sound settings manually, I can't adjust anything either, however, the sound in general still works fine. Restarting X brings things back to normal.
Any idea how I can regain control over the sound settings short of restarting the entire system? I'm running 11.10 with Gnome-Shell 3.2.
Somebody asked the same question a couple of days ago, which was closed for being "too localized". I'm obviously not the only one affected so I can only guess that Gnome-Shell is too niche here. If so, please just close this one as well.
UPDATE: I just found that all details of my problem match the bug described in this question. Can somebody please mark my question a duplicate? Thanks a lot.
Answer: make sure you still have pulseaudio installed. Otherwise, the sound indicator will not appear.
Comment: pulseaudio is installed. This isn't a general problem with my setup but occurs rather frequently after X has been running for while. Even then, sound is still there, just not adjustable, and restarting X fixes things.


Prove that the straight line joining the middle point of the hypotenuse of a right angled triangle to the right angle is equal to half the hypotenuse.

Question: I am supposed to use the following 8 theorems only to prove the above prepositions:
Theorem 1: If a ray stands on a line , then the sum of the adjacent angles formed is $180 $deg.
Theorem 2: If two lines intersect , then the vertically opposite angles are equal.
Theorem 3: If a transversal cuts two parallel lines, then each pair of alternate angles are equal, and the interior angles on the same side of the transversal are supplementary.
Theorem 4: Lines which are parallel to the same line are parallel to each other.
Theorem 5: The sum of the three angles of a triangle is $180$deg.
Theorem 6: If one side of a triangle is produced , the exterior angle so formed is equal to the sum of the interior opposite angles.
Theorem 7: The angles opposite to equal sides of a triangle are equal in an isosceles triangle.
Theorem 8: The bisector of the vertical angle of an isosceles triangle bisects the base and is perpendicular to the base.
I tried to get the solution but could not apply theorems 7 and 8 since it is a right angle triangle. I don't use concept of rotation. I use ASA, SAS, SSS and RHS Postulates and converse of theorem 1,3,7 and 8. can anyone tell me how the proof looks like? Thanks in advance...Srikanth
Answer: in $ \triangle ABC$, $\angle B=90^\circ$, $AD=DC$

we draw $DO \perp BC$. So $BO=OC= \frac{BC}{2}$ and $DO= \frac{AB}{2} $ [midpoint theorem]
so $ BD^2=DO^2+BO^2=\frac{BC^2+AB^2}{4}=\frac{AC^2}{4}$
so $BD= \frac{AC}{2}$ (proved)
Comment: Can You please tell me how does a perpendicular drawn to $BC$ bisect it? I could figure out a common side, a right angle, I need one more parameter to prove congruence? :-)
Answer: Let $\triangle ABC$ be a right angled triangle, right angled at $B$. Therefore the hypotenuse is $AC$. Let the middle point of $AC$ be $D$. Now draw a perpendicular $DE$ on $BA$ and $DF$ on $CB$. Now note that $DE \| CB$ (converse of Theorem 3) and similarly $DF \| AB \implies DF \|EB$ (corollary from Theorem 2). Now in $\triangle ADE$ and $\triangle DFC$ we have  $1. DA=CD$, $2. \angle AED = \angle DFC$ and $3. \angle EDA = \angle FED$ (from Theorem 3). There the two triangles are congruent. Hence we get $AE=DF$. But since in quadrilateral $DEBF$ we get $DF \| EB$ and $DE\|FA$ hence quadrilateral $DEBF$ is a parallelogram and so $DF=EB$ and $DE=FA$ thus giving us $AE=EB$ making $E$ the midpoint of $BA$. Now we note that in $\triangle ABD$ we get that$DE$ is the perpendicular bisector of $BA$. Hence $\triangle ABD $ is isosceles (converse of Theorem 8). We then get $AD = DB$. Similarly by proving that $\triangle DBC$ is isosceles we get $DB=CD$. Thus the theorem is proved.
Answer: Let $ABC$ be the triangle, with $C$ the right angle. Draw parallel lines to $AC$ and $BC$, through $B$ and $A$ respectively. Say they intersect in $D$. By Theorem 3, $\angle ABD$ and $\angle BAC$ are equal. So are $\angle BAD$ and $\angle ABC$. Therefore $\triangle ABC$ and $\triangle ABD$ are equal, by $ASA$. We get that $ABCD$ is a rectangle quadrilateral. Say that $CD$ intersects $AB$ at $M$. By $SAS$ we have that $\triangle DBC$ is equal to $\triangle DAC$. Use now Theorem 3 again , and the equality of all those right-angle triangles to show that $\angle DBA$ and $\angle BDC$ are equal. This shows that $\triangle DMB$ is isosceles. Similarly it follows that $\triangle BMC$, $\triangle CMA$, and $\triangle AMD$ are all isosceles. By $SAS$ $\triangle BMC$ and $\triangle DMA$ are equal. The $M$ is the mid point of $AB$ and $CM=BM$.
Answer: Let ABC a triangle right angled at A. Then the hypotenous=BC. Now mid point of BC be D. Construct a line segment DE perpendicular to AB. We will find that AE=CE. In triangle ADC,angleAED=angleCED=90,AE=CE and DE=DE then triangle ADE congruent to triangle DEC. Then by CPCT AD=DC or qe can say that AD=half BC. Proved
Comment: http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Answer: I didn't read Theorems 1–8, but offer the following proof: The midpoint $M$ of the hypotenuse $AB$ is the center of a Thales circle with  diameter $AB$, and $MC$ is a radius of this circle.


How do I turn off the hot water so I can fix a leaking hot tap

Question: My laundry hot water tap is dripping. I want to change the washer inside the tap but I'm unsure how to turn off the hot water.
Comment: What part of the world are you in?  Single family home or is it an apartment or condo type unit?
Answer: In an ideal world, there will be an isolating valve (see below) under the sink which you just turn.

Given you are asking the question, there probably isn't.
In that case you need to follow the pipework back until you find a valve.  Places to look:

If you have a hot water tank, there may be a valve to prevent any water coming out of it.  If there is, you can use that.
(If you have a hot water tank, and have to use any of the following valves, you may have to drain the hot water tank).  Check if there is a valve to stop water flowing in to the hot water tank.
Check if there is a valve before or after the boiler.
If you have a cold water tank, there may be a valve to stop water coming out of it.
Ultimately, you may have to turn off all water to the house (and if you have a cold water tank, you will have to drain it).  You do know where the main water stop-cock is don't you?  If not, now is a really good time to find it!  (Not when there is water pouring through a ceiling.)

Depending on how far back you have to go in order to cut off the water, you might want to consider taking this opportunity to add some additional isolating valves - it's very easy.
Answer: This depends on the system and who installed it.
On a basic system, then you need to turn off the incoming water supply to the dwelling and that stops the supply to everything, then you can work on the laundry tap, water may still come out due to air getting in and gravity.
However, some systems will have an isolator prior to the tank so that the tank can be isolated leaving other things working.
Other systems will have an isolator before each tap and you can just use that - makes life very easy but not always done.
Answer: It may be that you do not have to change the "washer" in the cut-off valve. It could be that all you have to do is tighten the bonnet nut on this valve. We need to know exactly where it is leaking to tell you what to do. If it is leaking around the stem with the valve open as it would normally be if the washer was connected with a supply hose, it may be that you do not have to shut off the water to the house, but simply have to tighten a so called bonnet nut around the stem.
But if the valve is old, then it is possible that the valve needs to be disassembled for repair or even replaced with a new valve.
To open up for repair or to remove to replace any of the hot water cut-off valves, including the hot for the clothes washer, you must normally turn off the water supply valve on the input of the water heater. As long as you are working on the valve the entire house will be without any hot water. The exception to this is that some modern plumbing systems have a manifold or manifolds which allow shutting off the water selectively to certain parts of the house.
Depending on how your house is constructed this valve will be in the basement or in a box in the ground outside next to the house  or at the water meter. In my area of Dallas, Texas everyone uses the cut-off valve on the city side of the water meter in a box in the ground next to the street. The city of Dallas is aware that their valves are being used for this purpose and does not actively object.
As per the local plumbing code in original construction all houses here have a set of valves in a box in the ground next to the foundation, but the type of valve used in the 1970s (a so called "gate" valve) would corrode and become inoperable in 10 years or less. The ball valves used nowadays last much longer, maybe indefinitely.


How to automatically choose which css to use depending on the URL/website and/or server I'm on?

Question: I have a HTML widget/table that is pulling info from a private server that diplays the info I want in the selected fields using JSON/knockoutjs data-bindings from a javascript viewmodel file.  I will be putting this widget on different servers/sites.  The problem is that (as silly as it is) I need to use different CSS's depending on which site/server I'm on.  Is there a way in either HTML or Javascript to say that if I go to this website or server use this CSS or if I visit this site/server use the other CSS file I have?
If it's even possible still; maybe there's a way to say if a website url or server contains a specific word; for example: http://abcdEXAMPLEefghi.com; in this example I would check to see if the word "EXAMPLE" was in the URL and if so, use CSS2 instead of the default CSS1.
Comment: You want to do this on client side or server side ??
Comment: in javascript you could check the domain, but this would make your css dependent from javascript: so probably it's better use some kind of server side detection instead (e.g. via `htaccess`).
Comment: @F.Calderan Forgive me as I'm new to this, but since the HTML table (trying to make it an app) is talking to a server and populating it's info from it; and the client could choose which URL to visit; my guess would be to make it on the client side.
Answer: Maybe something like this?
http://jsfiddle.net/pqLVz/

hello

Comment: YES!! thank you.  I didn't need the second line in the if statement though, just the document.write(') line was needed to get the page to load the appropriate style sheet for my table.
Comment: This is a similar approach to the how the HTML5 Boilerplate approaches link to CDN hosted JQuery with fallback-to-local copy.


How to specify more than 64 mb memory for an application?

Question: largeHeapSize = true increases heap size to 64 mb. But my application requires more memory than 64 mb. I have searched and didn't found any solution. I have got this in android developers site. Is this applicable in my case or what is more appropriate?
Answer: largeHeap = "true" does not increase the heap size to or by 64 MB:

Most apps should not need this and should instead focus on reducing their overall memory usage for improved performance. Enabling this also does not guarantee a fixed increase in available memory, because some devices are constrained by their total available memory. (source, emphasis mine).

Which means using the largeHeap flag just tells Android that your app is memory-intensive and needs a larger heap. On some devices, it means it can get 200-300 MB, on others 50 MB. And that depends on the free memory.
In addition, the memory your app gets is decided by the system, so you cannot set it manually. There are no Xmx flags or similar on Android. `
TL;DR: You cannot specify a specific heap size like you can on desktop Java. Using largeHeap doesn't give a fixed amount of memory to your app; it depends on the device and available memory. And whereever possible, save memory instead of requesting more as the docs of largeHeap states (Most apps should not need this and should instead focus on reducing their overall memory usage for improved performance)


How to force Cordova to emulate release apk, rather than debug apk?

Question: cordova run --emulator

launches the debug apk, rather than the release apk.
A. I wonder why?
B. How can I solve this?
I tried to relocate the debug folder in another directory, in the hopes that this will cause the emulator to default to the release apk (which was the only one left in the apk directory) -- it didn't. The debug apk got launched from its original location as if the folder has not been moved. I'm curious about this too.
I went over the documentation and the various Q&A here and elsewhere, but I couldn't find a solution or explanation.
Comment: try cordova run --emulator --release
Answer: cordova run --emulator --release

(as suggested in the first comment) solves the problem.


Wishful thinking in Clojure

Question: In Scheme I was used to do something like this
(define (f x) (g x))
(define (g x) (+ x 42))
(g 0)

That is, I was used to define functions in terms of other momentaneously unbounded functions.
Why isn't this possible in Clojure?  For example on a Clojure REPL the following isn't valid
(defn f [x] (g x))
(defn g [x] (+ x 42))
(g 0)

Answer: the thing is every line is being compiled in repl, so there is no g function when f is being compiled. You should add (declare g) before (defn f... so the compiler would be aware of this function:
user> (declare g)
#'user/g

user> (defn f [x] (g x))
#'user/f

user> (defn g [x] (+ x 42))
#'user/g

user> (g 0)
42

Comment: @Matteo Rich Hickey gives the rationale for this behavior in [this HN comment](https://news.ycombinator.com/item?id=2467809), which basically comes down to what type of error would you like to have for undefined symbols: runtime or compile time?  Common Lisp chooses runtime error, Clojure chooses compile time error.
Comment: @CurtisSummers: Common Lisp chooses: compile-time warnings, late binding and runtime errors.
Comment: Why doesn't the REPL automatically "declare" undefined functions? Wouldn't it be easier?
Comment: CF Matthew Flatt, "The top level is hopeless." best ref I can find: http://calculist.blogspot.com/2009/01/fexprs-in-scheme.html

Wishful thinking in Clojure


How can I determine the amount of write/output buffer space left on a linux serial port?

Question: You can determine how much data is available to read from a serial port under linux using an ioctl. Is it possible to determine how much buffer space remains for the serial port when writing to it? Effectively I want to write a block of data to a serial port, succeeding only if it can all be offloaded in one go, or failing if it would have to be chunked. The writes and reads to the ports are non-blocking. I'm not expecting this to be the UARTs buffer, but the kernels memory buffer ahead of the UARTs buffer (I guess).
Comment: I *suspect* it comes down to the hardware tx/rx FIFO size, which is abstracted from you by the kernel... but does the kernel just hold it in an internal buffer when it's too much for the HW? That I do not know.
Comment: That's what I expect, so there must be some upper bound on that kernels internal buffer. A bound I was expecting to be able to retrieve.
Comment: It's likely worth re-evaluating the problem definition and considering alternative design options.  Maybe an asynchronous IO scheme would be better.  Or `open` w/`O_NONBLOCK`, look for `EAGAIN`.
Comment: Effectively I'm trying to replicate the functionality send() offers for sockets, i.e. it all goes or none goes. I'm abstracting the physical transport away from the rest of the application. The whole system is already non-blocking, so I know that the write won't block, I just don't know if it will offload all the data I want to kernel space.
Comment: Ok, so try `O_NONBLOCK`.
Comment: I don't understand - it is already ALL non-blocking. It IS O_NONBLOCK. But all that means is that I won't block, not that I can write the amount I want to write. Just using O_NONBLOCK means that the write can part-succeed, which is not a replication of sends() functionality with a socket. Spinning trying to write the rest then effectively makes the call blocking, so that's no good. Passing back   the bytes written then breaks the abstraction.
Comment: NetBSD has FIONSPACE and FIONWRITE support for tty(4) devices (as well as sockets).  I think they allow something like what you want.  Keep in mind that the kernel side of a serial port device typically has two layers, the tty(4) lower driver, and a line discipline, typically termios(4).  If you want a write to succeed in its entirety on a tty(4) device than you'll have to let it block.
Answer: You can determine the amount of write/output.
For read:
ioctl(device_handler, TIOCINQ, &bytes);

For write:
ioctl(device_handler, TIOCOUTQ, &bytes);

Size of FIFO buffer:
serial_struct serinfo;
memset(&serinfo, 0, sizeof(serinfo));
ioctl(device_handler, TIOCGSERIAL, &serinfo);
serinfo.xmit_fifo_size;

Regards,
VA.
Comment: I've used that for sockets, I didn't know it worked for any device.
Comment: the `serial_struct` needs to instead be a `struct serial_icounter_struct`
Answer: The serial port is a character device not a block device. It has no buffer.
Character devices ( such as Serial port, keyboard, mouse) only writes and reads a character not a word.
For exame if you listen to a serial someone writes " have a nice day ", if you do not listen from the time he starts typing, you would not see the entire phrase. You would see only the characters typed when you listen
Comment: But surely there's *some* buffering in there? There's the UARTs FIFOs at least. And what buffer is the FIONREAD ioctl looking at?
Comment: Yes, there is buffering, but as far as I know it could be accessible only in Kernel Mode. You have to load a module in the Kernel, to listen to the device drive
Comment: It seems strange that I can find the kernel mode buffering size for reads with the FIONREAD ioctl but there's no parallel for writes. :-P
Answer: If you access serial port using file descriptor, you can use select for checking whenever the descriptor is ready for non-blocking write. I don't know whenever this works for serial ports. I used this for TCP sockets and it worked.


How can I easily use a damaged hose bibb outlet?

Question: The threads on my hose bibb outlet are damaged and in pretty bad shape. I have not done my own plumbing work before and am wondering if there is some type of solution that would not require opening up the siding to replace the entire bibb. I'm hoping for a solution outside the box possibly so I don't need to hire a plumber although I will if necessary. As is, leaking at the connection is pretty bad if I try to use the outlet.
Answer: What about if you used a screw-on hose bib anti-siphon adapter. You could screw/jam it on along with a generous amount of 2-part epoxy putty (like J.B. Weld) and have new garden hose threads... and anti-siphon protection as a bonus!
Comment: I'd like to report back that after using this method for the past 3 months, it was completely successful. I just have to watch out for the splash of water at the end now :) Thanks Jimmy!


Saving textbox value from a test execution in Ranorex

Question: I am automating Sharepoint list testing, filling up some field with values,
and like to save data I supplied to the field after.
Is there a way to automate saving the field value in a excel or csv?
Comment: Can you clarify the source of the field data values?  Because, the answer to your question is quite simple.  Since Ranorex is based on the .NET framework, it is really easy to output anything to any type of output.  But if your data is already coming from an excel file (using an excel data connector on your test suite) or a csv file, I do not see the point of writing it to another file...
Comment: The data will come from the share point box.
For example i have some text box in a list entry in a share point site namely FirstName and LastName on execution of the ranorex i want the content of the two field to be save in a file an excel or csv and be use by other process is that possible.
Answer: In order to keep it simple, I would create two recordings and write to a text file (csv).
The first one would get the text values from the desired fields and return them in bound variables using Ranorex GetValue action.
The second recording would write the content of the bound variables to a text file, separating fields with ',' (or any other character that is suitable for the kind of data that is present in the fields) in a user code function.
If you have no idea how to write to a file in .NET, take a look at System.IO.File.AppendAllLines or similar functions.
You could also combine the 2 recordings in one, but then, re-useability would be limited the scope of the SharePoint page you are testing.
Do not forget that since Ranorex is using the .NET framework, you have access to all the functions provided by the framework in user code.  With Ranorex, the usual question is not ask if something is possible. The real question is "how can it be done" and is the solution simple enough for testers to be able to use it!
Hope this helps!


PHP form contact, with checkboxs, error 500

Question: Can anybody help me! This php doesn't work in my web, doesn't send email, if i change die(error), the page say to me that..

There is de php action
    <?php
$name = $_POST['name'];
$lastname = $_POST['lastname'];
$email = $_POST['mail'];
$Title = $_POST ['position/title'];
$company = $_POST ['company'];
$location = $_POST ['location'];
$telephone = $_POST['telephone'];
$services = $_POST['services'];
$string = join(" \r\n ", $services);
$timeframe = $_POST['timeframe'];
$comments = $_POST['comments'];
$learn = $_POST['learn'];
        $message = '';
        $message .= '';
        $message .= '
';
        $message .= "
Name: 	" . strip_tags($_POST['name']) .  "
";
         $message .= "
Lastname: 	" . strip_tags($_POST['lastname']) . "
";
        $message .= "
Email: 	" . strip_tags($_POST['mail']) . "
";
         $message .= "
Title/Position: 	" . strip_tags($_POST['position/title']) . "
";
        $message .= "
Company: 	" . strip_tags($_POST['company']) . "
";
        $message .= "
Location: 	" . strip_tags($_POST['location']) . "
";
         $message .= "
Services: 	" . join(" \r\n, ", $services) . "
";
         $message .= "
Timeframe: 	" . strip_tags($_POST['timeframe']) . "
";
         $message .= "
Learn about Corbis: 	" . strip_tags($_POST['learn']) . "
";
        $message .= "
Comments: 	" . strip_tags($_POST['comments']) . "
";
        $message .= "
";
        $message .= "";
$recipient = "email@example.com";
$subject = "Contact Form from CorbisGlobal Web";
$mailheader .= "MIME-Version: 1.0\r\n";
$mailheader .= "From: " . strip_tags($_POST['mail']) . "\r\n";
$mailheader .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
mail($recipient, $subject, $message, $mailheader) or die (error);
header("Location: thankyou.php");
exit;
?>

Comment: A 500 error = Server error (probably some PHP error). Check your error log or turn display errors on and you will get a proper error message you can share with us. Here you can see how to turn it on: http://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display
Comment: Btw, why are you storing all the post values in variables, and then use the post variable directly anyway, later on?
Answer: Your error is probably on the middle row:
$subject = "Contact Form from CorbisGlobal Web";
$mailheader .= "MIME-Version: 1.0\r\n";
$mailheader .= "From: " . strip_tags($_POST['mail']) . "\r\n";

You didn't create the variable $mailheader before you're adding more text to it.
Turn error reporting on and you'll have meaningful error messages that will help you solve most of your problems.
Also, you're doing this:
mail($recipient, $subject, $message, $mailheader) or die (error);

or die (error), you probably didn't define the error constant, and there is no variable with this name in the code you have shown us. To check if the mail function has accepted your input, you can do this:
if (mail($recipient, $subject, $message, $mailheader)){
    header("Location: thankyou.php");
}
else{
    die("Error sending email");
}

Comment: I mean, you're sending `$services` as the second param in your `join()`-call. If that's not an array, you will get the error you just showed. `join()` is an alias for `implode()`.. here's the manual for it: http://php.net/manual/en/function.implode.php
Comment: Yes, this is probably it (assuming the OP didn't omit this)
Comment: I seriously doubt that would lead to a http 500 error.
Comment: There is also a problem with his "or die" function, I have added it to the answer.
Comment: When turn on the errors, appear that:

Warning: join(): Invalid arguments passed in /srv/www/corbis-www/mail.php on line 12

Warning: join(): Invalid arguments passed in /srv/www/corbis-www/mail.php on line 30
Error sending email

When i delet this line.. Die.. error sending email...
Comment: Don't forget the `exit;` after the `header('location: ...');` (that will probably not fix your error, but you should always have an `exit;` after a redirect-header.)
Comment: @EmilianoMaza - Does `$_POST['services']` actually contain an array?
Comment: it's stranger that, if a test in other server the same code, it's works... http://emilianomaza.com.ar/contact-form-corbis/contact.php

@MagnusEriksson you mean form code? nop


Using reflection to create object with parameters in constructor

Question: I can not understand the following code:
Constructor<T>[] constructors = (Constructor<T>[]) clazz.getConstructors();
for(int i = 0; i < constructors.length; i++){
  Constructor<T> constructor = constructors[i];
  if (constructor.getParameterTypes().length>0){
    T instanceObject = constructor.newInstance(new Object[constructor.getParameterTypes().length]);
        break;
  }

}

Have omitted try/catch and other stuff for clarity.
I can not understand how this works: T instanceObject = constructor.newInstance(new Object[constructor.getParameterTypes().length]);
It calls a constructor that has parameters, but passes as arguments Object?
How does this work? Passing Object independent of the actual formal parameters?
Comment: you need all arguments to be non-primitive and the c-tor to make sense w/ having all parameters null
Comment: @bestsss:`Individual parameters are automatically unwrapped to match primitive formal parameters` from Javadoc
Comment: Jim, except null is unwrapped to NPE. I know the spec and even the impl, really no need to quote. The unwrapping is simple: `Integer.intValue()`, `Double.doubleValue()` - hence the NPE.
Answer: It attempts to pass dummy parameters which are all null. This can give you an Object but it doesn't mean it will be a useful one. ;)
I am not sure why it skips zero length constructors as this is the one constructor you are likely to be able to pass no arguments successfully.
Comment: I mean it won't even get to the c-tor. Of course, any arbitrary data can lead to errors but at w/ primitives the c-tor won't even be invoked.
Comment: also can lead to NPE if any of the arguments are primitive
Comment: it could lead to an NPE even if the arguments are not primitive but expect you to pass it something. ;) I assume the outer loop catches exceptions and keeps trying if it gets one.
Answer: An array of objects with number of elements equal to number of parameters in the constructor, hence:
new Object[constructor.getParameterTypes().length])


CircularProgressIndicator not stopping while moving back

Question: Created a demo for understanding future..
I have taken two screen....Using Future.delayed I am forwarding to next screen in 5 seconds with CircularProgressIndicator...but when I move to back..it still showing CircularProgressbar...
What should I correct my code?
here is my code

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  bool isloading = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Async demo'),
      ),
      body: isloading == true
          ? Center(child: CircularProgressIndicator())
          : Center(
              child: TextButton(
                child: Text('Pressed'),
                onPressed: () {
                  setState(() {
                    isloading = true;
                  });

                  Future.delayed(Duration(seconds: 5), () {
                    Navigator.of(context)
                        .push(MaterialPageRoute(builder: (context) {
                      return NextScreen();
                    }));

                    isloading = false;
                  });
                },
              ),
            ),
    );
  }
}

Answer:
What should I correct my code?

Wrap the second assignment of isloading to false inside setState (just as you did when setting to true). Something like the following:
onPressed: () {
  setState(() {
    isloading = true;
  });

 Future.delayed(Duration(seconds: 5), () {
   Navigator.of(context).push(MaterialPageRoute(builder: (context) {
    return NextScreen();
  }));

    setState(() {
      isloading = false;
    });
  });
},

Answer: you need to use setState when you are assign variable = false
For that do as below
replace this
isloading = false;

with
 setState(() {
           isloading = false;
    });


Delete a map>

Question: Guys I am having a problem implementing the destructor of my class that has a map<int,list<Arestas*>>.
Using this map as a sample:
My map will look like this:
key   list
[1] - [2,10] -> [3,100] -> [4,25]
[2] - [1,10] -> [3,50]
[3] - [2,50] -> [1,100] -> [4,40]
[4] - [1,25] -> [3,40]

My Arestas class contains:
class Arestas {
private:
    Fronteira *vertice;
    unsigned int custo;
}

My destructor right now looks like this:
for (auto it = myGrafo.begin(); it != myGrafo.end(); ++it) {
    for (auto it1 = (*it).second.begin(); it1 != (*it).second.end(); ++it1) {
        delete *it1;
    }
    (*it).second.clear();
}

But is giving me this Error when I go for the list from key[2]:
_CRT_SECURITYCRITICAL_ATTRIBUTE
void __CRTDECL operator delete(void* const block) noexcept
{
    #ifdef _DEBUG
    _free_dbg(block, _UNKNOWN_BLOCK);
    #else
    free(block);
    #endif
}

Thank you in advance!
EDIT
I insert in my map the Arestas* like this:
Arestas *aux = new Arestas();
        aux->setCusto(_custo);
        aux->setVertice(encontrarFronteira(vertice_destino));
        // Se o vertice nao existir
        if (aux->getVertice()->getVertice() == NULL) {
            cout << "ERROR" << endl;
            exit(1);
        }
        myGrafo[vertice_origem].push_back(aux);

        // Put the same path in the opposite vertice
        Arestas *aux1 = new Arestas();
        // set cost
        aux1->setCusto(_custo);
        // it looks for the vertice in the list<vertices*>
        aux1->setVertice(encontrarFronteira(vertice_origem));
        myGrafo[vertice_destino].push_back(aux1);

Comment: It is @AdamZahran I already solved the problem thanks to all of you ! Thanks !
Comment: @user4581301 Thanks for all the tips I'll pay more attention to the Rule of Three from now on!
Comment: Look up at comment 2. It asked for the MCVE as well suggesting you remove the image. Note how none of the answers really answered your questions outright. They mostly suggested places for you to look, because the question cannot be answered properly as written.
Comment: We're not downvoting you, at least I hope people aren't. We're downvoting the question. Good (complete and original) questions generally get upvoted. Marginal questions generally get left alone, bad questions get downvoted. Looks like this one got one downvote and two closevotes. That's not too bad, really. Some sink to -10 and are closed and deleted within a minute, but those are usually *Gimmie teh coedz!!!* questions or questions that are duplicated many times every day like, *Why does `++i + i++` not equal 3?*. You provided enough for good, guided guesswork and got an answer. That's a win.
Comment: More data required. Something bad is happening, but it probably happened long ago and the program is really only realizing it during the destructor. For example, a [Rule of Three](https://en.cppreference.com/w/cpp/language/rule_of_three) violation resulting in a double delete. Question: Do you have a strong reason for storing `Arestas*` in the list? Eliminating the pointer should make the issue of destruction pretty much moot.
Comment: Clarifying: The destructor looks good. We need a [mcve] and I recommend adding the text of any reported error message to the question along with it. And remove the code image. They don't do anything for you except attract downvotes.
Comment: Hi, I am guessing that the last piece of code you posted which you're calling an error, is where the debugger breaks when you're trying to run this application. And I am guessing that your program is crashing somewhere while it's freeing some memory. It is really difficult to know what's going on without an example. Could you create a [MCVE](https://stackoverflow.com/help/mcve)? That will help us see what's wrong. Also what does the destructor of `Fronteira` look like?
Comment: @user4581301 Hey! Yeah I really need to use that Arestas* class. I think the problem is that in the list key[1] when I delete the Aresta* with [3,100] when I go for the list of key[2] and I try to delete the Aresta* [3,50] appears that as nothing there. But I don't know how to work it out. Is there a way in C++ to know if a pointer as already deleted ? Thanks
Comment: Sorry for being unclear. Using the class is a must. Do you need a pointer to the class? Library containers like `map` and `list` are at their best when they contain objects directly. They are almost always faster, too.
Comment: There is no easy way to know if a pointer has previously been deleted. It's up to the programmer to ensure that the allocation is not freed more than once. If you must use pointers, look into guaranteeing ownership with [Smart Pointers.](https://en.cppreference.com/w/cpp/memory)
Comment: @user4581301 Sorry, already edit it out. Thanks for the tip ! I did the whole project around the pointer because I can change it in multiple functions, I don't know if it makes sense. But if there's no way of resolving this way I ll need to work it out without using the pointer as you say!
Comment: @AdamZahran My ´Fronteira` destructor doesn't have nothing in it since none of the variables inside it are alocated dinamically. But I can provide the Fronteira Class aswell if you need. In the error doesn't give me any in the console, just when I run it with a debugger so that Error that I put in my question is when it breakpoints as you said.
Comment: [mcve] required to give more than general suggestions, and I've given al the good general suggestions I can think of. Make certain you've handled the Rule of Three correctly.
Comment: is `custo` a unique id?
Comment: Post your [MCVE] to continue.
Comment: Don't write the answer in the question.
Comment: *I was trying to delete the same `vertice*` in another `Aresta*`* `std::shared_ptr` might be the tool of choice here.
Comment: @LightnessRacesinOrbit sorry, didn't know I couldn't right it in the question ! Already edit it out.
Comment: My closevote is because the question is incomplete, specifically lacks a [mcve]. Get used to doing stuff like the MCVE. It's not for us; crafting a MCVE almost always helps you find the problem without any outside help. If you make a MCVE before you ask, odds are good you won't have to ask.
Comment: @user4581301 but why not do like you did before, and said like don't use images in code, or something instead of downvoting ? I think it helps more people than just put a document. It's more friendly you know ? I will make sure to make a MCVE before I ask my next question ! Thanks
Comment: I totally understand that @user4581301 and I do understand the utility of MCVE, but I got my problem solved without that this time. Now I have to make sure I use MCVE. The problem is if you downvote me when it will be the next question ?
Comment: @user4581301 see that couple of words made me want to make good questions using MCVE. Thanks dude !
Answer: Seems like you have an issue with the ownership of your structures. You had these arestas several times in your lists, and it's undefined behavior to delete them several times, so you need to delete them just once.
Try something like this:
std::set<Arestas*> s;

for(const auto& p1: m)
{
    for(const auto& el: p1.second)
    {
        s.insert(el);
    }
}

So you create a set of all the elements you need to delete. And then you delete them (works also with unique pointers, a better solution actually).
for(auto p: s)
{
    delete p;
}

It seems that your Arestas may be unique, so the problem could lie in Arestas destructor if the vertice are shared and destroyed there.
Comment: How do you guarantee the uniqueness of Arestas pointers in that set? if two pointers point to the same object, they're not the same and the set will still take them in.
Comment: Yeah that `vertice` is the same in all the `Arestas*` like [3,100] and [3,50]. And that is the problem, I was wondering if I could delete all the vertices after I deleted my map. I don't know if I maked my self clear.
Comment: Thanks Matthieu, after looking at my code the problem was on Arestas destructor.
Comment: In the example given there was no commonality between the lists.
Comment: Ok @LightnessRacesinOrbit I don't know what to say, how was it like your first question in stackoverflow ? Did you have someone like you in all of the comments saying that you did a bad question ? Even tough a lot of people got the answer right ?
Comment: @LightnessRacesinOrbit ahaa I see, the edges are unique. OK, that makes sense now.
Comment: @diogofalken No because I read the site's instructions before posting
Answer: First of all, you only can delete objects previously created with new statement.
If so, in order to avoid multiple calls to delete, you could use a smart pointer like std::shared_ptr<Aresta>.
You could execute your code with Valgrind to get a more specific trace of this problem.
Comment: Hey, thanks for the help. I am not sure if I can use this smart pointer because I am doing this project for my OOP class. And since I never learned it in class, I am not allowed to use it.
Comment: Are you creating `vertice` with new too?
Comment: Multiple frees are unlikely to be the problem since all the list elements across the map are unique. Possibilities include never dynamically allocating in the first place but we simply do not have enough information to know.
Comment: @LightnessRacesinOrbit Yeah sorry for the lack of information, but since is a school project I can't really publish all my code. But the problem was in the destructor of the `Aresta`. Thanks !
Comment: @diogofalken You need to have some way to understand when your objects are owned and when they're not owned. One possibility is to have a link count in the object. When you delete a link, decrement the link count. If the link count reaches zero, delete the object. This can be made elegant by having the link be an object whose constructor increments the count and destructor decrements it.
Comment: @diogofalken You're welcome. It might be overkill for your particular issue, but it's a good technique to know. A very important general concept is that you really need to think about who owns what objects and what is responsible for cleaning them up and how it will know when to do that.  If you haven't already, you'll soon learn to use things like `unique_ptr` and `shared_ptr` to make this easier in many cases.
Comment: I am not sure if I am going to learn about that type of pointers but I will learn for my self. Since it looks like it will make easier to use pointers ! Thanks @DavidSchwartz

Delete a map>