text:
Q: Can someone formulate a clear description of the ending of Limbo? I had seen the ending of Limbo, but at the time was distracted so I didn't catch the subtlety.
I just watched it again here.
I have some ideas about what the ending implies, but wanted to know if anyone could formulate a clear description of "What just happened?"

A: I think the two of them are dead. Ever realize how after the credits roll there are two sets of flies buzzing over two separate spots on the ground? Those are the bodies of the brother and sister. I personally think that they fell out of their tree-house and both landed in a different part of Limbo. The sister got there first, and it looks like she's burying her body, or her brother's body. Notice how when you find her it's really bright and the tree-house looks nice? In the title menu, the tree-house is old and broken.
That's what makes Limbo so amazing. The game leaves the ending so open that I don't think there's really a wrong guess as to what ACTUALLY happened to the brother and sister.

A: I don't think there is an agreed upon meaning, but an interesting article discussing several theories can be found here.
Edit with summary as per @tzenes request:
The main theories the article mentions are as follows

*

*It is simply a happy ending, and the boy is reunited with his sister

*They are both dead and needed to meet up before entering the afterlife

*They are both alive, but are trapped and doomed to die a slow death of starvation.

*It was a dream and he woke up and found her alive

*Only the boy is dead, and the sister is surprised to discover he is dead

*They both died at the treehouse, but were lost in Limbo, the between of this world and the after life. When they met they went to the after life and their bodys remaind cover with flyes

A: I think they are both just trapped in an endless cycle because the sister killed you the first time. It ends the same way it starts.

A: I think that they fell out the tree house and the sister landed first. And at the end if you look past where the sister is sitting theres the ladder and then a big tree with wooden "steps" on it...It also leads me to thinking its a Tree House because at the end Menu if you look up and on the branch it seems to be a broken down structure.
Its clear that they are dead because for one at the end the flies flying around where the boy was standing and also where the girl was sitting and burying. :/ T
I don't think it could have been a dream, because the title of the game is "Limbo" and Limbo is the place IN BETWEEN Heaven and Hell. So i think they had to reunite and be together before finally being set to peace..


text:
Q: Given that the system works, compute the probability that component is working. Suppose the diagram of an electrical system is
as given in Figure 2.10. What is the probability that
the system works? Assume the components fail independently

I got the answer for the probability of all the system works and it is $0.8037$
but there is another question.
Given that the system works, compute the probability that component B is working.
I am not sure about this one. But
is the calculation like this?
$$
P(A \cup B \cup C \cup D)/0.8037
$$
or
only $P(A \cup B \cup D)/0.8037$ since we are only talking about B is working given that the system works.

A: The system is: $\rm A\cap(B\cup C)\cap D$ with:   $\mathsf P(A)=0.95\\\mathsf P(B)=0.7\\\mathsf P(C)=0.8\\\mathsf P(D)=0.9$
When given that the system works, we know components $\rm A$ and $\rm D$ must do so, and that at least one of $\rm B$ or $\rm C$ does too.
So: $\mathsf P(B\mid A\cap(B\cup C)\cap D)=\mathsf P(B\mid B\cup C)$
The question is then: find $\mathsf P(B\mid B\cup C)$.

Because component failures are independent: $$\begin{align}\mathsf P(B\mid A\cap (B\cup C)\cap D) ~=~& \dfrac{\mathsf P(B\cap A\cap (B\cup C)\cap D)}{\mathsf P(A\cap(B\cup C)\cap D)} \\=~& \dfrac{\mathsf P(A\cap B\cap D)}{\mathsf P(A\cap(B\cup C)\cap D)} \\=~& \dfrac{\mathsf P(A)~\mathsf P( B)~\mathsf P( D)}{\mathsf P(A)~\mathsf P(B\cup C)~\mathsf P(D)} \\=~& \dfrac{\mathsf P(B)}{\mathsf P(B\cup C)} &\bbox[ghostwhite]{\color{ghostwhite}{=~\dfrac{\mathsf P(B)}{\mathsf P(B)+\mathsf P(C)-\mathsf P(B)~\mathsf P(C)}}}\\=~&\dfrac{\mathsf P(B\cap(B\cup C))}{\mathsf P(B\cup C)} \\[2ex]\therefore \mathsf P(B\mid A\cap (B\cup C)\cap D) ~=~& \mathsf P(B\mid B\cup C)\end{align}$$

A: If components are in serial (e.g A & B), all must work in order for the system to work.
If components are in parallel (e.g B & C), the system works if any of the components work.
Segment 1: P(A) = 0.95
Segment 2: 1 - P(B') x P(C') = 1-0.3 x 0.2 = 0.94
Segment 3: P(D) = 0.9
Probability entire system works = Segment 1 x Segment 2 x Segment 3
Probability entire system works =  0.95 x 0.94 x 0.9 = 0.8037

redpajama_set_name: RedPajamaStackExchange


text:
Q: form submit on each button click My code is
<form action="test.php" name="test">
<?php foreach($result as $res)
{
 ?>

  <?php echo $res->name;?>
    <input type="text" name="<?php echo $res->val;?>">
    <input type="submit" value="submit" />

<?php }
?>
</form>

I need the same action for each submit button, whenever user clicks on it the action test.php should be called.
I have tried like this but it doesn't work. Please help.

A: For each submit, you need a different form. Here you go:
<?php foreach($result as $res)
{
echo "<form action=\"test.php\" name=\"".$res->name."\">";
 ?>

  <?php echo $res->name;?>
  <input type="text" name="<php echo $res->val;?>">
  <input type="submit" value="submit"

<?php
echo "</form>";
 }
?>

A: First of all, take a look at alternative syntax for control structures.


text:
Q: Running NUnit tests with Gallio I'm trying to write some NUnit tests for a project. I add a new Class Library to the solution. Is this the correct project type?
I added a reference:
using NunitFramework;

and added my tests.
I have Gallio installed, but I'm unsure about whether it's configured properly. I'm new to using this, and I'm hoping someone can tell me how you actually run the tests.
It was my understanding you could right click and select run all tests. Alternatively I thought you could click on the [Test] attribute and click run or debug.
Alternatively, how do I load tests into the Test Results window to run debug them?

A: Basically it's correct. Your unit test should look like this:
using System;
using NUnit.Framework;

namespace Demo
{
  [TestFixture]
  public class SampleTestFixture
  {
      [Test]
      public void SampleTest()
      {
         // my test here...
      }
  }
}

Compile your test project (a class library is OK) in debug mode. Now you can run your test suite within any runner that supports NUnit:

*

*Any Gallio test runner (Echo, PoSh snap-in, Icarus, etc.) There is a nice tutorial explaining how to use the Gallio test runners here. The examples use MbUnit instead of NUnit, but it's all the same.

*The built-in NUnit GUI or console runner.

*The built-in VS test runner (interfaced by Gallio) if your version of Visual Studio includes the MS testing tools. You should be able to see your tests in the test tool window, but there is a nasty trick to make VS recognize your project as a test project if you did not create it initially as such.

*You can also use TestDriven.Net which is lightweight and fast test runner that comes as an add-in for VS. IMHO, it's certainly the most simple and efficient way to run your unit tests directly from the VS IDE.


text:
Q: Stub ODATA service We will be building a Java/JS client that reads data from a server through ODATA.
What will be the easiest way to setup a stubbed ODATA server for our development and testing purposes. In the REST world I would have gone with MounteBank. Even this is doable using mountebank, only issue will be that i have to hard code all possible queries as a separate endpoint.
Is there a simpler way to do this?

A: After some research, figured out these two options.

*

*https://github.com/TossShinHwa/node-odata
This supports v4.

*https://github.com/htammen/n-odata-server
This supports v2.
The downside of both these libraries is that they don't support all the ODATA functions. But, decent enough to start with.


text:
Q: Why is my while loop stucked? I want to replace two (or more) line breaks in a textarea but Its always got stucked in an infinty loop
here it is:
var dateinput = document.getElementById("date");
var intIndexOfMatch = dateinput.value.indexOf('\n\n');

while (intIndexOfMatch != -1){
    dateinput .value = dateinput .value.replace('\n\n', '\n');

}

A: because you haven't changed intIndexOfMatch
var dateinput = document.getElementById("date");
var intIndexOfMatch = dateinput.value.indexOf('\n\n');

while (intIndexOfMatch != -1){
    dateinput .value = dateinput .value.replace('\n\n', '\n');
    intIndexOfMatch = dateinput.value.indexOf('\n\n');
}

better solution though
var dateinput = document.getElementById("date").value.replace(/\n{2,}/g, '\n');

that replaces your WHOLE code, by the way


text:
Q: How to change Android Oreo launcher icon daily? On Android Oreo, the icon of Google Calendar is always updated with the current month day (for example today is 2018-02-09).

Is this feature avaiable to all developers? For example, I would like to change the launcher icon for monthly paying users and freemium users.


text:
Q: Can i list possible source types as ones not available? I have this code currently:
NSArray *mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:imagePicker.sourceType];
imagePicker.mediaTypes = mediaTypes;

But it's causing this leak:
figremote_createpropertylistfrombinaryplistdata

And somebody said to replace it with this:
CFStringRef mTypes[2] = { kUTTypeImage, kUTTypeMovie };

CFArrayRef mTypesArray = CFArrayCreate(CFAllocatorGetDefault(), (const void**)mTypes, 2, &kCFTypeArrayCallBacks);

imagePicker.mediaTypes = (NSArray*)mTypesArray;

CFRelease(mTypesArray);

The problem is, some devices won't have a movie mode. Would it cause a problem if i allowed that mode and it wasn't available?

A: As far as I know there are no devices who do not support video mode exclusively. If a device does not support video mode, it will not support the camera at all. My advice would be to check if the device supports camera at all. In such case, the following code will do.
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
    NSLog(@"Device supports camera");
} else {
    NSLog(@"Device does not support camera");
}


text:
Q: JQuery sends multiple request while clicking submit button multiple times I have a code in code-igniter project.
Where I'm sending a query to controller ,
It should execute only one time . But when I click multiple times on submit button , it adds the same product which is got from jquery multiple times.
For example, I chose a product "phone" which costs $5 . When I click submit button , 3 times it adds 3 "phone" product and it costs $15 .
I tried to disable to "add-to-cart" button , tried to hide it when clicking,
But it takes so much of time to load.
Here's my code .

$(document).ready(function(){
    var n = 0;
    $( "#add-to-cart" ).one( "click", function() {
        var index = $( "#add-to-cart" ).index( this );
        $( this ).css({
            borderStyle: "inset",
            cursor: "auto"
         });
    });
});
<input id="add-to-cart" type="submit" value="ADD TO CART">

A: Have you tried to declare a control variable and check its state when you add to cart?
var added = false;
$(document).ready(function()
{
    var n = 0;
    $( "#add-to-cart" ).one( "click", function()
    {
      if (!added)
      {
          var index = $( "#add-to-cart" ).index( this );
          $( this ).css({
              borderStyle: "inset",
              cursor: "auto"
          });
          added = true;
      }
    });
});


text:
Q: Mutate Array of ActiveRecord objects and update in single transaction? What is the preferred way to update an entire array of ActiveRecord objects in a single transaction?  Assume there is a lot of processing in the loop.
@items = Item.all

@items.each do |i|
  i.name = somethingDynamic()
end

#Commit @items to DB in single transaction

A: You can simply wrap the entire loop within a transaction:
@items = Item.all

ActiveRecord::Base.transaction do
  @items.each do |i|
    i.name = somethingDynamic()
    i.save!
  end
end

A: You can start a transaction explicitly with ActiveRecord::Base.transaction like this:
Item.transaction do
  @items.each do |i|
    i.name = something_dynamic()
    i.save!
  end
end

This will run a bunch of UPDATE items set name = x statements within one transaction, and roll the transaction back on the first failure (since save! will throw an exception).
If you want to do something that doesn't require a bunch of update statements, you can do one update statement with raw sql like this:
 `@items.update_all("name = sql_func(name)")`


text:
Q: Q-value in APD photodetector I try to calculate the Q value of APD photodetector with these parameters:
$$R \hspace{0.1in} (response) = 1$$
$$M \hspace{0.1in} (magnification) = 10$$
$$k \hspace{0.1in} (ionization \hspace{0.1in} constant) = 0.1$$
$$N_{th} \hspace{0.1in} (noise \hspace{0.1in} density \hspace{0.1in} of \hspace{0.1in} thermic \hspace{0.1in} current) = 12 \hspace{0.1in} pA/\sqrt{Hz}$$
$$P_1 \hspace{0.1in} (optical \hspace{0.1in} power \hspace{0.1in} of \hspace{0.1in} '1' \hspace{0.1in} bit) = 0.5 \hspace{0.1in} \mu W$$
$$f \hspace{0.1in} (frequency)= 193.1 \hspace{0.1in} THz$$
$$r_e \hspace{0.1in} (extintion \hspace{0.1in} ratio) = 0.05 \xrightarrow \quad r_e = P_0/P_1$$
$$B_R \hspace{0.1in} (bitrate) = 10 \hspace{0.1in} Gbits/s$$
$$B_e \hspace{0.1in} (electrical \hspace{0.1in} bandwidth) = B_R$$
I use as reference the explanation of "Principles of Optical Communications" of José Capmany and it applying the following equation for Q value:

The possible values of Q are:

*

*77.499

*2.9592

*0.019739

*0.3947

I search more information about how I can calculate the Q value  in APD photodetectors. However, I haven't found any way to get one of the above results. Somebody could help me?
Thanks!


text:
Q: Why can I use the new version of go's API even though I specified the old go version in go.mod? I specified go 1.15 in go.mod and then used the new API of go 1.16 in my code and it works fine.
my go.mod:
module go_test

go 1.15

my a.go:
package main

import (
    "os"
)

func main() {
    os.CreateTemp("", "*.txt") // os.CreateTemp was introduced in go 1.16
}

my local golang version is 1.16 and it works fine:
go version
// go version go1.16 darwin/amd64
go run a.go // no errors

What confuses me is that if I use the embed library (also a new feature introduced in go 1.16), I get an error when compiling:
go:embed requires go1.16 or later (-lang was set to go1.15; check go.mod)

There is a similar question in this issue but I didn't find a clear answer:
https://github.com/golang/go/issues/43980#issuecomment-770306226


text:
Q: Escape commas when writing string to CSV I need to prepend a comma-containing string to a CSV file using Python. Some say enclosing the string in double quotes escapes the commas within. This does not work. How do I write this string without the commas being recognized as seperators?
string = "WORD;WORD 45,90;WORD 45,90;END;"
with open('doc.csv') as f:
    prepended = string + '\n' + f.read()
with open('doc.csv', 'w') as f:
    f.write(prepended)

A: So as you point out, you can typically quote the string as below. Is the system that reads these files not recognizing that syntax? If you use python's csv module it will handle the proper escaping:
with open('output.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerows(myIterable, quoting=csv.QUOTE_ALL)

The quoted strings would look like:
"string1","string 2, with, commas"

Note if you have a quote character within your string it will be written as "" (two quote chars in a row):
"string1","string 2, with, commas, and "" a quote"


text:
Q: MPI parallelize one function I want to parallelize an numerical integration function.  I want to use this function in the middle of calculation. The work before should be done in root process. Is this possible to do in MPI?
 double integral_count_MPI(double (*function)(double) , double beginX, double endX, int      count)
 {
    double step, result;
    int i;
    if (endX - beginX <= 0) return 0;
    step = (endX - beginX) / count;
    result = 0;

    double *input = (double*)malloc((count+1) *sizeof(double));
    for (i = 0; i <= count; i ++)
    {
       input[i] = beginX + i*step;
    }
    // Calculate and gather
 }

EDIT
algorithm:
  1 process calculation;
while:
  1 process calculation;
  integration very complex function with many processes;
  1 process calculation;
end while;
1 process calculation;

A: MPI provides various means to build libraries that use it "behind the scenes". For starters, you can initialise MPI on demand. MPI-2 modified the requirements for calling MPI_Init so every compliant implementation should be able to correctly initialise with NULL arguments to MPI_Init (because the actual program arguments might not be available to the library). Since MPI should only be initialised once, the library must check if it was already initialised by calling MPI_Initialized. The code basically looks like this:
void library_init(void)
{
   int flag;

   MPI_Initialized(&flag);
   if (!inited)
   {
      MPI_Init(NULL, NULL);
      atexit(library_onexit);
   }
}

The initialisation code also registers an exit handler by calling atexit() from the C standard library. Within this exit handler it finalises the MPI library if it not already finalised. Failure to do so might result in mpiexec terminating the whole MPI job with a message that at least one process has exited without finalising MPI:
void library_onexit(void)
{
   int flag;

   MPI_Finalized(&flag);
   if (!flag)
      MPI_Finalize();
}

This arrangement allows you to write your integral_count_MPI function simply like:
double integral_count_MPI(...)
{
    library_init();

    ... MPI computations ...
}

integral_count_MPI will demand-initialise the MPI library on the first call. Later calls will not result in reinitialisation because of the way library_init is written. Also no explicit finalisation is necessary - the exit handler will take care.
Note that you will still need to launch the code via the MPI process launcher (mpirun, mpiexec, etc.) and will have to be careful with doing I/O, since the serial part of the code would execute in each instance. Many MPI-enabled libraries provide their own I/O routines for that purpose that filter on the process rank and allow only rank 0 to perform the actual I/O. You can also use the dynamic process management facilities of MPI to spawn additional processes on demand, but that would require that you abstract a huge portion of the process management into the library that performs the integration, which would make it quite complex (and the code of your main program would look awkward).

A: You can find the MPI documentation here
Basically, the logic is the following:
int main()
{
    MPI_INIT(...);
    MPI_Comm_size(...);    //get the number of processes
    MPI_Comm_rank(...);    //get my rank

    if (rank == 0)     //master process
    {
        for (i = 1; i < n; i++)
            MPI_Send(...) //Send interval data specific to i process

        double result = 0;
        for (i = 1; i < n; i++)
        {
            double part_result;

            MPI_Recv(&part_result, ...) //Receive partial results from slaves

            result += part_result;
        }

        // Print result
    }
    else               //slave process
    {
        MPI_Recv(...)  //Receive interval data from master (rank 0 process)

        double result = integral_count_MPI(...);

        MPI_Send(...)  // Send results to master
    }

    MPI_FINALIZE(...);
}


text:
Q: why this doesn't throw an exception it's kind a simple question but i have the doubt see the code belows
public static String something;
    static void Main(string[] args)
    {
        try
        {
            if (something == "blah")
                System.Console.Write("ok");
        }
        catch (Exception)
        {

            throw;
        }

    }

i know that doesn't throw an exception but why? because the variable with the name something it's null and when you compare you're trying to get a reference with null. Can someone please explain to me why? Thanks!

A: This is IL code generated by compiler:

IL_0002:  ldsfld     string ConsoleApplication1.Program::something
IL_0007:  ldstr      "blah"
IL_000c:  call       bool [mscorlib]System.String::op_Equality(string, string)

String.op_Equality Method:
public static bool operator == (string a, string b)
a - A String or a null reference
b - A String or a null reference
op_Equality allows to pass null references and doesn't throw exception.

A: Nothing is wrong here, since you're not trying to dereference something. You are getting its value, which is null. If you tried to dereference it (ie something.somemethod()) then an exception would have been thrown.

A: The variable, something, doesn't need to be instanced for that kind of comparison.  It knows how to compare itself to a null.
So it doesn't throw an exception because
null == "string"
is a valid comparison which returns false.

A: You can compare null to a string - the result is that they aren't equal. In this case Something is null - you don't have to "dereference" to use it in a comparison, the null value itself works.

A: since the something variable is null, then comparing it to a string value is the same as saying
if(null == "blah")...

Clearly null and "blah" are not the same, so it will return false, it won't throw an exception.

A: A string is a nullable type.
So you in the given code you compare a NULL string to a string that contains the characters "blah" and you have no else statement.
Of course I would argue using == when you are trying to compare a string is wrong.
Technically "Dog played ball with the boy\n" and "Dog played ball with the boy\0" would not equate to true when using the == comparison.


text:
Q: How to control playback speed of iTunes U lectures in Mac OS? I try to learn swift and opened iTunes U lectures in iTunes on Mac. I wonder how can i change playback speed? It is easy on iPad, but i have no idea how to do this while playing videos in iTunes on Mac

A: It is currently not possible in iTunes. I highly recommend you to give feedback about this feature to Apple.
However there is a workaround:

*

*Download VLC

VLC is a free and open source cross-platform multimedia player and
  framework that plays most multimedia files as well as DVD, Audio CD,
  VCD, and various streaming protocols.

*Right click on the file in iTunes and choose "Show in Finder"

*Open the file shown in Finder with VLC

*In the menu "Playback" you can find the "Playback Speed" settings.

A: If you're trying to speed it up, press the fast-forward button (connected two right pointing arrows). It continues to play audio and video, but at 2x-60x speed.
I don't know of any native method for playing at 0.5x, 1.5x, or any other speed slower than 2x.


text:
Q: Android external activity fails I'm trying to set up android multiple file chooser from https://github.com/paulasiimwe/Android-Multiple-file-Selector-Dialog.
I've added dependency to this library from my project.
Problem is app just fails when I click "run as android application".
Log:
[2015-01-30 01:55:19 - PhotoSigner] Android Launch!
[2015-01-30 01:55:19 - PhotoSigner] adb is running normally.
[2015-01-30 01:55:19 - PhotoSigner] Performing com.vladimir.photosigner.MainActivity activity launch
[2015-01-30 01:55:19 - PhotoSigner] Automatic Target Mode: using device 'HT17MV800004'
[2015-01-30 01:55:19 - PhotoSigner] Uploading PhotoSigner.apk onto device 'HT17MV800004'
[2015-01-30 01:55:26 - PhotoSigner] Failed to install PhotoSigner.apk on device 'HT17MV800004': timeout
[2015-01-30 01:55:26 - PhotoSigner] Launch canceled!

Here is my android manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com`enter code here`.vladimir.photosigner"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <activity android:name="paul.arian.fileselector.FileSelectionActivity" />
    <activity android:name="paul.arian.fileselector.FolderSelectionActivity" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity
            android:name="com.vladimir.photosigner.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

And my code calling external activity:
import paul.arian.fileselector.FileSelectionActivity;
...
setContentView(R.layout.activity_main);
Intent intent = new Intent(getBaseContext(), FileSelectionActivity.class);
startActivityForResult(intent, 0);

...
onActivityResult is exactly same as man said in https://github.com/paulasiimwe/Android-Multiple-file-Selector-Dialog.
Could anyone help with that?


text:
Q: WinSock Library for Visual C++ 2008 Express? please how to add winsock library to Visual C++ 2008 Express? I tried including <windows.h> alone, than <windows.h> and <winsock.h>, but I get LINK error on WSAStartup().
I found somewhere that you need to add additional dependencies for your project, so I brought up linker for project properties, and in the select box for additional dependencies there was no ws_32.lib, So I tried to add it manually (write it) but still LINK Error....

A: Visual C++ Express don't install the full Windows SDK.  You can download and install the full SDK from Microsoft.
After installing the SDK there is a tool (it will be on the start menu) to register the SDK directories with Visual Studio.  After than you should be able to reference winsock.


text:
Q: The frog puzzle: simple probability isn't so simple; intuition and generalization There have been numerous discussions of the frog puzzle. Below is a puzzle followed by some solutions:
"You're poisoned in the jungle and the only way to save yourself is to lick a special kind of frog. To make matters worse, only the female of that species will do. Licking the male frog doesn't do anything. The male and female frogs look identical and appear with equal probabilities. The only difference is that the male frogs sometimes emit a distinctive croak.
You spot a frog in front of you, but then you hear a croaking sound behind you. You turn around and spot two frogs there. There's only time to run to one side. Which way should you run?"
(1) The original solution to the puzzle gives the probability 2/3 of survival if you run to two frogs, which is wrong. The original solution assumes that the problem is equivalent to finding a female in a reduced sample space $MM$ $MF$ $FM$ and doesn't take into account the fact that you heard a croaking.
(2) Another solution is that since you hear a croaking, you may represent a male frog as $M_c$ if it croaked and $M_n$ if it didn't croak, so the new sample space is $M_cM_n$ $M_nM_c$ $FM_c$ $M_cF$, which gives a 1/2 probability that there is a female among the two frogs.
(3) The correct solution (I believe) is that if the probability that a male frog croaks during a short time interval that you were listening for croaks is $p$, then the probability that there is a female among the two frogs is
$$
\begin{align*}
&P(FM\mbox{ or }MF | \mbox{one croak})\\
&=\frac{P(\mbox{one croak}|FM\mbox{ or }MF) P(FM\mbox{ or }MF)}{ P(\mbox{one croak}|FM) P(FM) +  P(\mbox{one croak}|MF) P(MF) + P(\mbox{one croak}|MM)P(MM)}\\
&=\frac{p\cdot0.5}{0.25p+0.25p+0.25p(1-p) + 0.25(1-p)p}\\
&=\frac1{2-p}
\end{align*}
$$
Here we're using Bayes' Theorem.
If we look at the single frog that didn't croak, the probability that it is female is
$$
\frac{ P(F)}{ P(M_n) + P(F)} = \frac{0.5}{0.5+0.5(1-p)} = \frac1{2-p}
$$
So it doesn't matter which direction you run!
Does anyone have a good intuition as to why it doesn't matter which way you run? Does there exist an intuitive way to arrive at the answer in a general case:
"
There are $n$ frogs and $m$ of them croak. What is the probability that one of the frogs is female?
"
If $m=0$, we can use the Binomial Theorem to get
$$
1-\frac{(1-p)^n}{{n\choose0} + {n\choose1}(1-p) + {n\choose2}(1-p)^2+\ldots + {n\choose n}(1-p)^n}
= 1-\left(\frac{1-p}{2-p}\right)^n
$$
I suspect that the answer to the general case is $\displaystyle 1-\left(\frac{1-p}{2-p}\right)^{n-m}$ because we can just "ignore" the croaking frogs. I'm looking for a good intuitive explanation as to why that's true (if it is true, of course).
A further generalization would be skewing the probability of a male vs. female frog. Let's say that the probability that any given frog is male is $x$. Then the above formula for the case $m=0$ becomes
$$
1-\frac{x^n(1-p)^n}{{n\choose0}(1-x)^n + {n\choose1}(1-x)^{n-1}x(1-p) + {n\choose2}(1-x)^{n-2}x^2(1-p)^2+\ldots + {n\choose n}x^n(1+p)^n}
= 1-\left(\frac{x(1-p)}{1-xp}\right)^n
$$
Is there a good answer for this more general case with $n$ frogs, $m$ of which are croaking?

A: Because the presence of croaking identifies a frog as male with certainty, but not all male frogs are observed to croak, this is informative of the frog's sex; thus one must posit a model in which there is a probability $p \in (0,1]$ of observing a male frog croaking, with assumptions about the independence of frogs croaking.
Let's first deal with the case of seeing a single frog that does not croak.  The probability it is female is $$\Pr[F \mid \bar C] = \frac{\Pr[\bar C \mid F]\Pr[F]}{\Pr[\bar C]} = \frac{\Pr[\bar C \mid F]\Pr[F]}{\Pr[\bar C \mid F]\Pr[F] + \Pr[\bar C \mid M]\Pr[M]} = \frac{1 \cdot \frac{1}{2}}{1 \cdot \frac{1}{2} + (1-p) \cdot \frac{1}{2}} = \frac{1}{2-p},$$ as you stated.  This answer makes intuitive sense:  in the limiting case where male frogs are never observed to croak ($p = 0$), then the lack of croaking is non-informative of the sex, and we are equally likely to have seen a female versus a male; conversely, in the limiting case where a male is guaranteed to croak ($p = 1$), then the lack of croaking is fully informative of the frog being female.
Now let's deal with the general case with seeing $n$ frogs but hearing one croak.  We are interested in the random variable $X$ that counts the number of females among the $n$ frogs.
$$\Pr[X = 0 \mid C] = \frac{\Pr[C \mid X = 0]\Pr[X = 0]}{\Pr[C]}.$$  The numerator is easy enough, but the denominator needs to be further decomposed via the law of total probability:
$$\Pr[C] = \sum_{x=0}^n \Pr[C \mid X = x]\Pr[X = x].$$  Since we assume that $X \sim \operatorname{Binomial}(n, \theta = 1/2)$, and male frogs croak independently with probability $p$ of the presence of any other male frogs (which is not true in nature, as males exhibit competitive vocalizations), then if $X = x$ frogs are female, the probability of hearing at least one of them croak is $$\Pr[C \mid X = x] = 1 - \Pr[\bar C \mid X = x] = 1 - (1-p)^{n-x},$$ and $$\Pr[C] = 2^{-n} \sum_{x=0}^n  (1 - (1-p)^{n-x}) \binom{n}{x} = 1 - (1 - p/2)^n.$$  Consequently, $$\Pr[X = 0 \mid C] = \frac{(1-(1-p)^n)\binom{n}{0}2^{-n}}{1 - (1-p/2)^n} = \frac{1-(1-p)^n}{2^n - (2-p)^n}.$$  Hence the probability of having at least one female frog among the $n$ frogs, given that a croak was heard, is $$\Pr[X \ge 1 \mid C] = 1 - \Pr[X = 0 \mid C] = 1 - \frac{1-(1-p)^n}{2^n - (2-p)^n},$$ and in the case where $n = 2$, this simplifies to $2/(4-p)$.  This is not the same as the single frog case and in fact is worse except when $p = 0$, in which case they are equal.  Note that this result assumes you are not able to infer any information between single versus multiple croaks.
When $n > 2$, then heading for the $n$ frogs becomes increasingly prefrable except in the case where $p$ is close to $1$.

As for the generalization, suppose we are directly observing a group of $n$ frogs, and we see $m$ of them croak.  As before, prior to croaking, each frog is equally likely to be male or female, and given that a frog is male, it has a probability $p$ of croaking independent of any other frogs.  So now we let $C$ be a random variable that counts the number of croaking frogs.  Then the probability that at least one frog is female, given $m$ croaking frogs, is $$1 - \Pr[X = 0 \mid C = m] = 1 - \frac{\Pr[C = m \mid X = 0]\Pr[X = 0]}{\Pr[C = m]}.$$  The unconditional probability of observing exactly $m$ croaking frogs is $$\Pr[C = m] = \sum_{x=0}^{n-m} \Pr[C = m \mid X = x] \Pr[X = x],$$ since if the number of females exceeds $X > n-m$, it is not possible to observe $m$ croaking frogs--females do not croak.  In a subgroup of $n-x$ male frogs, the probability that exactly $m$ croak is itself binomial:  $$\Pr[C = m \mid X = x] = \binom{n-x}{m} p^m (1-p)^{n-x-m}, \quad 0 \le m \le n-x, \quad 0 \le x \le n.$$  Hence $$\Pr[C = m] =  \binom{n}{m} 2^{-n} (2-p)^{n-m} p^m = \binom{n}{m} (p/2)^m (1 - p/2)^{n-m}.$$  That is to say, it is the PMF of a binomial random variable with parameters $n$ and $p/2$.  Then the desired probability is $$\Pr[X \ge 1 \mid C = m] = 1 - \frac{\binom{n-0}{m} p^m (1-p)^{n-m} 2^{-n} }{\binom{n}{m} (p/2)^m (1-p/2)^{n-m}} = 1 - \left(1 - \frac{1}{2-p}\right)^{m-n}.$$  This agrees with your computation.  Moreover, it addresses the difference in interpretation that we encountered earlier, since in the case $n = 2$, $m = 1$, we get $\Pr[X \ge 1 \mid C = 1] = \frac{1}{2-p}$, which is the same as your answer in $(3)$.

Edit 2:  To answer the non-equiprobable case $\theta \ne 1/2$, we simply modify the above computation.  We get
$$\Pr[C = m] = \binom{n}{m} (p(1-\theta))^m (1 - p(1-\theta))^{n-m},$$ and $$\Pr[X \ge 1 \mid C = m] = 1 - \left( 1 - \frac{\theta}{1-p(1-\theta)} \right)^{n-m},$$ where $\theta$ is the prior probability of the frog being female.

A: Ahead of you is a frog that's either a female or a non-croaking male. Behind you is one frog that's a croaking male and another frog that's either a female or a non-croaking male. Since you're going to lick both frogs if you opt for the ones behind you, you can disregard the fact that one of them is definitely a (croaking) male. That is, you can simply think of the situation as consisting of what's ahead of you is either a female or a non-croaking male while what's behind you is exactly the same thing. So it doesn't matter which choice you make.
Note, this analysis doesn't care what the ratio is of males to females. If the probability of a randomly encountered frog being a female is $F$ and the probability of it being a non-croaking male is $N$ (with $0\lt F+N\lt1$ since the problem establishes that both croaking and non-croaking frogs exist, but with no other constraints on the probabilities $F$ and $N$), the probability of living (by licking a female) is $F/(F+N)$.

A: Suppose there is one frog in front of you and one frog behind you, and you hear no croak. Clearly, it does not matter which way you turn, since you have no information about either frog. Now add a male frog behind you, wait for it to croak, and now make your choice. The addition of the male frog and croak don't make a difference to the other frogs at all - although they're both now somewhat more likely to be female since you didn't hear them croak, that chance has changed by the same amount for both of them. Your choice is between a frog you know little about, and a frog you know little about plus an irrelevant male frog. Since you know equally little about the two frogs you didn't hear, it doesn't matter which you choose. Placing a male frog behind you and waiting for it to croak will not make its companion any more likely to be female than the lone frog in front of you.
Another way to view it is that the two frogs that didn't croak are indistinguishable. I could switch those two silent frogs after you make your choice, and you would have no way of knowing. It's not possible that one is more likely to be female than the other.


text:
Q: method/function inside object method javascript Hey guys I've just started using javascript's prototype and I was wondering if it's possible, and if so, how to call a function inside a method eg:
obj = function(test){
this.test=test;
}

obj.prototype.a = function(){
    var x = this.test;

    function b(){
        alert(x);
    }

    function c(){
    console.log(x);
    }
}

var foo = new obj();
foo.a.b();

So, could I access function b inside obj.a without calling function c ie I want to be able to call a and have it call both functions inside it, but also be able to just call b or c if I need to?
I know I could just put these in separate methods outside of a, but I thought I'd ask the question.
Cheers.

A: b is scoped to the anonymous function in which it is declared. There is no way to access from outside that function without changing that function to expose it.
You can call a because it is a property of the object prototype (it isn't stored in a scoped variable). b and c are not exposed at all. The way you have written the code is how people usually create private methods in JavaScript.

A: You could alter your code a bit to make it possible, but I suspect what you really want is to be able still to get the value of x when you call b from outside... Am I right?
Have you perhaps considered making a another instance in it's own right? I'm assuming your code is non-trivial enough to make this worth while...


text:
Q: Lua, table imprime solo nils En una tabla guardo todos los valores que me indica el usuario con un ciclo for pero al momento de imprimirlos solo me devuelve nils
for i=1,n do
    io.write("Por favor deme el valor de a" .. i .. ": ")
    a = io.stdin:read("*n")
    tablaA[i] = a
end

A: Hola Giovanni a lo mejor tu problema era la forma en que imprimias los valores, no se exactamente como lo hiciste pero aqui dejo una implementacion.
io.write("Ingrese la cantidad de valores a ingresar ")
local n=io.stdin:read("*n")

local tablaA={}
for i=1,n do
   io.write("Por favor deme el valor de a" .. i .. ": ")
   tablaA[i] = io.stdin:read("*n")
end

for i,number in ipairs(tablaA) do io.write(number.." ") end

A: Es preferible que añadas los datos con table.insert para añadirlos por rango, primero te dejo el código más claro y más corto:
io.read() -- lee valores

table.insert(tabla, elemento) -- inserta elementos por indice

tonumber(valor) -- podemos validar si es númerico y evitarnos errores.

tabla = {} -- estamos declarando una tabla

El código podría ser de esta forma:
elementos = {} -- declaramos una tabla como lista
num = nil -- declaramos num como nulo
while(not tonumber(num)) do -- hacemos un bucle mientras no sea númerico, recuerda la función "tonumber()"
    if (not num) then -- si es nulo imprimimos un mensaje
        print("Ingresa un NUMERO:")
    else -- y si no, el siguiente, y salir del bucle hasta que obligatoriamente sea un número
        print("No ingresaste un número:")
    end
    num = io.read() -- leemos el dato durante el bucle hasta obtener el númerico
end

for i=1, tonumber(num) do -- recuerda que las listas en Lua inician desde 1, ponemos que lea desde uno siempre y cuando no alcanze el tamaño del número, io.read() retorna una cadena(string) así que lo convertimos a númerico
    print("Ingresa el elemento "..i.." para añadir:") -- leemos los datos
    table.insert(elementos, io.read()) -- insertamos los datos que se lean en la tabla 'elementos'
end

lista = '{' -- una simple vista para que el usuario vea que elementos insertó
for i,v in pairs(elementos) do
    lista = lista..'"'..v..'"'
    if not (i == #elementos) then
        lista = lista..', ' -- si no es el limite, inserta una coma y espacio separandolos
    end
end
lista = lista..'}' -- seramos nuestra "lista" creada que en realidad es una cadena
print("Los elementos en la tabla son los siguientes:\n"..lista) -- le damos al usuario los datos que insertó


text:
Q: nServiceBus UnicastBusConfig.MessageEndpointMappings.Endpoint I am playing with custom config for NServiceBus and I am implementing IConfigurationSource.
In the case of UnicastBusConfig, what is property UnicastBusConfig.MessageEndpointMappings[n].Endpoint supposed to be?
Thank you

A: The Endpoint property is the address of the target endpoint, usually in the format "queue@machine" or "queue" when it is on a local machine.

A: It is a name of your QUEUE.
<UnicastBusConfig>
   <MessageEndpointMappings>
     <add Messages="YOURASSEMBLYNAME" Endpoint="NAMEOFQUEUE@MACHINENAME"></add>
   </MessageEndpointMappings>
</UnicastBusConfig>


text:
Q: delegate.Invoke and delegate.BeginInvoke - used on the same method, return two different results I'm writing a software that communicates with 4 devices via serial port. One of them, Input/output module (ICP CON) has 4 input channels (DL) and 4 output channels (RL). I need to monitor status of DL channels and then, when a signal is detected I have to do some processing, which depends on which signal has been detected.
I'm calling 4 methods asynchronously, every 500ms (timer), here's the tick event:
//stop the timer
timer1.Stop();

//open com port 2
Tester.Devices.ICP.OpenICPPort(2, 9600);

//dl 0
ic = new CheckDLStatus(0, this);
ic.Execute();

//dl 1
ic = new CheckDLStatus(1, this);
ic.Execute();

//dl 2
ic = new CheckDLStatus(2, this);
ic.Execute();

//dl3
ic = new CheckDLStatus(3, this);
ic.Execute();

//close com port 2
Tester.Devices.ICP.CloseICPPort(2);

//enable the timer again
timer1.Enabled = true;

public CheckDLStatus(int DL, Form1 F1)
{
    //form 1 instance
    f1 = F1;

    // setup the delegate to call
    switch (DL)
    {
        case (0):
        {
            checkDL_delegate = new checkDL(
                BusinessLogicLayer.Classes.
                DevicesCommunication.CheckDl0);

            break;
        }
        case (1):
        {
            checkDL_delegate = new checkDL(
                BusinessLogicLayer.Classes.
                DevicesCommunication.CheckDl1);

                break;
        }
        case (2):
        {
            checkDL_delegate = new checkDL(
                BusinessLogicLayer.Classes.
                DevicesCommunication.CheckDl2);

                break;
        }
        case (3):
        {
            checkDL_delegate = new checkDL(
                BusinessLogicLayer.Classes.
                DevicesCommunication.CheckDl3);

                break;
        }
    }
}

public static void CheckDl2()
{
    //declare
    bool currentStatus;

    try
    {
        //input
        currentStatus = DevicesCommunication.Dl_2_On;
        //should be false at the start of the test,
        //so when it becomes true, the change is detected immediately

        //dl2?
        if (ICP.LookForSignal_DL2((short)2,
            Util.Classes.Util.ResolveComPortNumber(
                Cache.settings.icpModulePort),
            Convert.ToInt32(Cache.settings.icpModuleBaudRate)))
        {
            //signal detected
            DevicesCommunication.Dl_2_On = true;
        }
        else
        {
            //signal not detected
            DevicesCommunication.Dl_2_On = false;
        }

        //check, if status of DL2 has been changed
        //(from true to false, from false to true)
        if (currentStatus != DevicesCommunication.Dl_2_On)
        {
            //status from before checking signal is different
            // from status read from the device so
            //status has changed

            if (DevicesCommunication.Dl_2_On)
            {
                DevicesCommunication.DL2_apperancesCounter += 1;

                //TODO
                //process
                //ProcessDL2();
            }
        }
        else
        {
            //status did not change
            //just clear buffer
            ClearBuffer();
        }

        return;
    }
    catch (Exception ex)
    {
        Util.Classes.ErrorLogging.LogError(ex, true);
        //EndCurrentTest();
        return;
    }
}

Execute() method, that invokes a delegate:
public void Execute()
{
    // call the method on the thread pool
    checkDL_delegate.BeginInvoke(
        this.CallBack, null);

    //checkDL_delegate.Invoke();
}

The method that is called for checking DL2 status:
public static bool LookForSignal_DL2(short DL_number, int port, int baudRate)
{
    //declare
    bool iBit;

    try
    {
        //check if there is a signal at specified Dl_number
        iBit = DCON.Read_DI_Bit(Convert.ToByte(port), 1, -1,
            DL_number, 16, 0, 100);

        //return resposne
        return iBit; //true/false
    }
    catch (Exception ex)
    {
        Util.Classes.ErrorLogging.LogError(ex, true);
        return false;
    }
}

My problem is, when I turn on signal on DL2 channel, and I call LookForSignal_DL2 like this, without the timer and asynchronous calls (just for test):
private void button25_Click(object sender, EventArgs e)
{
    ICP.OpenICPPort(2, 9600);

    if (ICP.LookForSignal_DL2(2, 2, 9600))
    {
        MessageBox.Show("True");
    }
    else
    {
        MessageBox.Show("false!");
    }

    ICP.CloseICPPort(2);
}

It works - returns true.
If, in Execute() method I use Invoke, which makes the method call synchronous - it works (returns true), but this way I can only check 1 signal at the time.
If, in Execute() method I use BeginInvoke it doesn't work, it returns false, even though there is signal in DL2.
I admit I don't know what's going on. Do you have any idea?

A: I figured it out, if it helps anyone, I made a mistake here (bold text):
//stop the timer
timer1.Stop();

//open com port 2
Tester.Devices.ICP.OpenICPPort(2, 9600);

//dl 0
ic = new CheckDLStatus(0, this);
ic.Execute();

//dl 1
ic = new CheckDLStatus(1, this);
ic.Execute();

//dl 2
ic = new CheckDLStatus(2, this);
ic.Execute();

//dl3
ic = new CheckDLStatus(3, this);
ic.Execute();

Tester.Devices.ICP.CloseICPPort(2);
I ran my methods asynchronously, but the execution of the code went on, and everytime the port had been closed before any of the methods was able to check for signal. Unfortunetely the SDK library doesn't return any error in that case, so it just kept returning false.
Thank you for your comments.


text:
Q: 6502 assembly get data from a block of memory I've been learning 6502 assembly using the cbm programming studio. I'm reading a book by Jim Butterfield and Richard Mansfield. Both books discuss how one can use a method (I think it was indirect addressing)  to get data from a block of memory  (like  messages) but there isn't an example could someone provide me one please? I don't care what method is used.

A: It's fairly straight forward. You set ups a pair of zero page addresses to hold the address of the start of the block and then use indirect indexing by Y to access bytes within the block. The instruction LDA ($80),Y reads the bytes at $80 and $81 as a 16 bit address ($81 contains the highest 8 bits) then adds Y on, then reads the byte at the resulting address.
Note that, if you know the address in advance, you do not need to use indirect addressing, you can use absolute indexed.
The following routine demos both address modes. It copies the 10 bytes at a location specified in the X and Y registers (Y is the high byte) to the locations following $0400
      stx $80        ; Store the low byte of the source address in ZP
      sty $81        ; Store the high byte of the source in ZP
      ldy #0         ; zero the index
loop: lda ($80),y    ; Get a byte from the source
      sta $0400,y    ; Store it at the destination
      iny            ; Increment the index
      cpy #10        ; Have we done 10 bytes?
      bne loop       ; Go round again if not

Note that there is an obvious optimisation in the above, but I'll leave that as an exercise for the reader.

Edit OK here is the obvious optimisation as per i486's comment
      stx $80        ; Store the low byte of the source address in ZP
      sty $81        ; Store the high byte of the source in ZP
      ldy #9         ; initialise to the highest index
loop: lda ($80),y    ; Get a byte from the source
      sta $0400,y    ; Store it at the destination
      dey            ; Decrement the index
      bpl loop       ; Go round again if index is still >= 0


text:
Q: CSP error while serving with express (with helmet) an app created with create-react-app I'm struggling with serving a build created with "create-react-app" using Express with Helmet. I'm getting several errors in the explorer console related to Content Security Policy:
csp-errors
Of course, it isn't showing the app. I noticed that if a remove Helmet as middleware in Express it works but that's not the solution I want. This is my server code:

const express = require('express');
const helmet = require('helmet');
const cors = require('cors');
const morgan = require('morgan');
const bodyParser = require('body-parser');

/**
 * Server Configuration
 */

const whitelist = [];

const app = express();

// Express Configurations

// Enable reverse proxy support in Express. This causes the the "X-Forwarded-Proto" header field to be trusted so its
// value can be used to determine the protocol. See // http://expressjs.com/api#app-settings for more details.

app.enable('trust proxy');

app.use(morgan('dev')); // Log every request to the console
app.use(helmet()); // Configure secure Headers
app.use(bodyParser.urlencoded({ extended: false })); // Enable parsing of http request body
app.use(bodyParser.json());

// CORS Configuration

const corsOptions = {
  origin: (origin, callback) => {

    if (whitelist.indexOf(origin) !== -1 || !origin) {

      callback(null, true);

    } else {

      callback(new Error('Not allowed by CORS'));

    }

  },
};

app.use(cors(corsOptions)); // Allow CORS

/**
 * Launcher method
 */

app.start = () => {

  // start node server
  const port = process.env.PORT || 3000;
  app.listen(port, () => {

    console.log(`App UI available http://localhost:${port}`);
    console.log(
      `Swagger UI available http://localhost:${port}/swagger/api-docs`,
    );

  });

};

/**
 * App Initialization
 */

function initializeApp(readyCallback) {

  readyCallback(null, app);

}

module.exports = (readyCallback) => {

  initializeApp(readyCallback);

};

Can anyone give me a hand? Thanks in advance!

A: Got here via google with the same question. I didn't want to lower any of the security settings in helmet so I changed my react build config. Simply add the line
INLINE_RUNTIME_CHUNK=false

to your .env in the react app root directory. Then when you run
npm run build to build the app, all inlined scripts will be removed and will no longer violate the CSP. This does add one extra initial HTTP GET request when first loading the site but seems to be worth the security benefits in my opinion.

A: Helmet maintainer here.
This is happening because of something called Content Security Policy, which Helmet sets by default. To solve your problem, you will need to configure Helmet's CSP.
MDN has a good documentation about CSP which I would recommend reading for background. After that, take a look at Helmet's README to see how to configure its CSP component.
To give some help specific to this question, let's take a look at one error you're seeing:
Content Security Policy: This page's settings blocked the loading of a resource at inline ("script-src").

This error is telling you that the script-src directive of your CSP does not allow inline JavaScript, and so it was blocked.
This is considered "inline" JavaScript:
<script>console.log('hello world!')</script>

This, however, is not:
<script src="/foo.js"></script>

There are several ways to fix this:

*

*Add a hash or nonce to the inline <script> and use that in your CSP. See this example on MDN for help.

*Refactor your app to avoid inline scripts entirely.

*Update your CSP to allow unsafe inline scripts. You'd do something like this:
app.use(
  helmet({
    contentSecurityPolicy: {
      directives: {
        ...helmet.contentSecurityPolicy.getDefaultDirectives(),
        "script-src": ["'self'", "'unsafe-inline'", "example.com"],
      },
    },
  })
);

Note that this is considered unsafe.

*Disable CSP. This is the most dangerous option so I don't recommend it.
app.use(
  helmet({
    contentSecurityPolicy: false,
  })
);

Your other errors, such as the fonts.googleapis.com error, refer to default-src, which is the fallback if a directive is not specified.
In summary: to solve your problem, you will need to tell Helmet to configure your CSP.

A: Here is a third solution. Change your build script in package.json to following:
"build": "GENERATE_SOURCEMAP=false node scripts/build.js"


text:
Q: Listen to link click in SwiftUI TextView I have this code below
import SwiftUI

struct MyView: View {

    let text = "If you want to know more, ***[Click Here](http://example.com)*** to continue"
    @Environment(\.openURL) private var openURL

    var body: some View {
        Text(LocalizedString(text))
            .environment(\.openURL, OpenURLAction{ url in
                print(url)
                return .systemAction
            })
    }

}

I saw this in OpenURLAction Documentation and other SO questions like This answer from workingdog support Ukraine
But I always get a runtime error from Xcode saying:
Key path value type 'WritableKeyPath<EnvironmentValues, OpenURLAction>' cannot be converted to contextual type 'KeyPath<EnvironmentValues, OpenURLAction>'

Please can some one tell me what's going wrong? I'm using Xcode 14.0.1 if needed
Note: My reason for this is that the URLs associated with the text are not valid URLs, for example, I have a URL like this "[John Doe](friend-4-2)", so I want to open another ViewController in my app depending on the particular link the user clicked
Below is an image showing how my code looks like and the error I get

A: This was an odd one...
The error "Key path value type 'WritableKeyPath<EnvironmentValues, OpenURLAction>' cannot be converted to contextual type 'KeyPath<EnvironmentValues, OpenURLAction>'" only happens in when supporting  anything less than iOS 15.
That is because OpenURLAction(handler:) is only available starting iOS 15.
https://developer.apple.com/documentation/swiftui/openurlaction/init(handler:)
If you add @available(iOS 15, *) above the struct the error should go away.
After that you should be able to intercept any URL
import SwiftUI

@available(iOS 15, *)
struct LinkView: View {
    @State var clickedCount: Int = 0

    let text = "If you want to know more, ***[Click Here](yourApp://click-here)*** to continue"
    @Environment(\.openURL) private var openURL

    var body: some View {
        VStack{
            Text("\(clickedCount)")
            Text(LocalizedStringKey(text))
                .environment(\.openURL, OpenURLAction { url in
                    clickedCount += 1
                    return .systemAction
                })
        }
    }
}
@available(iOS 15, *)
struct LinkView_Previews: PreviewProvider {
    static var previews: some View {
        LinkView()
    }
}

iOS 14 and below are not supported by this method.
But if you want to support the lower versions you can use URL Scheme with onOpenURL(perform:)
First add the Scheme "Target > Info > URL Types"

then use the code below.
struct LinkView: View {
    @State var clickedCount: Int = 0

    let text = "If you want to know more, ***[Click Here](yourApp://clickHere)*** to continue"
    @Environment(\.openURL) private var openURL

    var body: some View {
        VStack{
            Text("\(clickedCount)")
            Link("Click-here", destination: URL(string: "yourApp://clickHere")!)
            Text(LocalizedStringKey(text))
                .onOpenURL { url in
                    //Check the URL
                    if url.absoluteString.hasSuffix("clickHere") {
                        clickedCount += 1
                    }else{
                        print("Tried to open \n\t\(url.absoluteString)")
                    }

                }
        }
    }
}

A: //
//  ContentView.swift
//  OnClickExample
//
//  Created by Allan Garcia on 21/01/23.
//

import SwiftUI
import Foundation
import UIKit

struct ContentView: View {
    var body: some View {
        VStack {
            // VStack is not really necessary, i'm using to centralize the content, but on newer versions of iOS this is not necessary.
            Spacer()
            // 1. Best Swifty way to open a link is by using a Link struct
            Link("Open Google Search", destination: URL(string: "https://www.google.com/")!)
            Spacer()
            // 2. If you need more customization link a link on your text of simple a different formatting of the text you can use a different initilizaer using Link(destionation:view), like so:
            Link(destination: URL(string: "https://www.google.com/")!) {
                Label("Open Google Search", systemImage: "link")
            }
            Spacer()
            // 3. If you need more customization on the action itself to open an url, that I thinks is your case, use a simple personalized struct (simple code is always better them complex code)
            TheWayIDoIt(
                urlText: "Open Google Search",
                urlLink: "https://www.google.com/",
                urlSystemImage: "magnifyingglass.circle.fill"
            )
            Spacer()
        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct TheWayIDoIt: View {

    let urlText: String
    let urlLink: String
    let urlSystemImage: String

    var body: some View {
        Link(destination: URL(string: urlLink)!) {
            Label(urlText, systemImage: urlSystemImage)
        }
        .simultaneousGesture(
            TapGesture()
                .onEnded { _ in
                    print("Going to link \(urlLink)")
                }
        )
    }

}


text:
Q: How to show that the reciprocal set is also a basis of $\mathbb{R}^3$ If three vectors (say $\vec v_1$, $\vec v_2$ and $\vec v_3$) are a basis of $\mathbb{R}^3$, their reciprocal vectors ($\vec u_1$, $\vec u_2$ and $\vec u_3$, defined by $\vec{u}_i \cdot \vec{v}_j = \delta_{ij}$) must also be a basis of $\mathbb{R}^3$.
How do I go about proving this? I have tried using $\alpha_{1}\vec v_{1} + \alpha_{2}\vec v_{2} + \alpha_{3}\vec v_{3} = 0$ means that $\alpha_1 = \alpha_2 = \alpha_3 = 0$, and dotting different things through it, but I'm not getting very far.

A: Hint: If $\alpha_1\vec{u_1}+\alpha_2\vec{u_2}+\alpha_3\vec{u_3}=0$, then $\vec{v_1}.\left(\alpha_1\vec{u_1}+\alpha_2\vec{u_2}+\alpha_3\vec{u_3}\right)=0$ too. In other words, $\alpha_1=0$.


text:
Q: View controller dismiss issue I am setting up a new application which have a firebase authentication
While you are registered user there is no problem with you to create and post add (Item) so other people can see it. BUT if you are not logged in user it will show you a Log IN pop up! WHICH HAVE A DISMISS button!
I tried to create an if statement for example
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if segue.identifier == "itemToAddItemSeg" {
            let vc = segue.destination as! AddItemViewController
            vc.category = category!
            }
        }

    private func showItemView(_ item: Item) {

        let itemVC = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "itemView") as! ItemViewController
        itemVC.item = item

        self.navigationController?.pushViewController(itemVC, animated: true)
    }

    //Mark: Load items
    private func loadItems() {
        downloadItemsFromFirebase(category!.id) { (allItems) in
            self.itemArray = allItems
            self.tableView.reloadData()
        }
    }

    private func showLoginView() {
        let loginView = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "loginView")
        self.present(loginView, animated: true, completion: nil)
    }
}

Which code need to be implemented? - so if when my showlogin pops up!
someone will press dismiss button it will not proceed to the AddItemViewCotroller
moreover it will stay on the same page in itemViewController

A: Swift 5
dismiss(animated: true, completion: nil)

Dismisses the view controller that was presented modally by the view controller.

I can't tell how you are calling your dismiss function based on your provided code, but an example of implementing the dismiss method:
func dismissButtonTapped() {
   dismiss(animated: true, completion: nil)
}

Again, not sure how you are calling your function, but the example above should be enough to guide you in the right direction.
This will dismiss the showLoginView and keep the user on the itemViewController.
Since you presented your loginView morally, this should do the trick.
Check out the documentation on the dismiss(animated:, completion:) method for more details.

A: As i said earlier the problem was with a transition i am really sorry if i  implemented the wrong code! The issue was in the place where i was implementing the code if Muser.curentUser() != nil
there was a better place when someone will press the done button they will ask them are they are registered users or no? adding a show login view popup in other place solved the issue sorry guys!! thank you you are the best and really good people because you tried to help me! thank you so much!


text:
Q: AngularJS scope property is undefined Why is $scope.orderBy undefined?
Shouldnt it be "test" ?
http://jsfiddle.net/XB4QA/4/
var app = angular.module("Foo", []);

app.directive("two", function () {
return {
    scope: {
        orderBy: '@'
    },
    restrict: 'E',
    transclude: true,
    controller: function ($scope, $element, $attrs) {
        console.log($scope.orderBy); // is undefined, why?
    },
    template: '

',
    replace: true
};
});

    <two order-by="test">test</two>

A: @ bindings are interpolated in the scope of the directive and this interpolation takes place later, after the directive linking phase.  This means that while directive templates can make use of the bindings, they will not be available in the various directive config methods.  = bindings, however, are available to the directive immediately, so I would suggest using such a binding if you want immediate access.
If test is a literal value that you want access to, add single quotes around the attribute value, like:
<two order-by="'test'">

or just leave the HTML as-is if test is a variable. In either case, change the binding like:
scope: {
    orderBy: '='  // = instead of @
}

A: If you want to use string interpolation (which seems to be the case by your use of @) you should be using $observe as mentioned by Ajay in the comments for the currently accepted answer.
Alternatively, if your orderBy attribute is always a literal string, you could create an empty isolation scope and don't attempt to bind orderBy.  Then you could use $attrs.orderBy to get the string value.
This works just fine.
app.directive("two", function () {
  return {
    scope: {
      orderBy: '@'
    },
    restrict: 'E',
    transclude: true,
    controller: function ($scope, $element, $attrs) {
      $attrs.$observe('orderBy', function() {
        console.log($scope.orderBy);
      });
    },
    template: '

',
    replace: true
  };
});

So does this:
app.directive("two", function () {
  return {
    scope: {
    },
    restrict: 'E',
    transclude: true,
    controller: function ($scope, $element, $attrs) {
      console.log($attrs.orderBy);
    },
    template: '

',
    replace: true
  };
});


text:
Q: Angular Universal SSR TransferState only first page data available I've created an ApiService using the TransferState API to cache data from a wordpress:
get(url, id) {
  const key = makeStateKey(id);
  if (this.transferState.hasKey(key)) {
    const item = this.transferState.get(key, null);
    return of(item);
  } else {
    return this.http.get(url).pipe(
      map(items => {
        this.transferState.set(key, items);
        return items;
      })
    );
  }
}

Then i'm using it to get data:
this.apiService.get(environment.url + '/wp-json/wp/v2/posts').subscribe(res => {
  this.posts = res;
});

This works well, and when run, calls the API the first time, then second time is always cached.
When statically generated:
/index.html
<script id="my-app-state" type="application/json">
  <!-- top level page data -->
</script>

/posts/index.html
<script id="my-app-state" type="application/json">
  <!-- top level page data -->
  <!-- posts data -->
</script>

*

*If I land on the exact html page /posts/index.html, the data is loaded from the TransferState cache
https://kmturley.github.io/angular-universal-wordpress-cms/frontend/dist/browser/sample-page

*If I land on /index.html, and navigate to /posts it uses html5 routes, the data is not available in the script tag. and is loaded via http instead
https://kmturley.github.io/angular-universal-wordpress-cms/frontend/dist/browser/
From what I understand the reason is because you land on a real static index.html file, containing the  then when navigating, all subsequent pages are not loading .html files, they are actually html5 routes /posts.
So the question is, how can I get the TransferState cache to use the  from the /posts/index.html file which was statically generated?
Potential solutions:

*

*Loading all data upfront (works, but pages are 1.1MB each)

*Putting data into a static file which can be loaded by ajax

*disabling html5 routing, so user hits static .html file with correct script tag

*some undocumented angular solution??

Static generated demo:
https://kmturley.github.io/angular-universal-wordpress-cms/frontend/dist/browser/
Static generated source:
https://github.com/kmturley/angular-universal-wordpress-cms/tree/gh-pages/frontend/dist/browser
Full codebase is here:
https://github.com/kmturley/angular-universal-wordpress-cms

A: I managed to solve this using a workaround. I created a new TransferState JSON which returns data as JSON, which can be shared between multiple pages:
export function serializeTransferStateFactory(
    doc: Document, appId: string, transferStore: TransferState) {
  return () => {
    return JSON.parse(transferStore.toJson());
  };
}

https://github.com/kmturley/angular-universal-google-apis/blob/master/src/app/shared/transfer_state_json.ts
and then modified the renderModuleFactory to return html and data separately:
const callbacks = moduleRef.injector.get(BEFORE_APP_SERIALIZED, null);
let data = null;
if (callbacks) {
  for (const callback of callbacks) {
    try {
      data = callback();
    } catch (e) {
      // Ignore exceptions.
      console.warn('Ignoring BEFORE_APP_SERIALIZED Exception: ', e);
    }
  }
}
const output = platformState.renderToString();
platform.destroy();
return {
  output: output,
  data: data
};

https://github.com/kmturley/angular-universal-google-apis/blob/master/utils.ts#L53
so that it can be saved to a .json file in prerender.ts:
previousRender = previousRender.then(_ => renderModuleFactory(AppServerModuleNgFactory, {
  document: index,
  url: route,
  extraProviders: [
    provideModuleMap(LAZY_MODULE_MAP)
  ]
})).then((res: { output: string, data: object }) => {
  // write html file
  writeFileSync(join(fullPath, 'index.html'), res.output);

  // write json files from TransferState objects
  Object.keys(res.data).forEach(item => {
    writeFileSync(join(jsonPath, item + '.json'), JSON.stringify(res.data[item]));
  });
});

https://github.com/kmturley/angular-universal-google-apis/blob/master/prerender.ts#L53
You can see a demo static version using the json here:
https://kimturley.co.uk/angular-universal-google-apis/dist/browser/
and the source code here:
https://github.com/kmturley/angular-universal-google-apis


text:
Q: How to disconnect an external browser launched inside w3m from w3m? Pressing Shift+m in w3m will launch external browser to show the current page from w3m. However, once the external browser is launched, w3m is frozen, waiting the user to quit the external browser before going back to the normal mode. Is it possible to config it such that it can launch the external browser to the background? So that I can use it and the external browser at the same time.

A: It's in the FAQ.
Hit o to go into options and specify
browsername %s &

where browsername is the command to invoke said browser.


text:
Q: PySpark script is not getting completed I have written PySpark script to read the data from database and csv, the script is not getting completed, it being executed. Below is the code,
import pyspark
from pyspark.sql import SparkSession
from pyspark.context import SparkContext
import os

os.environ['JAVA_HOME'] = 'path/to/java/bin/'

spark = SparkSession.builder.appName("") \
.config("spark.jars", "path/to/postgresql-42.3.2.jar") \
.config("spark.driver.extraClassPath", "path/to/postgresql-42.3.2.jar") \
.config("spark.executor.extraClassPath", "path/to/postgresql-42.3.2.jar") \
.getOrCreate()

df_etl_control = spark.read \
    .format("jdbc") \
    .option("url", "jdbc:postgresql://database_connection") \
    .option("query", "select * from table") \
    .option("user", "wwwww") \
    .option("password", "wwwwww").load()

df = spark.read.option("header",True).csv("path/to/csv")
df.printSchema()

I was getting RuntimeError: Java gateway process exited before sending its port number error before adding java home path os.environ['JAVA_HOME'] = 'path/to/java/bin/'. After adding the path, job is not getting completed
Any suggestion would be great


text:
Q: Module in Azure Function I am trying to bootstrap an ABP module in an Azure Function but I get an error:
Castle.MicroKernel.ComponentNotFoundException: 'No component for supporting the service System.IServiceProvider was found'
Stack Trace
[].EntityFrameworkCore.dll![].EntityFrameworkCore.Seed.SeedHelper.WithDbContext<[].EntityFrameworkCore.DbContext>(Abp.Dependency.IIocResolver iocResolver, System.Action<[].EntityFrameworkCore.DbContext> contextAction) Line 79
[].EntityFrameworkCore.dll![].EntityFrameworkCore.Seed.SeedHelper.SeedHostDb(Abp.Dependency.IIocResolver iocResolver) Line 35
[].EntityFrameworkCore.dll![].EntityFrameworkCore.EntityFrameworkModule.PostInitialize() Line 46

So in the Function's Startup.Configure I use Host.CreateDefaultBuilder to initialize the module.  Everything seems to go great until the EntityFrameworkModule tries to complete initializing and seed the DB.  That's when I get the error above.
Here is my code:
[assembly: FunctionsStartup(typeof(JobProcessor.Startup))]
namespace JobProcessor
{
    public class Startup : FunctionsStartup
    {

        public override void Configure(IFunctionsHostBuilder builder)
        {
            Host.CreateDefaultBuilder()
                .ConfigureServices(services =>
                {
                    var abpBootstrapper = AbpBootstrapper.Create<JobProcessorModule>();
                    services.AddSingleton(abpBootstrapper);
                    abpBootstrapper.Initialize();
                })
                .UseCastleWindsor(IocManager.Instance.IocContainer)
                .Build()
                .Run();
        }
    }
}

namespace JobProcessor
{
    [DependsOn(
        typeof(EntityFrameworkModule),
        typeof(CoreModule),
        typeof(AbpAspNetCoreModule)
    )]
    public class JobProcessorModule : AbpModule
    {
        public override void Initialize()
        {
            IocManager.RegisterAssemblyByConvention(typeof(JobProcessorModule).GetAssembly());
        }
    }
}

Any ideas?


text:
Q: Pivot key value data to row I have data in a table in a 'key-value' pairing format - for each Id you can have multiple key/value pairing values with additional column specifying Table value.
DataTable:
ID    Table  Key     Value
--    --     --      --
221   Tab1   Field2  Jon
221   Tab1   Field5  Snow
221   Tab1   Field4  Male
221   Tab1   Field3  Pass
2256  Tab1   Field2  Jil
2256  Tab1   Field5  Dark

Data in Key column refers to actual column name refered to by (table)data in Table column.
Now, I want pivot this data such that each ID is only represented as a single row in relevant table and data copied to appropriate column:
Tab1:
Id   Field1 Field2  Field3  Field4  Field5  Field6
--   --     --      --      --      --      --
221         Jon     Pass    Male    Snow
2256        Jil                     Dark

How do I go about writing this?

A: First, sample DDL/DML statements:
CREATE TABLE t (ID INT, [Table] VARCHAR(5), [Key] varchar(6), Value varchar(5))
INSERT INTO t VALUES (221, 'Tab1', 'Field2', 'Jon'),
(221 ,'Tab1','Field5','Snow'),
(221 ,'Tab1','Field4','Male'),
(221 ,'Tab1','Field3','Pass'),
(2256,'Tab1','Field2','Jil '),
(2256,'Tab1','Field5','Dark')

A static pivot query with hard-coded columns looks like this:
SELECT *
FROM t
PIVOT (MAX(Value) FOR [Key] IN ([Field1], [Field2], [Field3], [Field4], [Field5], [Field6]))p

Returns:
ID      Table   Field1  Field2  Field3  Field4  Field5  Field6
221     Tab1    NULL    Jon     Pass    Male    Snow    NULL
2256    Tab1    NULL    Jil     NULL    NULL    Dark    NULL

If you need to dynamically determine the columns from the data, here's an approach using sp_executesql:
DECLARE @sql NVARCHAR(MAX)
SELECT @sql = N'
SELECT p.*
FROM t
PIVOT (MAX(Value) FOR [Key] IN (' +
    STUFF((SELECT DISTINCT ',' + QUOTENAME([Key]) FROM t FOR XML PATH('')), 1, 1, '') + '))p
'
EXEC sp_executesql @sql

Returns:
ID      Table   Field2  Field3  Field4  Field5
221     Tab1    Jon     Pass    Male    Snow
2256    Tab1    Jil     NULL    NULL    Dark

This line:
SELECT STUFF((SELECT DISTINCT ',' + QUOTENAME([Key]) FROM t FOR XML PATH('')), 1, 1, '')

just brackets and delimits the columns into this string:
[Field2],[Field3],[Field4],[Field5]


text:
Q: @Autowired is resulted as null I am working with spring boot, In Controller, I tried to create an object using new operator, And tried to print object value its working.but for repository I used @Autowired but resulted in null
@RestController
public class SignupController {
    //@Autowired
    UserService userservice =new UserService() ;

    @GetMapping("/Allusers")
    public ResponseEntity<List<User>> allUsers() {
        System.out.print(userservice+"\n");
        List<User> userlist = userservice.getAllUsers();
        if (userlist.isEmpty()) {

            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }

        return new ResponseEntity<>(userlist, HttpStatus.OK);
    }

This is service class in which i Auto-wired "UserRepository userrepo;"
public class UserService {
     @Autowired
    UserRepository userrepo;

    public List<User> getAllUsers() {
        List<User> userlist = new ArrayList<User>();
        System.out.println(userrepo);
        userrepo.findAll().forEach(users -> userlist.add(users));
        System.out.println("hii");
        return userlist;
    }

A: Add the @Service annotation to UserService class and also a constructor to the same class. Like shown below;
@Service
public class UserService {

    private final UserRepository userrepo;

    public UserService(UserRepository userRepository) {
        this.userrepo = userRepository;
    }

    public List<User> getAllUsers() {
        List<User> userlist = new ArrayList<User>();
        System.out.println(userrepo);
        userrepo.findAll().forEach(users -> userlist.add(users));
        System.out.println("hii");
        return userlist;
    }
}

If you want to use @Autowired annotation, make sure that UserRepository class is annotated with @Service or @Controller or @Component. This is needed because, we need to say that the object is a Spring managed component.

A: Add @Service in UserService class and make sure UserRepository have @Repository. OR
    @Service
    public class UserService {

        private final UserRepository userRepository;

        public UserService(UserRepository userRepository) {
            this.userRepository= userRepository;
        }

        //your code
    }

Difference between new & @Autowired
@Autowired private UserDao userdao;

private UserDao userDao = new UserDaoImpl();

Performance
new
With the new approach, you get a new object every time, whether you want to or not. Even if UserDaoImpl is reusable, stateless and threadsafe (which DAO classes should strive to be) you will still create new instances of them at every place they are needed.
Consider a situation where the UserDaoImpl has implemented at multiple places which needs a Hibernate session, which needs a DataSource, which needs a JDBC connection - it quickly becomes a lot of objects that has to be created and initialized over and over again.
@Autowired
Springs dependency injection costs a little more in startup-time as the container has to be initialized and all managed objects set up. However, since you won't be creating new instances of your managed objects (assuming that is how you design them), you'll gain some runtime performance from less GC load and less object creation.
Scope
Another important thing is with spring annotation even you can manage object scope, but with new keyword no way(unless you do dumb singleton or something like that), I am sure with a new keyword you cannot have Prototype,  Request,  Single
Code Maintiblity
Consider 100 classes that uses UserDao class, And you get dao instance like that: private UserDao userDao = new UserDaoImpl(); in 100 places. Now consider a requirement changed and we need to use SomeOtherUserDao as class LdapUserDao implements UserDao, How we will handle new keywords, we tied impl class into usage.


text:
Q: Is $0^i$ indeterminate? According to Euler's identity

$$e^{ix}=\cos{x}+i\sin{x}$$

Using this identity

$$0^i=e^{i\ln{0}}=\cos\ln0+i\sin\ln0=\cos{-\infty}+i\sin{-\infty},\because \ln0=-\infty$$

But $\cos{-\infty}$ and $\sin{-\infty}$ are indeterminate Does it mean that $0^i$ is indeterminate.
Please Explain.

A: The critical point comes from the trigonometric functions. Instead, start from the equality
$$
e^{\ln x} = x
$$
which holds for every positive real $x$. Then $\lim_{x \to 0^+} x = 0$, $\lim_{x \to 0^+} = -\infty$ and $\lim_{x \to 0^+} e^{\ln x} = 0$, since $x \to e^x$ is continuous on $\mathbb{R}$ and tends to $0$ when $x$ tends to $-\infty$. Thus in this case, $e^{-\infty} = 0$ is an acceptable convention, which is actually frequently used in mathematics.
However, in your case, neither $\cos x$ nor $\sin x$ have a limit when $x$ tends to $-\infty$. I hope this explains the difference between the two cases.

A: $Lim_{x \to 0}x^i=Lim_{x \to 0}e^{i\ln x}=Lim_{x \to 0}\cos\ln x+i\sin\ln x$
$\because$ both $\cos{\ln{0}}$ and $\sin{\ln{0}}$ are indeterminate $0^i$ is indeterminate.

A: Perhaps you're confused because you expect that $0^x=0$ for any $x$. This is not true.
$0^x=0$ for any positive Real number $x$, but $0^x=\infty$ (or undefined) if $x$ is negative.
More generally, with Complex exponents,
$$b^{x+iy} = \exp\big((x+iy)\ln(b)\big)$$
$$= \exp\big(x\ln(b)+iy\ln(b)\big)$$
$$= \exp\big(x\ln(b)\big)\cdot\exp\big(iy\ln(b)\big)$$
$$= b^x\cdot\big(\cos(y\ln b)+i\sin(y\ln b)\big)$$
If we take a limit as $b\to0$, the left factor $b^x$ has the same behaviour as described above. The right factor (assuming that $y\neq0$) oscillates around the unit circle at increasing speed, because $\ln(b)\to{^-}\infty$.
If $x$ is positive, then $b^x$ damps out the oscillation, and $b^{x+iy}$ converges to $0$.
If $x$ is negative, then $b^x$ amplifies the oscillation, so it diverges.
If $x$ is exactly $0$, then $b^x=1$, and it still diverges (but not to infinity; it just spins around).
So a power of $0$ should be $0$ if the exponent's Real part is positive, $\infty$ (or undefined) if the Real part is negative, and indeterminate (or undefined) if the Real part is $0$.
(Exception: $0^0=1!$)

A: As you point out, one can not define $0^i$ via the identity of Euler. The question is whether we can find any other good properties of $0^i$. For me good properties would be that the function $f:x\mapsto x^i$ is continuous. This function is basically defined for $\mathbb{C}\backslash\mathbb{R-}$, where the $log function is not defined.
Can we extend the definition of the function to $0$?
For this we see
$$\lim_{x\in\mathbb{R},x\rightarrow 0} x^i =$$
$$=\lim_{x\in\mathbb{R},x\rightarrow 0} e^{i\cdot log(x)}$$
This limit does not converge, so we do not have any continuous extension to $0$


text:
Q: filter with prefetch_related I want to know how I can filter my def to see only questions for the filtered patient.
I have try this:
def detail3(request, patient_id):
    patient = get_object_or_404(Patient, pk=patient_id)
    questions = Question.objects.filter(patient=patient_id).prefetch_related('reply_set').all().order_by('pub_date')
    return render_to_response('PQR/detail3.html', {'questions_list': questions, 'patient': patient })

patient=patient_id => When I start my views with my template i have this result :

"Cannot resolve keyword 'patient' into field."

I have no idea why this error is happening because when i try another solution with the same argument (patient=patient_id)I have no problem !
def detail2(request, patient_id):
    tab_replies = []
    patient = get_object_or_404(Patient, pk=patient_id)
    questions = Question.objects.all().order_by('pub_date')
    for question in questions:
        tab_replies.append(question.reply_set.filter(patient=patient_id))
        replies_per_question = zip(questions, tab_replies)
    return render_to_response('PQR/index.html', {'questions_list': replies_per_question, 'patient': patient })

So what is the solution for filter my questions with patient_id with the method prefetch_related ?
Thanks you for you help !
This is my models.py
class Patient(models.Model):
    name = models.CharField(max_length=50)

    def __unicode__(self):
        return self.name + ' [' + str(self.id) + ']'

    def listReply(self):
        replies = Reply.objects.filter(patient= self.id)
        return replies

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __unicode__(self):
        return self.question_text

class Reply(models.Model):
    question = models.ForeignKey(Question)
    patient = models.ForeignKey(Patient)
    reply_text = models.CharField(max_length=200)

    def __unicode__(self):
        return str(self.reply_text)

A: You're trying to filter by a field in the Question model that does not exist:
Question.objects.filter(patient=patient_id)

patient is not a Question field and this is why you're getting this error.
In your Reply model, add a related_name property to the question field:
question = models.ForeignKey(Question, related_name="replies")

Then you can query the list of questions with replies by a specific patient by doing:
Question.objects.filter(replies__patient=patient_id)


text:
Q: View controller origin changes every time it's presented This is what my view controller should be:

This is what it is sometimes:

I want to display a view controller in the circle, however, almost every time the view controller in the circle (ResultViewController) is presented, it's place is different, though its properties doesn't change at all. Here's my code:
func openCircle(withCenter center: CGPoint, dataSource: ([Items], Int, String)){
    self.addCircle(withCenter: center, dataSource: dataSource)
}

func addCircle(withCenter circleCenter: CGPoint, dataSource: ([Items], Int, String)) {

    let longerSide = fmax(view.frame.size.height, view.frame.size.width)
    let shorterSide = fmin(view.frame.size.height, view.frame.size.width)

    let circleRadius = longerSide / 2
    var resultViewOrigin = CGPoint()
    var resultViewSize = CGSize()

    if UIDevice.current.userInterfaceIdiom == .pad {

        let rectWidth = shorterSide / 2
        let rectHeight = sqrt(abs(circleRadius * circleRadius - rectWidth * rectWidth)) + view.frame.size.height - circleCenter.y
        resultViewSize = CGSize(width: rectWidth, height: rectHeight)
        resultViewOrigin = CGPoint(x: (view.frame.size.width - rectWidth) / 2, y: view.frame.size.height - rectHeight)

    } else {
        resultViewOrigin = CGPoint(x: 0.0, y: 0.0)
        resultViewSize = CGSize(width: view.frame.size.width, height: view.frame.size.height)
    }

    let resultViewController = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "ResultVC") as! ResultViewController
    resultViewController.transitioningDelegate = self
    resultViewController.modalPresentationStyle = .custom
    resultViewController.dataSource = dataSource
    resultViewController.view.frame = CGRect(origin: resultViewOrigin, size: resultViewSize)

    transition.circle = UIView()
    transition.startingPoint = circleCenter
    transition.radius = circleRadius
    transition.circle.frame = circleFrame(radius: transition.radius, center: transition.startingPoint)

    present(resultViewController, animated: true)
}

It works well on the iPhone, not on the iPad, what's the problem?

A: I found the problem, it's actually a missing constraint on Regular-Regular size class caused this problem, I fixed it by adding a spacing to bottom layout guide to the part that used to get misplaced.
Thanks to everybody for your idea.

A: You can use a container view  instead of presenting the view controller. You can create them programmatically or in interface builder (see Apple docs).


text:
Q: Detect old Internet explorer Javascript functions ( < ES6) There is a web online, library or something to detect old IE functions that are not compatible with Chrome/Firefox or just ES6?
Like: document.all, event.returnValue, etc
JsHint/Jslint are not detecting them as deprecated or incompatibles

A: It's not quite fair to say JSLint won't tell you about deprecated properties. Let me explain.
Recall first that JavaScript is a dynamic language. You can assign any property to [almost] any object. You could assign all to window in a browser context if you wanted just by saying window.all = "Muahahaha!!! I'm evil!!!". You could add .all to a string with...
var spam = "a string";
spam.all = "I'm still evil!!!"

Or, worse, some piece of code could have changed the prototype for String (or any other object type) somewhere outside of your file. Try this in a browser console:
String.prototype.all = String.prototype.all || "This is beyond evil.";
// 'This is beyond evil.'
var spam = "spam"
// undefined
spam.all
// 'This is beyond evil.'

So JSLint doesn't, by default, check for properties on objects by names. Especially for objects that could live outside of your file's context (because JSLint lints file-by-file), it simply can't know what's happened to an object's properties and identify what's valid and what isn't.
(That's what TypeScript is for, btw.)
Unless you tell JSLint how!! -- the JSLint property directive ftw
Or you can use the JSLint property directive, which does exactly what you want, if you're willing to do some work.
If you put the property directive at the top of your file, JSLint will show errors for any properties that are used by objects on the page that aren't in that list.
For instance, try this on the official JSLint.com page:
/*property
    log
*/
/*jslint browser, devel */
function mySpam() {
    var spam = document.all;
    console.log(spam);
}

See how I'm using document.all but all isn't in the property directive? It's going to error for me.
1. Unregistered property name 'all'.
    var spam = document.all;

You might be saying, "But it will take me FOREVER to get all the good properties from my 3000 line file I'm linting into that directive!!"
Not so! Here's a tip: Paste your file, even unlinted, into JSLint.com. It will create a property directive for you in its report.
Here's one I made from AngularJS' [sic] route.js in just a few seconds:
/*property
    $$minErr, $evalAsync, $get, angularVersion, caseInsensitiveMatch, create,
    defaultPrevented, eagerInstantiationEnabled, extend, info, isArray,
    isDefined, isObject, isUndefined, length, module, noop, originalPath,
    otherwise, preventDefault, provider, redirectTo, reload, reloadOnSearch,
    reloadOnUrl, routes, run, substr, when
*/

Alphabetical, even.
Now just remove the ones you don't want and presto! You'll catch everything you need.
Is this a little tedious, and will it take a little massaging/training on files that use document properly? Yes, but, again, in a dynamic language, this is close to the best you can hope for with file-by-file linters.
NOTE: If this doesn't solve your issue, however imperfectly, that's when we need to see more of your files and hear more precisely what problem you're trying to solve in practice.


text:
Q: How to prevent repeating combinations of two random numbers? Here my my code for generating the three-word combinations (combo_generator.php):
<?php

include "db_connect.php";

// Query database of words
$words_sql    = "SELECT * FROM words";
$words_res    = mysqli_query($db, $words_sql)or die(mysqli_error());

// Create array of words
$array  = array();

// Loop through each word and add each to the array
while($row = mysqli_fetch_array($words_res)){
     $array[] = $row['word'];
}

// Set $word1 as random word from $array
$ran_num = array_rand($array);
$word1   = $array[$ran_num];

// Remove the chosen word from the array
array_splice($array, $ran_num, 1);

// Reset the array
$array2 = $array;

// Set $word2 as random word from $array
$ran_num2 = array_rand($array2);
$word2    = $array2[$ran_num2];

// Set variables
$word        = 'star';
$three_words = "$word.$word1.$word2";

echo $three_words;

?>

Here is my code for assigning a random three-word combination to each star from the database (test.php):
<?php

include "db_connect.php";

// Pull all stars from database
$stars_sql = "SELECT * FROM stars";
$stars_res = mysqli_query($db, $stars_sql)or die(mysqli_error());

// Loop through every star in the array
while($row = mysqli_fetch_array($stars_res)){
     // Store the star name in a variable
     $star = $row['star_name'];

     // Create a random 3-word combination
     include "combo_generator.php";

     // Attach the random 3-word combination to the star
     echo $star.'    '.$three_words.'

';
}

?>

I'm trying to generate three-word combinations in the form star.word1.word2, where word1 is a random word from the database, and word2 is a different random word from the database (word1 != word2). Each combination that is generated is then assigned to a star from the database.
How do I avoid repeating combinations? By repeating combinations I mean the following:
Combination 1: star.lamp.chair; Combination 2: star.dog.ball; Combination 3: star.ball.dog; Combination 4: star.lamp.chair
Here, combination 1 and combination 4 are the same - this repetition is what I want to avoid. The order is not important, so combination 2 and combination 3 are fine.

A: You could save which combinations were already created.
Create a global array (=a variable in test.php) that represents all already created combinations:
/*@var $createdCombinations array*/
$createdCombinations=[];

Then, before just echoing your new combination, check if it has been already created. If not, add it to the array. If yes, create a new combination.
Like so:
// ...

while(true){
    // Set $word1 as random word from $array
    $ran_num = array_rand($array);
    $word1   = $array[$ran_num];

    // ...

    if(!in_array($three_words,$createdCombinations)){
        $createdCombinations[]=$three_words;
        echo $three_words;
        break;
    }
}

Other parts of the code can stay the same, so they were omitted.

A: You could create an array with all possible word pairs, and then do the pick-and-remove from that array:
<?php

// Retrieve a list of words from the DB and build the pairs list
include "db_connect.php";

// Query database of words
$words_sql = "SELECT * FROM words";
$words_res = mysqli_query($db, $words_sql)or die(mysqli_error());

// Create array of words
$array  = array();

// Loop through each word and add each to the array
while($row = mysqli_fetch_array($words_res)){
    $array[] = $row['word'];
}

// Create all valid pairs
$pairs = array();
foreach ($array as $word1) {
    foreach ($array as $word2) {
        if ($word1 !== $word2) {
            $pairs[] = "$word1.$word2";
        }
    }
}

// Pull all stars from database
$stars_sql = "SELECT * FROM stars";
$stars_res = mysqli_query($db, $stars_sql)or die(mysqli_error());

// Loop through every star in the array
while($row = mysqli_fetch_array($stars_res)){
    // Store the star name in a variable
    $star = $row['star_name'];

    // Set $pair as random word from $pairs
    $ran_num = array_rand($pairs);
    $pair = $pairs[$ran_num];

    // ... and remove it
    array_splice($pairs, $ran_num, 1);

    // Set variables
    $word        = 'star';
    $three_words = "$word.$pair";

    // Attach the random 3-word combination to the star
    echo $star.'    '.$three_words.'

';
}

?>


text:
Q: Mopub: Testing Facebook Audience Network Native Ad integration I'm unsure how one can test Facebook Audience Network integration with Mopub. On the Facebook Audience Network page on testing, it doesn't reveal any information on testing integration with Native ads :
https://developers.facebook.com/docs/audience-network/testing
In the mopub docs, I have completed all the steps for integration with a Third Party Ad Network:
https://github.com/mopub/mopub-android-sdk/wiki/Integrating-Native-Third-Party-Ad-Networks
I have also completed this part of the tutorial on self-testing your creatives by creating an inventory item which is a native ad and an test order that serves the native ad. This works successfully for my app but this is a my very own created ad, it is not a facebook ad:
https://dev.twitter.com/mopub-demand/overview/self-testing-your-creatives
INVENTORY SCREEN:
It shows the ad source breakdown and this does not include Facebook Audience Network.

ORDER SCREEN
The screen shows my very own created order which works with my app. I can see my own creative within my app:

NETWORK SCREEN
This is the network screen showing that I have added FacebookAudienceNetwork:

This is the configuration for the FacebookAudienceNetwork:

The Facebook placement_id is darken out in the picture below, but it matches with the one on facebook.
Facebook website:

How do I know that Facebook Audience Network has been integrated successfully with MoPub for native ads - is there a way to test this?

A: I finally solved this through a response from MoPub from their support staff. The below is the email I was sent. Hopefully, this will also help someone else with their integration:

Thanks for reaching out!  When you tested your integration were you
  able to see the MoPub test creative for your native ad unit?  If so,
  that means your initial MoPub integration is correct.
Next, you'll want to target FAN against your ad units.  To do this
  please follow these steps:

*

*Go to the "Segments" tab in the MoPub UI

*Click the specified segment you want to set (Note: Accounts will automatically be set with a Global Segment on creation. This would be
  the segment most people would need to navigate to to set the ad
  network for the specific ad unit. This changes if a new segment is
  created and has specific targeting as new segments will override the
  Global Segment for their specific parameters.)

*There is a filter set to show only running ad sources. You want to close the tab for this that says "Status:Running" inside the filter
  box to see the rest of the ad sources.

*Click the drop down for the ad unit you want to change

*Edit the ecpm of the ad source

*Click "Set"

  After Facebook is enabled on your ad unit, you can start testing live
  Facebook ads.  You will want to make sure you have the Facebook app
  installed on your device with a Facebook account set up against it in
  order to see ads.  Additionally, you will want to make sure you are
  using the MoPub certified version of the FAN SDK, which is 4.8.1 for
  Android.
If you aren't seeing any Facebook ads after you complete these testing
  steps please let us know.  Be sure to include device logs in your
  response so we an get a better idea of what is going on when you try
  to call FAN ads.

Just to clarify as well in the docs MoPub refers that you need to put the extra adapters inside your 'src' folder in your android app. I found that by doing this, I ended up getting a log message saying that FacebookNative.java file is not found.
You will need to add the extra adapters into your main -> java folder for android to detect them.