text:
Q: Calling a jQuery function from a PHP file I am having problems trying to activate a jQuery function from a PHP.
The following is my own test version.
index.php file
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"           "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Welcome to temp index</title>

    <link rel="stylesheet" href="style.css" type="text/css" />

hello

PHP file I am attempting to call my jQuery function from
<?php

if( $_REQUEST["activate"])
{
  $activate = $_REQUEST['activate'];
};

if($activate == 'colourchange')
{
 // This is the code that I believe not to be working as this isn't
 // activating the jQuery function to work. (The page background isn't changing colour)

    echo "";
};

?>

Thank you to anyone who has an idea of what to do it is much appreciated.
I have now tried ...
<?php
require 'userinfo.php';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>Welcome to temp index</title>

<link rel="stylesheet" href="style.css" type="text/css" />

hello

and the PHP index file is ...
<?php

if( $_REQUEST["activate"])
{

  $activate = $_REQUEST['activate'];

};

  if($activate=='colourchange')
  {
    echo "colourchange();";
  };

?>

A: I don't exactly understand why you are using PHP to execute a jQuery function at all - perhaps this is just an oversimplified example. Assuming your primary goal is to have the PHP response trigger a specific Javascript function (and perhaps allow for the PHP response to trigger several different responses) you'd do something like this:
First change the callback from
function(data){
  $('report').html(data);
}

to something like:
function(data) {
  if (data.indexOf("colourchange") >= 0) {  // php page returned "colorchange" or a string containing "colourchange"
     colourchange();
  } else if (data.indexOf("moodchange") >= 0) {
     moodchange();  /// etc... you can add more trigger functions here
  }
}

And second... just have your PHP page return "colourchange" instead of an HTML snippet:
if($activate == 'colourchange')
{
  echo "colourchange";
};

Does that help?

A: you could try this-- example call the jquery function on success
  $.ajax({
     url: //the url,
     data: //the data,
     type: "POST",
     success: function(data){

         if(data == "ok"){
        colorChange();
        }
     }
   });

here the data will be the success result returned by the php code..
you can call a function depending on the data returned


text:
Q: How to nicely split on multiple lines long conditionals with OR on ansible? I already know that if you have long conditionals with and between them you can use lists to split them on multiple lines.
Still, I am not aware of any solution for the case where you have OR between them.
Practical example from real life:
when: ansible_user_dir is not defined or ansible_python is not defined or ansible_processor_vcpus is not defined

This line is ugly and hard to read, and clearly would not fit a 79 column.
How can we rewrite it to make it easier to read?

A: Use the YAML folding operator >
when: >
  ansible_user_dir is not defined or
  ansible_python is not defined or
  ansible_processor_vcpus is not defined

As the ansible documentation states:

Values can span multiple lines using | or >. Spanning multiple lines using a Literal Block Scalar | will include the newlines and any trailing spaces. Using a Folded Block Scalar > will fold newlines to spaces; it's used to make what would otherwise be a very long line easier to read and edit. In either case the indentation will be ignored.

Additional info can be found here:

*

*https://yaml-multiline.info/

*https://docs.ansible.com/ansible/latest/reference_appendices/YAMLSyntax.html

*http://yaml.org/spec/1.2/spec.html#id2760844

A: While you should use yaml operators and syntax for majority of the Ansible code, you don't have to use yaml operators with when: conditional. Take a look at official docs. When conditional can be really flexible depends on your need. I think it works because when conditionals are already an expression and evaluated by Jinja2 directly, hence you don't use {{ }} in when condition.
Another great reference: https://stackoverflow.com/a/57600771/9720375
---
- name: Test multiline when condition
  hosts: all
  gather_facts: false
  strategy: linear
  tasks:
    - name: Should run
      debug:
        msg: "print this if works"
      when:
        - true
        - false or
          true

    - name: Should run
      debug:
        msg: "print this if works"
      when:
        - true
        - true or
          false

    - name: Should run
      debug:
        msg: "print this if works"
      when:
        - false or true

    - name: Should skip
      debug:
        msg: "print this if works"
      when:
        - false
        - false or true

    - name: Should run
      debug:
        msg: "print this if works"
      when:
        false or true

    - name: Should skip
      debug:
        msg: "print this if works"
      when:
        false or
        false

    - name: Should run
      debug:
        msg: "print this if works"
      when: (false or true) or (false and true)

    - name: Should run
      debug:
        msg: "print this if works"
      when: (false or false) or
            (true and true)

redpajama_set_name: RedPajamaStackExchange


text:
Q: iOS Mapkit - dequeueReusableAnnotationView with Interface Builder XIB Is there a way to create a custom annotation view in the interface builder (XIB), but also make use of MapKit's dequeueReusableAnnotationView method?
The use of dequeueReusableAnnotationView seems to imply that we are just using a subclass of MKAnnotationView where you can draw all subviews programmatically.
I am properly registering my custom AnnotationViews via the MapView.register() method
I'm struggling to find a way to use dequeueReusableAnnotationView and the XIB for the custom view.


text:
Q: Adaptive mesh in FreeFem++ I'm trying to improve my FreeFem++ code by adapting my initial mesh at certain time steps but FreeFem++ comes up with this error message:
Exec error : Try to get unset x,y, ...

after the mesh is indeed adapted. The problems seems to appear when computing the solution in the new mesh, but I haven't had this problem in other cases though. This is how I adapt the mesh in FreeFem++ and update the variables:
Th = adaptmesh(Th,[u1,u2]);
plot(Th);
u1 = u1;
u2 = u2;
p  = p;

but now I'm confused on how to proceed after the warning message.
Does anybody know how to solve this? Any piece of advice will be appreciated.
Thanks!

A: I know this is a very old question, but my following answer is for those who still want to.
I ran into the same error when trying to output (cout) a FE variable uh, it's solved if we try uh[] instead. In this case, it's an array.
Vh uh = x;
cout << uh << endl; // error
cout << uh[] << endl; // good

Hope you can check the same thing for your problem.


text:
Q: Configure Json.NET serialization settings on a class level and its nesting class properties This is a follow up to this question:
Configure Json.NET serialization settings on a class level
I have a class with properties of other classes
internal class Program
{

    [JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
    public class Foo
    {
        public string Bar;
        public NestedFoo NestedFoo { get; set; }
    }
    public class NestedFoo
    {
        public string NestedBar;
    }

    static void Main(string[] args)
    {

        Foo c = new();
        c.NestedFoo = new();
        c.Bar = "Bar";
        c.NestedFoo.NestedBar = "NestedBar ";
        string output = JsonConvert.SerializeObject(c, Formatting.Indented);

        Console.WriteLine(output);
    }
}

The output result is:
{
  "bar": "Bar",
  "nestedFoo": {
    "NestedBar": "NestedBar "
  }
}

With the above example, the NamingStrategyType apply to the main class members only. The members inside the NestedFoo did not follow the NamingStrategyType
Means NestedBar should be serialized as nestedBar
I know I have the following options, but I prefer to get the intended result using an attribute at the top level class:

*

*apply [JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))] to the every class inside.

*Supply the naming strategy to the JsonConvert.SerializeObject.

Is there any way to have the attribute [JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))] apply to a top level class and all its nested properties?


text:
Q: Data Transformer on multiple fields and parent entity I've been searching for a while, but was not able to find specific documentation on my DataTransformer use-case. Ofcourse there is the Symfony2 cookbook chapter, but it does not resolve my specific use-case. I could only find info on transforming a single field.
Entities
I've got two entities (with a 0..n relationship)
Order

*

*priceTotal (other fields aren't relevant)

OrderLine

*

*amount

*priceFactor

*pricePerPiece

*priceTotal

Use-case
I do not want to calculate the Order->priceTotal on the fly in the view every time. That is why I'd like to create a transformer on the OrderLine that recalculates a couple of values on submit:

*

*The Order->priceTotal should be a sum of all OrderLine->priceTotal

*The OrderLine->priceTotal should be (amount * priceFactor * pricePerPiece)

Since I don't want to put this logic in every Controller function, I assume the DataTransformer is correct solution (?). Is the FormType the correct level for this type of validation?

A: I don't think a DataTransformer is what you're looking for. A DataTransformer can mutate the submitted content for one field in your form, but does not have access to any fields around it. This is probably something you'll want to do with LifeCycleCallbacks.
http://docs.doctrine-project.org/en/2.0.x/reference/annotations-reference.html#annref-haslifecyclecallbacks
Here is an example of how LifeCycleCallbacks are used:
http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html
It does not reflect what you want to do, but it will teach you what LifeCycleCallbacks are and how to use them.


text:
Q: LocalBroadcastManager don't receive broadcast on 2.3 Not works on 2.3. But works on 4.0.x. Why?
Sending from IntentService:
intent.setAction(MessagesThread.NEW_MESSAGE);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

Receiving
protected void onStart() {
super.onStart();
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,new IntentFilter(NEW_MESSAGE));
}

protected void onStop() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onStop();
}

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
    .......................................
            .......................................
}
};

A: I am not sure, but the issue might be due to LocalBroadcastManager. Try sending broadcast without using LocalBroadcastManager, like below:
SEND BROADCAST
Intent i = new Intent("ALERT_CHANGE");
i.putExtra("DATA","News");
sendBroadcast(i);

RECEIVE BROADCAST-in Activity
registerReceiver(uiUpdated, new IntentFilter("ALERT_CHANGE"));

private BroadcastReceiver uiUpdated= new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent)
{
String DATA = i.getStringExtra("Data");
txt.settext(DATA);
}
};

A: LocalBroadcastManager.getInstance(this).sendBroadcast(newIntent(MessagesThread.NEW_MESSAGE).putExtras(intent));


text:
Q: Using a string to represent the criteria for an if function in VBA I was hoping someone will have an answer to this. I don't think it is possible but what I am trying to do is set up an if function using a string as the criteria. For example:
With ThisWorkbook.Worksheets("Sheet1")
    stNumerator = .Cells(6, 3).Value
    stDenominator = .Cells(6, 4).Value

    If .Cells(7, 3) = "x" Then
        stCriteria = stNumerator & " >0"
    End If

    If .Cells(8, 4) = "x" Then
        stCriteria = stCriteria & " and " & stDenominator & " <>0"
    End If

    If stCriteria Then
         .Cells(1, 1) = stNumerator / stDenominator
    End If

So stCriteria should equal stNumerator > 0 and stDenominator <>0

A: What you want can be achieved using Application.Evaluate
Here is an example
Sub Sample()
    Dim stCriteria1 As String, stCriteria2 As String

    With ThisWorkbook.Worksheets("Sheet1")
        stNumerator = .Cells(6, 3).Value
        stDenominator = .Cells(6, 4).Value

        If .Cells(7, 3) = "x" Then stCriteria1 = stNumerator & " >0"
        If .Cells(8, 4) = "x" Then stCriteria2 = stDenominator & " <>0"

        If stCriteria1 <> "" And stCriteria2 <> "" Then
            If Application.Evaluate(stCriteria1) And _
            Application.Evaluate(stCriteria2) Then
                 .Cells(1, 1) = stNumerator / stDenominator
            End If
        ElseIf stCriteria1 <> "" Then
            If Application.Evaluate(stCriteria1) Then
                 .Cells(1, 1) = stNumerator / stDenominator
            End If
        ElseIf stCriteria2 <> "" Then
            If Application.Evaluate(stCriteria2) Then
                 .Cells(1, 1) = stNumerator / stDenominator
            End If
        End If
    End With
End Sub


text:
Q: How do I keep a list of numbers I have already enountered? I am currently working on a BASIC simulator in Python, as the title suggests.  Here is my code for this problem:
def getBASIC():
   l = []
   x = 1
   while x == 1:
      i = input()
      l.append(i)
      if len(i.split()) != 3:
         x = 0
   return l

def findLine(prog, target):
   for l in range(0, len(prog)):
      progX = prog[l].split()
      if progX[0] == target:
          return l

 def execute(prog):
      location = 0
      visited = [False] * len(prog)
      while True:
        T = prog[location].split()[2]
        location = findLine(prog, T)
        visited[location] = True
      if visited[len(visited)-1] == False:
          return "infinite loop"
      else:
          return "success"

The first function does what it is intended to do -- convert input of BASIC code into a list.  The second function, findLine also does what it is intended to do, in that it finds the item which contains the string equal to the input.  The last function, however, I cannot get to work.  I know what I have to do, and that is to check whether or not a part of it has been visited twice.  I cannot figure out how to do this, due to the existence of the while loop.  As a result of this, the second half of that function is just placeholder.  If you could help me figure out how to solve this, it would be greatly appreciated.  Thanks.

A: You keep a list of places that have been visited (you already do this) and then when you encounter a goto, you check if it does to a line that already have been visited, and if it has been visited, you exit.
One mistake right now is that you make a list that is as long as the program is. That's pretty pointless. Just keep a list of the visited line numbers instead, and check with
if current_line in visited:

A: Try adding an if statement declaring a line in the visited list to be true when it is encountered in the loop.  This is my solution:
    def execute(prog):
       location = 0
       visited=[False]*len(prog)
   while True:
           if location==len(prog)-1:
           return "success"
       if visited[location]==True:
           return "infinite loop"
       if visited[location]==False:
           visited[location]=True
       line2strings=prog[location].split()
       T=line2strings[-1]
       location=findLine(prog, T)


text:
Q: Do you need to synchronize a buffer if only one thread adds and only one (different) thread removes? I hava a java application that uses Buffers to pass object around between threads.  Generally I synchronize these buffers using BufferUtils.  If I have just one thread that adds objects to a buffer, and only adds, and just one other thread that removes objects from the buffer, and only removes; does the buffer between them need to be synchronized?
I have a situation now where the two threads in question are instantiated from spring beans and can only get their hands on the shared buffer by having a third bean for the buffer that they both reference.  I couldn't figure out how to make a synchronized buffer from a bean, hence the question regarding whether or not it was necessary.

A: Perhaps you could use a BlockingQueue to pass those objects around. And the blocking queue is thread safe. Plus it offers several put/get variants that can be used nicely.
The method put, for instance, will make the thread block until there is enough room in the queue.
Offer method, can be used with a timeout, so if it doesn't manage to add to the queue it will return false.
You could check it out
BlockingQueue

A: Yes the buffer will need to be synchronized. Per the Java memory model if more than one thread are accessing the same datastructure without synchronization there is no guarantee that changes made by one thread are visible to the other threads. Some form of the BlockingQueue should do the trick.

A: I would use an Exchanger.  This allows two threads to swap to buffers (the producer a full buffer and the consumer an emptied buffer)
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Exchanger.html
My article on the Exchanger for swapping ByteBuffers.
http://vanillajava.blogspot.com/2011/09/exchange-and-gc-less-java.html


text:
Q: html input field search items in database only first letter I want to do an SQL search query where if the user inputs the name of an item it searches the database for that item but I also want to have it so if the user only inputs one letter it give all the items that match with that letter as the first letter.
string sql = "SELECT * FROM inventory WHERE ItemName = @search AND Location_id = @location  ";

A: What you're looking for is the LIKE functionality. You use wildcards to add "rules" to your search query. Check this out.
https://www.w3schools.com/sql/sql_wildcards.asp


text:
Q: Is it possible to make pytest report if a function is never called directly in a test? Example
def main(p):
    if foo_a(p):
        return False
    return p**2

def foo_a(p):
    return p % 11 == 0

Now you can get 100% test coverage by
import unittest
from script import main

class Foobar(unittest.TestCase):
    def test_main(self):
        self.assertEquals(main(3), 9)

But maybe one wanted foo_a to be p % 2 == 0 instead.
The question
Branch coverage would shed a light on it, but I would also like to know if a function was never called "directly" by a test (such as main is in the example), but only indirectly (such as foo_a in the example).
Is this possible with pytest?

A: First of all just general line of thought is to unittest foo_a as well
import unittest
from script import main, foo_a

class Foobar(unittest.TestCase):
    def test_main(self):
        self.assertEquals(main(3), 9)

    def test_foo_a(self):
        self.assertEquals(foo_a(11), True)

You are probably looking for https://coverage.readthedocs.io/en/coverage-4.5.1/ which can be used with pytest https://pypi.org/project/pytest-cov/, this tool can show you exactly which lines of code had been called during testing
But I think there is another way to check your problem it is called mutation testing, here are some libraries that could help you with it
https://github.com/sixty-north/cosmic-ray
https://github.com/mutpy/mutpy
And also look into property based testing libraries like https://github.com/HypothesisWorks/hypothesis/tree/master/hypothesis-python


text:
Q: Why does invoking PowerShell from C# throw a System.Management.Automation.CommandNotFoundException? I'm using this c#:
    public bool RunPowershell(string script)
    {
        RunspaceConfiguration runspaceConfig = RunspaceConfiguration.Create();

        using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfig))
        {
            runspace.Open();

            using (RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace))
            {
                scriptInvoker.Invoke(script);
            }
        }

        return true;
    }

To run this script:
      Add-PSSnapin -name Microsoft.SystemCenter.VirtualMachineManager
      $vmm = Get-VMMServer -ComputerName "VmmComputerName"

It works ok on a Windows 2003 32bit OS, but on a Windows 2008R2 64bit, I get this error:
System.Management.Automation.CommandNotFoundException: The term 'Get-VMMServer' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
at System.Management.Automation.CommandDiscovery.LookupCommandInfo(String commandName, CommandOrigin commandOrigin)
at System.Management.Automation.CommandDiscovery.LookupCommandProcessor(String commandName, CommandOrigin commandOrigin, Nullable`1 useLocalScope)
at System.Management.Automation.CommandFactory._CreateCommand(String commandName, CommandOrigin commandOrigin, Nullable`1 useLocalScope)
at System.Management.Automation.ExecutionContext.CreateCommand(String command)
at System.Management.Automation.CommandNode.CreateCommandProcessor(Int32& index, ExecutionContext context)
at System.Management.Automation.CommandNode.AddToPipeline(PipelineProcessor pipeline, ExecutionContext context)
at System.Management.Automation.PipelineNode.Execute(Array input, Pipe outputPipe, ArrayList& resultList, ExecutionContext context)
at System.Management.Automation.ParseTreeNode.Execute(Array input, Pipe outputPipe, ExecutionContext context)
at System.Management.Automation.AssignmentStatementNode.Execute(Array input, Pipe outputPipe, ExecutionContext context)
at System.Management.Automation.StatementListNode.ExecuteStatement(ParseTreeNode statement, Array input, Pipe outputPipe, ArrayList& resultList,     ExecutionContext context)

And, I have got Microsoft.SystemCenter.VirtualMachineManager installed. The script also works if I manually type it in to the power-shell console on the 2008R2 machine.
Can you please help on any ideas for what I might be missing?
Thanks very much.

A: This occurs because powershell snap-in metadata is recorded in the registry. In your case, this means that the snap-in info is only available in the 32 bit software hive in the registry. Normally the trick to make it available is to use the 64 bit version of  the .NET framework's installutil.exe (in the framework64 directory) to register it, but sometimes it's 32 bit only for a reason. It may be depending on 32 bit COM objects that are not available in a 64 bit environment.
So you have two approaches:
1) register the snap-in for 64 bit by using installutil.exe /i  (unlikely to work)
or
2) target your .NET exe for 32 bit only via VS project properties (anycpu -> x86)
or
3) wrap your work up in a script like this: http://www.nivot.org/blog/post/2012/12/18/Ensuring-a-PowerShell-script-will-always-run-in-a-64-bit-shell
-Oisin

A: Here's an example that handles named parameters and worked for my needs. Original was taken from the linked option in x0n's post. See the linked post for additional details. I'm executing this script from a C# console application that has 3rd party dependencies on x86.
param([string[]]$listOfVMNames, [string]$userName, [string]$resourceGroupName, [int]$waitForJob)
if ($pshome -like "*syswow64*") {
    & (join-path ($pshome -replace "syswow64", "sysnative") powershell.exe) -file `
        (join-path $psscriptroot $myinvocation.mycommand) -listOfVMNames (,$listOfVMNames) -userName $userName -resourceGroupName $resourceGroupName -waitForJob $waitForJob
    exit
}


text:
Q: Angular 1.5 routing(ngRoute) refresh/reload issue in MVC 5 I've been going through a lot of the posts about routing mvc/angular how to use it together but still was not able to make it work.
I have problem with the page refresh/reload when being on the angular view/route, it's just wont work.
Here is what I got so far:
Anguar Route Provider - routes to my components:
$routeProvider
            .when('/angular/test1', {
                template: '<sample-component1></sample-component1>'
            })
            .when('/angular/test2', {
                template: '<sample-component2></sample-component2>'
            });

$locationProvider.html5Mode(true);

MVC Web config:
<rewrite>
  <rules>
    <rule name="AngularJS" stopProcessing="true">
      <match url=".*" />
      <conditions logicalGrouping="MatchAll">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_URI}" matchType="Pattern" pattern="^(?!.*angular/).*$" negate="true" />
      </conditions>
      <action type="Rewrite" url="/" />
    </rule>
  </rules>
</rewrite>

My MVC routes configuration:
routes.MapRoute(
                name: "angular",
                url: "angular/{*catch-all}",
                defaults: new { controller = "Home", action = "Angular" }
                );
   routes.MapRoute(
                name: "Default",
                url:"{controller}/{action}/{id}",
                defaults:new { controller = "Home", action = "Index", id = UrlParameter.Optional });

Currently when I refresh page I'm getting redirected to the default route, additionally the layout is messed up even though the references seems to be in place...
What's the issue?

A: I guess you are just allowing files from angular folder only. I'd say change your condition would fix the issue.
<conditions logicalGrouping="MatchAll">
    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>

A: Limit your Default route to the Home controller by specifying a constraint and then the catch-all route will start to work.
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    constraints: new { controller = "Home" } // for catch all to work
);

// Route override to work with Angularjs and HTML5 routing
routes.MapRoute(
    name: "NotFound",
    url: "{*catchall}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

A: My solution was like this :

*

*MVC routing

routes.MapRoute(
              name: "Application",
              url: "{*url}",
            defaults: new { controller = "Home", action = "Index" });

*Angular routing

   $routeProvider.
            when("/App/", {
                templateUrl: scriptPath + "A.html?v=1.6",
                controller: "AController"
            })
            . when("/App/home", {
                templateUrl: scriptPath + "A.html?v=1.0",
                controller: "AController"
            })
            .when("/App/B", {
                templateUrl: scriptPath + "B.html?v=1.0",
                controller: "BController"
            })
           .when("/App/C", {
                templateUrl: scriptPath + "C.html?v=1.0",
                controller: "CController"
            })
            .otherwise({ redirectTo: '//App/home'});

        $locationProvider.html5Mode({ enabled: true, requireBase: false });

this section I put in app.js and loaded with _Layout.cshtml so I can have it on every page that will use the same layout.
So to fix server reload issue I just create the corresponding controllers (A,B,C) with default action (index) and returned empty view that use _Layout.cshtml
so when user click on links and moving around with angular the URL will be changed in the way that mvc will understand and if user click on Refresh button it will load the page that will load angular routing and continue with it .
All other solution that I found were suggested to change web config and put rewrite rule or put it on IIS and neither of that was acceptable for me.
i hope it will work for you...


text:
Q: Formatting problems when fetching feeds When I fetch data from a feed I store it in a table, the problem is that the format of the quote, so It will store ' instead of ' (I hope you can see the difference)
You get the same thing when you copy paste code from a website or word document in your editor.
the problem is that when I display the content on my site I get the following, how to I get rid of that?

A: The problem relates to character sets. You need to find out what the character set of the feed is (how it's encoded) and also how your site is encoded too.
If the feed will never contain HTML markup then you can use htmlentities() otherwise you'll need to do conversion of the feed at input so that it matches up with the same charset as your site.
MySQL has good internationalization support too and would be able to perform this conversion.
Without knowning the specifics of your site it's hard to advise further

A: Echo the text like this on your page:
echo  htmlentities($your_text_here);

A: James C already has the correct answer.
If your site is ISO-8859-1 encoded, and you are using the results of a UTF-8 encoded feed. In that case, a
utf8_decode($text);

would be a quick trick to make it work.
On the long run, it would be good to switch to UTF-8 altogether.
If you're outputting data from your database, you need to check the encoding of your

*

*database tables

*the mySQL connection

*your page encoding

For more sophisticated character set conversion, there is iconv().
Excellent basic reading on the issue is The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)


text:
Q: php loop inside accordion not displaying correctly In my database i have a table called publi inside this table i have two columns pub_year and pub_publi
Example of the table publi content :

        2016
        content_2016_1

        2016
        content_2016_2

        2016
        content_2016_3

        2015
        content_2015_1

        2015
        content_2015_2

and i want this output

  <button type="button" class="btn btn-info" data-toggle="collapse" data-target="#2016">2016</button>

    content_2016_1

    content_2016_2

    content_2016_3

  <button type="button" class="btn btn-info" data-toggle="collapse" data-target="#2015">2015</button>

    content_2015_1

    content_2015_2

and this is my code :
<?php
$query = "SELECT * FROM publi where pub_type=0 order by pub_year DESC, pub_publi ";
$result = mysqli_query($connection, $query);

$previous =0;
while ($val = mysqli_fetch_array($result))
{

    if ($previous <> $val['pub_year'])
    {
        $previous = $val['pub_year'];
        $year = $previous;

        echo '<button type="button" class="btn btn-info" data-toggle="collapse" data-target="#';
        echo $year;
        echo '">';
        echo $year;
        echo '</button>';
        echo '
';

        $Temp = highlight("person1",$val['pub_publi'],"0000FF");
        $Temp = highlight("person2",$Temp,"0000FF");
        $Temp = highlight("person3",$Temp,"0000FF");
        $Temp = highlight("person4",$Temp,"0000FF");
        $Temp = highlight("person5",$Temp,"0000FF");
        $Temp = highlight("person6",$Temp,"0000FF");
        $Temp = highlight("person7",$Temp,"0000FF");
        $Temp = highlight("person8",$Temp,"0000FF");
        $Temp = highlight("person9",$Temp,"0000FF");
        $Temp = highlight("person10",$Temp,"0000FF");

        echo '';
        echo $Temp;
        echo '
';
    }
}

?>

but the result that i get is:
<button type="button" class="btn btn-info" data-toggle="collapse" data-target="#2016">2016</button>

    content_2016_1

content_2016_2

content_2016_3

<button type="button" class="btn btn-info" data-toggle="collapse" data-target="#2015">2015</button>

content_2015_1

content_2015_2

A: The way you are grouping the data by pub_year is correct but from your example, you are only outputting information when group is changing.
I would propose something similar:
    <?php
        $previous = false;
        while ($val = mysqli_fetch_array($result)) {

            // when group is changing, end previous and start new
            if ($previous <> $val['pub_year']) {

                // end previous group html markup
                if ($previous !== false) {
                    echo '
';
                }

                $previous = $val['pub_year'];
                $year = $previous;

                echo '<button type="button" class="btn btn-info" data-toggle="collapse" data-target="#' . $year . '>' . $year . '</button>';
                echo '
';
            }

            // always output data inside group
            $Temp = highlight("person1",$val['pub_publi'],"0000FF");
            $Temp = highlight("person2",$Temp,"0000FF");
            $Temp = highlight("person3",$Temp,"0000FF");
            $Temp = highlight("person4",$Temp,"0000FF");
            $Temp = highlight("person5",$Temp,"0000FF");
            $Temp = highlight("person6",$Temp,"0000FF");
            $Temp = highlight("person7",$Temp,"0000FF");
            $Temp = highlight("person8",$Temp,"0000FF");
            $Temp = highlight("person9",$Temp,"0000FF");
            $Temp = highlight("person10",$Temp,"0000FF");

            echo $Temp . '
';
        }

        // end last group html markup
        if ($previous !== false) {
            echo '
';
        }
?>


text:
Q: Is it possible to call method after n minutes event if application will went to background Is it possible to call method after n minutes even if application will go to background?
What i should use for this?

A: You can fire a local notification after a set amount of time. But then you can only handle an event in case the user taps "View" on the dialog. Otherwise you can use one of the background modes (Location, Audio, VoIP) to continue running in the background. Then you have all the freedom you wish except that you probably won't get your app accepted in the app store unless you use your app for the purpose that you describe in your background mode.
I recently got an app rejected twice for polling every n minutes using location background mode (even though I was using the location!).
Good luck


text:
Q: Isn't (10<=10) and (10>=10) same in python? The greater than(>) and less than(<) is operating differently in python. Why is it happening so? Here are the two pieces of python code, the only difference between the two codes is in line number 2. The question says that if the sum of nicholas and john's marbles is greater than or equal to alex's marbles, we need to print yes, otherwise no. But both codes give different output when I input as nicholas = 10, alex = 20, john = 10. Why is it happening so?
1. nicholas,alex,john = map(int,input(Enter the number of
 marbles for nicholas, alex and john respectively.).split())
2. if((nicholas+john) >= alex):
3.  print("No")
4. else:
5.  print("Yes")

1. nicholas,alex,john = map(int,input("Enter the number of marbles for nicholas, alex and john respectively.).split())
2. if((nicholas+john) <= alex):
3.  print("Yes")
4. else:
5.  print("No")

I tried nicholas = 10, alex = 20, john = 10.
The first code gave me output as "No".
The second code gave me output as "Yes".
Both the things are completely same but also, why it's giving different output?

A: The opposite of >= is <, not <=.

A: You are giving input where they are equal.
10 is == to 10
so it is true that 10 <= 10 AND it is also true that 10 >= 10.
When Nicholas+John == Alex, both codes will evaluate to true written either way, <= or >=
Also > is the opposite of <= and vice versa.
Also  < is the opposite of >= and vice versa.
In your code, you have yes for the true statement in one branch and no for the true statement in the other. They are not opposites.


text:
Q: Story with joke telling time traveller I can't remember where I read this prose story, but in it there are super heroes. One of the super heroes can travel backward in time, but experiences all of the time that they travel through (so traveling 1 day back would cause him to experience 1 day of time in limbo.)
The hero ages faster because of all this time spent in limbo, but he also gets bored, and tells jokes to himself to pass the time.
He wasn't the main character in the story, but was a viewpoint character at times. I think I read this online.
Edit: I recall the main character was a different super hero who did not dress in a costume (and did not have a secret identity). He has a normal name (like Bob or Joe), and his super hero name was something like "Amazing Bob" or something like that. I believe he was considered powerful in the story world, and I recall a portion of the story where someone clones him a lot (4 times?) and makes the clones try to kill him. The story was named after the main character, and his super powers were pretty much similar to Super Man's powers (flight, speed, strength, laser vision, etc). Additionally, the story was named after the main character, and the main character had money problems and had to keep a day job because people never paid him for his super hero work.
The main character was just way less exciting than the time traveling masked hero who told jokes. I just also remembered that the time traveler also went back to visit himself at one time in the story and the version of him that had traveled back to see himself was nearly dead, and he had to figure out how to prevent himself from getting killed.
What story is it, and where can I find it again?


text:
Q: Include another page's ToC in Sphinx I have the following page at plugins/index.html:
Plugin Development
==================

.. toctree::
   :hidden:

   basics/index
   advanced/index

The Basics
----------

- :doc:`basics/gettingstarted`
- :doc:`basics/resources`
- :doc:`basics/i18n`

Advanced Topics
---------------

- :doc:`advanced/models`
- :doc:`advanced/controllers`
- :doc:`advanced/services`

plugin/basics/index.html and plugins/advanced/index.html contain their own toctree's, which link to the same subpages listed in plugins/index.html. So what I'm wondering is, is there a way to just include those sub toctree's, rather than manually listing the sub pages out like I'm doing?
I realize that I could just remove the :hidden: flag from the toctree, but the point is I want to keep Basic/Advanced topics in separate lists, with their own headings, intro paragraphs, etc.

A: You can list the entire directory contents like this (or various combinations of these directives):
.. toctree::
  :glob:
  :titlesonly:
  :maxdepth: 2

  **

or I think also like this (untested):
.. toctree::
  :glob:
  :titlesonly:
  :maxdepth: 2

  *
  basics/*
  advanced/*

However, I have found just manually listing things is often the best way to go. While the automatically generated TOCs are nice, they don't allow you much room in terms of formatting (for example, creating sub headings, and changing the order of pages etc).
In our documentation I have done pretty much the same thing you did in the initial question.


text:
Q: Pass each matched record value to filter in Elasticsearch For geo_distance query I'm using a constant value for distance. I need to make it dynamic. So I want to pass the above matched record radius value to distance.
Here's the code:
let searchRadius = '12KM'
        query: {
            bool: {
                must: {
                    match: {
                        companyName: {
                            query: req.text
                        }
                    }
                },
                filter: {
                    geo_distance: {
                        distance: searchRadius,//here I want to pass doc['radius']
                        location: {
                            lat: parseFloat(req.lat),
                            lon: parseFloat(req.lon)
                        }
                    }
                },
            }
        }

For each record, I have a different radius value. I want to pass doc['radius'] instead of constant searchRadius value.
I can hit two queries then iterate the values but it's not optimal. Can anyone suggest how can I pass each record value to geo_distance filter?

A: I have resolved from this answer.
Heres the code
query: {
              bool: {
                must: [
                  {
                    match: {
                      companyName: {
                        query: req.text
                      }
                    }
                  },
                  {
                    script: {
                      script: {
                        params: {
                          lat: parseFloat(req.lat),
                          lon: parseFloat(req.lon)
                        },
                        source: "doc['location'].arcDistance(params.lat, params.lon) / 1000 < doc['searchRadius'].value",
                        lang: "painless"
                      }
                    }
                  }
                ]
              }
            },

Using script Query, from more details:
https://www.elastic.co/guide/en/elasticsearch/reference/6.1/query-dsl-script-query.html


text:
Q: QGIS Server WFS query with BBOX filter of size 0 I'm trying to query QGIS WFS service for a specific feature for a specific point (lat/lng) value.
(The use case - I have a customer's coordinates for his address, and I want to take from the layer of neighbourhoods the name of the area he lives in).
I was succeeded to enter this query:
http://10.253.69.120/cgi-bin/qgis_mapserv.fcgi?SERVICE=WFS&REQUEST=GetFeature&MAP=/home/user/Documents/MyFirst.qgz&TYPENAME=JerusalemGIS_GPL0&PROPERTYNAME=CODE,SCHN_NAME&BBOX=215841.9,630761.9,217380.9,632096.2

And get back these results:
<wfs:FeatureCollection xsi:schemaLocation="http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.0.0/wfs.xsd http://www.qgis.org/gml http://10.253.69.120/cgi-bin/qgis_mapserv.fcgi?MAP=/home/user/Documents/MyFirst.qgz&SERVICE=WFS&VERSION=1.1.0&REQUEST=DescribeFeatureType&TYPENAME=JerusalemGIS_GPL0&OUTPUTFORMAT=text/xml; subtype%3Dgml/3.1.1">
<gml:boundedBy>
<gml:Envelope srsName="EPSG:2039">
<gml:lowerCorner>215841.9 630761.9</gml:lowerCorner>
<gml:upperCorner>217380.9 632096.2</gml:upperCorner>
</gml:Envelope>
</gml:boundedBy>
<gml:featureMember>
<qgs:JerusalemGIS_GPL0 gml:id="JerusalemGIS_GPL0.14">
<qgs:CODE>56</qgs:CODE>
<qgs:SCHN_NAME>בית הכרם</qgs:SCHN_NAME>
</qgs:JerusalemGIS_GPL0>
</gml:featureMember>
<gml:featureMember>
<qgs:JerusalemGIS_GPL0 gml:id="JerusalemGIS_GPL0.15">
<qgs:CODE>60</qgs:CODE>
<qgs:SCHN_NAME>בית וגן</qgs:SCHN_NAME>
</qgs:JerusalemGIS_GPL0>
</gml:featureMember>
<gml:featureMember>
<qgs:JerusalemGIS_GPL0 gml:id="JerusalemGIS_GPL0.41">
<qgs:CODE>240</qgs:CODE>
<qgs:SCHN_NAME>הר הרצל</qgs:SCHN_NAME>
</qgs:JerusalemGIS_GPL0>
</gml:featureMember>
<gml:featureMember>
<qgs:JerusalemGIS_GPL0 gml:id="JerusalemGIS_GPL0.42">
<qgs:CODE>248</qgs:CODE>
<qgs:SCHN_NAME>הר נוף</qgs:SCHN_NAME>
</qgs:JerusalemGIS_GPL0>
</gml:featureMember>
<gml:featureMember>
<qgs:JerusalemGIS_GPL0 gml:id="JerusalemGIS_GPL0.52">
<qgs:CODE>228</qgs:CODE>
<qgs:SCHN_NAME>יד ושם - הר הז</qgs:SCHN_NAME>
</qgs:JerusalemGIS_GPL0>
</gml:featureMember>
<gml:featureMember>
<qgs:JerusalemGIS_GPL0 gml:id="JerusalemGIS_GPL0.75">
<qgs:CODE>488</qgs:CODE>
<qgs:SCHN_NAME>עין כרם</qgs:SCHN_NAME>
</qgs:JerusalemGIS_GPL0>
</gml:featureMember>
<gml:featureMember>
<qgs:JerusalemGIS_GPL0 gml:id="JerusalemGIS_GPL0.86">
<qgs:CODE>568</qgs:CODE>
<qgs:SCHN_NAME>קריית היובל</qgs:SCHN_NAME>
</qgs:JerusalemGIS_GPL0>
</gml:featureMember>
</wfs:FeatureCollection>

Which are correct.
But when I tried to 'be clever' and just put the upper-right value for the BBOX to be equal to the lower-left value (What I assumed was that I'll have a BBOX in a size of one point) - I don't get the neighbourhood name of that point.
How can I work-around this and get a feature for a specific point?

A: You can use an Intersects filter:
FILTER=<Filter xmlns="http://www.opengis.net/ogc" xmlns:gml="http://www.opengis.net/gml"><Intersects><PropertyName>the_geom</PropertyName><gml:Point srsName="EPSG:4326"><gml:coordinates>-74.817265,40.5296504</gml:coordinates></gml:Point></Intersects></Filter>


text:
Q: Changing the packet data with pcapy/impacket I'm writing a small program in Python on Linux that will intercept packets flying over the wire on specific port from host A to host B. Host C will act as a man in the middle so all traffic will be going through host C (arp poisoning method). I've written successfuly the part with interception so I can see all the data on the screen but I want additionaly to modify the packets data without changing the header data (of course the cheksum will be changed). How can I achieve this using intercepted packets with pcapy/impacket?

It may be a little fuzzy, but the main idea is presented below.
1. Host A sends 'Hello' to host B (host A and B are arp spoofed so that traffic goes through host C).
2. Host C gets the 'Hello' from host A (by default host C redirects 'Hello' to host B, but I want something else - see point 3)
3. Host C modifies the 'Hello' to 'Bye' and redirects (kernel's ip_forward?) to host B.
4. Host B gets 'Bye'.

Maybe there is a way using some linux mechanisms to achieve this? Right now I'm stuck and I would appreciate any ideas.

A: I prefer scapy for this kind of application. It's a powerful python package that allows you to capture, manipulate and transmit packets at various layers of the protocol stack.
There are several ways to perform your man-in-the-middle attack. I'd probably use the "sniff" function with a filter that captures packets from Host A. I would then specify a callback (via the "prn" parameter) that modifies the packet and retransmits it to host B using "sendp". Note that scapy also includes a built-in "arpcachepoison" function.


text:
Q: Highcharts overriding X or Y axis key for series data objects In the examples in the highchart docs I see you can define your data like so:
[{ x: 100, y: 3}, { x: 105, y: 4} ...]

But I have non standard keys like this:
[{ myCustomXKey: 100, myCustomYKey: 3}, { myCustomXKey: 105, myCustomYKey: 4} ...]

Surely there must be a way to use my custom keys rather than the standard "x" and "y", right?  Can anyone help?

A: You can update the data series like this

var dataServer = [{
  myCustomXKey: 100,
  myCustomYKey: 3,
  myCustomZKey: 4
}, {
  myCustomXKey: 105,
  myCustomYKey: 4,
  myCustomZKey: 5
}, {
  myCustomXKey: 110,
  myCustomYKey: 5,
  myCustomZKey: 6
}, {
  myCustomXKey: 120,
  myCustomYKey: 6,
  myCustomZKey: 7
}]

function initialize(dataServer) {

  //suppose you need x,y,z data
  var dataH = [];//creating array for chart
  for (var i = 0; i < dataServer.length; i++) {
    /*pushing objects into array*/
    dataH.push({
      x: dataServer[i].myCustomXKey,
      y: dataServer[i].myCustomYKey,
      z: dataServer[i].myCustomZKey
    })
  }

  Highcharts.chart('container', {

    chart: {
      type: 'bubble',
      plotBorderWidth: 1,
      zoomType: 'xy'
    },
    title: {
      text: 'update chart data from server data'
    },

    series: [{
      data: dataH //add the variable here
    }]

  });
}
initialize(dataServer)


text:
Q: Add multiple ngControls with ngFor Is any proper way to generate *ngControls with *ngFor with template based approach? The problem is same as in ngControl with ngFor in Angular2, but don't want to obstruct controller logic with controls generation. In angular beta 17 was working
<form>
    <input *ngFor="let val of vals; let idx = index" [ngModel]="val" ngControl="input-{{idx}}">
</form>

but in 2.0.0 updating vals with this approach causes EXCEPTION: The null object does not have a method 'updateValue'.

A: try:
... ngControl="'input' + idx" ...

or
ngControl="input{{idx}}


text:
Q: Targeting compound selectors in gulp-uncss? I'm new to gulp and uncss, and am not sure whether my logic is flawed, or whether what I need is not possible.
I'd like uncss to ignore a slew of CSS rules that are prefixed with a certain string, but that have many compound selectors chained in their declaration.
I know we can use a regex in our ignore statement, and I'm using a regex to hopefully ignore all rules that begin with my prefix. But I'm not sure whether that regex in ignore covers just one class within a selector, or the entire rule.
e.g. I wish for gulp-uncss to ignore all CSS rules that are prefixed with .foo
.foo .bar {...}
.foo-baz {...}
.foo-ballz .bazzie:hover {...}

And my gulp-uncss rule (that doesn't seem to work as intended)
.pipe(uncss({
     html: ['index.html'],
     ignore: ['/^.foo/']
}))

Things compile ok, but I seem to be losing some (but not all) needed CSS. Anything I may have missed? Thanks!

A: I think I solved my own problem. In our ignore statements, I found you don't have to wrap the regular expression in quotes.
Therefore:
.pipe(uncss({
     html: ['index.html'],
     ignore: [/^\.foo/]
}))

Seems to be working out ok for me!

A: Alternatively, you could use an ignore comment just before your selector:
/* uncss:ignore */

But, I do prefer your answer. I was wrestling with the same issue and came across yours here.


text:
Q: Oracle round varchar2 column to 2 decimal places I have a varchar2 column that i need to get an average number from.
So take the following table where val is a column varchar2(20):
 val
 5
 4.654645
 3.4534353

I have tried the following:
select ROUND(AVG(TO_NUMBER(val)),2) as n from table

The result i am getting is 1.9110E+13
The result i want is a number rounded to 2 decimal places
Thanks in advance for any help

A: Perhaps . . .
select CAST(AVG(TO_NUMBER(val)) as decimal(20, 2)) as n
from table;

Why are you storing numbers as strings?  That seems like abad design decision.

A: So the following worked for me:
select ROUND(AVG(CAST((val) as decimal(20, 2))),2) as n from table

Thanks for suggestions


text:
Q: How do I add a custom field to a model in Laravel? I'm very new to Laravel and php frameworks in general, so sorry if I miss anything basic. I've created a new model called Journey in my application which extends the standard Eloquent model. What I've noticed is that I'm using my Journey model in two different Controllers and I'm duplicating a bit of code because of it.
Essentially, what I'm doing is I'm taking the title of a Journey and I'm formatting it with a custom class to clean the title (convert to lowercase, add hyphens, remove whitespace, etc) so I can append it to my page URLs.
In one controller, I'm calling:
$journey = Journey::find($id);
$journey->cleanURL = Url::clean($journey['name']); // This creates a new element/property with a clean string

And in the other, I'm calling:
$journeys = Journey::all();
foreach ($journeys as $journey) {
    $journey->cleanURL = URL::clean($journey['name']);
}

It would be inappropriate to add a fixed field to my database with the cleaned URL because I may change the title (which the cleaned URL is based on) at any time and I'd like the URL to update automatically in this event. However, saying this, I'm repeating myself by calling Url::clean twice.
What I'd like to do is write a method or alter an existing method, so that when I call Journey::all() or Journey::find() or any query-based method, the URL field is already present and filled. I've tried looking through some of the Vendor/Eloquent files, but they just make me confused.
How would I go about doing this?

A: You can use accessor for this.
Add to your Journey model the following function:
public function getCleanUrlAttribute($value)
{
    return Url::clean($this->name);
}

Now you will be able to use:
$journey = Journey::find($id);
echo $journey->clean_url;


text:
Q: Fisher information of a Binomial distribution The Fisher information is defined as $\mathbb{E}\Bigg( \frac{d \log f(p,x)}{dp} \Bigg)^2$, where $f(p,x)={{n}\choose{x}} p^x (1-p)^{n-x}$ for a Binomial distribution. The derivative of the log-likelihood function is $L'(p,x) = \frac{x}{p} - \frac{n-x}{1-p}$. Now, to get the Fisher infomation we need to square it and take the expectation.
First, we know, that $\mathbb{E}X^2$ for $X \sim Bin(n,p)$ is $ n^2p^2 +np(1-p)$. Let's first focus on on the content of the paratheses.
$$
\begin{align}
\Bigg( \frac{x}{p} - \frac{n-x}{1-p} \Bigg)^2&=\frac{x^2-2nxp+n^2p^2}{p^2(1-p)^2}
\end{align}
$$
No mistake so far (I hope!).
\begin{align}
\mathbb{E}\Bigg( \frac{x}{p} - \frac{n-x}{1-p} \Bigg)^2 &= \sum_{x=0}^n \Bigg( \frac{x}{p} - \frac{n-x}{1-p} \Bigg)^2 {{n}\choose{x}} p^x (1-p)^{n-x} \\
&=\sum_{x=0}^n \Bigg( \frac{x^2-2nxp+n^2p^2}{p^2(1-p)^2} \Bigg) {{n}\choose{x}} p^x (1-p)^{n-x} \\
&= \frac{n^2p^2+np(1-p)-2n^2p^2+n^2p^2}{p^2(1-p)^2}\\
&=\frac{n}{p(1-p)}
\end{align}
The result should be $\frac{1}{p(1-p)} $ but I've been staring at this for a few hours incapable of getting a different answer. Please let me know whether I'm making any arithmetic mistakes.

A: So, you have $X$ ~ Binomial($n$, $p$), with pmf $f(x)$:

You seek the Fisher Information on parameter $p$. Here is a quick check using mathStatica's FisherInformation function:

which is what you got :)

A: Fisher information: $I_n(p) = nI(p)$, and $I(p)=-\mathbb{E_p}\Bigg( \frac{\partial^2 \log f(p,x)}{\partial p^2} \Bigg)$, where $f(p,x)={{1}\choose{x}} p^x (1-p)^{1-x}$ for a Binomial distribution. We start with $n=1$ as single trial to calculate $I(p)$, then get $I_n(p)$.
$\log f(p,x) = x \log p + (1-x) \log p$
$\frac {\partial \log f(p,X)}{\partial p} = \frac {X}{p} - \frac {1- X}{1 - p}$
$\frac {\partial^2 \log f(p,X)}{\partial p^2} = -\frac {X}{p^2} - \frac {1- X}{(1 - p)^2}$
$I(P) = -\mathbb{E_p}\Bigg( \frac{\partial^2 \log f(p,x)}{\partial p^2} \Bigg) = -\mathbb{E_p}\Bigg(-\frac {X}{p^2} - \frac {1- X}{(1 - p)^2}\Bigg) = \frac {p}{p^2} + \frac {1-p}{(1-p)^2} = \frac {1}{p} + \frac {1}{(1-p)} = \frac {1}{p(1-p)} $
As a result, $I_n(p) = n I(p) = \frac {n}{p(1-p)} $

A: You are correct.
In this case it is easier to find FI as -E d^2 {log f(x|p)}/dp^2.

A: The result does not dependent on $n$ in the asymptotic information matrix.
\begin{align*}
\mathcal{I}\left(p\right)&=\underset{n\to\infty}{\mathrm{plim}}\dfrac{1}{n}\dfrac{n}{p\left(1-p\right)}\\&=\dfrac{1}{p\left(1-p\right)}
\end{align*}

A: I  know this is well beyond time for the OP, but I have incurred into an analogous issue today and I would like to point out the source of confusion.
The Fisher information for a single Bernoulli trial is $\frac{1}{p(1-p)}$. When you have $n$ trial, the asymptotic variance indeed becomes $\frac{p(1-p)}{n}$.
When you consider the Binomial resulting from the sum of the $n$ Bernoulli trials, you have the Fisher information that (as the OP shows) is $\frac{n}{p(1-p)}$. The point is that when you consider your variable as a Binomial you only have a sample of 1 -- since you observed only 1 binomial outcome. So that when you apply the classic result about the asymptotic distribution of the MLE, you have that the variance is simply the inverse of the Fisher information: $\frac{p(1-p)}{n}$ .
Therefore, the asymptotic variances coincide from both perspectives.


text:
Q: unity3d ios. App doesn't clear threads while running Some time ago I had a very strange situation.
I use Unity3d and C# to develop a client-server application for iOs. On an iPad mini retina, after building in Xcode, about 50% of the time (or little more) I have trouble with threads that don't clear after completing. In the profiler I see the number threads my app is using is about 83-85. After this my app doesn't respond at all (and we don't close it). If we close the connection to the server (by shutting down the server) the app starts working again.
In other cases all work good. Thread clear correctly.
To work with the server we use WWW:
StartCoroutine(MakeRequest(request, command, delaySeconds));

private IEnumerator MakeRequest(string request, Command command, float delaySeconds = 0f)
{
    if (delaySeconds > 0.00001f)
       yield return new WaitForSeconds(delaySeconds);

    WWW requester = new WWW(apiUrl, Recode(Encoding.UTF8.GetBytes(request), -1, outgoingKey));

    yield return requester;

    if (!string.IsNullOrEmpty(requester.error))
    {
       Debug.LogWarning(requester.error);
    }
    else
    {
       //something
    }

    requester.Dispose();
}

Do I have any options to fix this?
UPD:
Unity version 4.6.8f1. iOs version - 9.2


text:
Q: ASP.Net web service won't return JSON - Always XML I'm trying to create a simple AJAX & web service test (using C# .Net 2.0) to return data in JSON format, and I have (I believe) everything I need but I keep running into the same problem over and over again.  The response from the web service is always XML.  (It always has <?xml version="1.0" encoding="utf-8"?> as the 1st line).
I've tried the various options that come within the ScriptMethod tag, but nothing makes any difference.
The call works okay, but I get a "parsererror" with the response, which I would expect as it's not valid JSON.  I can call the web service method within the browser and get the return value I expect, just in XML format.  Fiddler also shows that the request and response are as I've found.
There are already several questions on here about the exact same issue, but none of them have given me a working answer.
Please ask questions if you need more information.
C#
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Script.Serialization;

namespace jQueryWebServiceTest
{
    /// <summary>
    /// This is a simple web service to test calling from javascript using AJAX, and getting a response.
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string SayHello()
        {
            //  I've tried both this...
            var response = new { value = "Hello" };
            JavaScriptSerializer json = new JavaScriptSerializer();
            return json.Serialize(response);

            //  and this...
            return "Hello";
        }
    }
}

Javascript
$(function () {

    var data = JSON.stringify({ Name: "John" });  // This is not used - part of other testing.
    data = "{}";

    $.ajax({
        type: "POST",
        data: data,
        url: "TestService.asmx/SayHello",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            console.log(data);
        },
        error: function (error, status) {
            console.log("status = " + status);
            console.log(error);
        }
    });

});

A: I managed to get it working by adding the following 2 blocks to the web.config...
In the configuration block inside system.web...
<assemblies>
    <add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</assemblies>

and anywhere else, inside system.web...
<httpHandlers>
    <remove verb="*" path="*.asmx"/>
    <add verb="*" path="*.asmx" type="System.Web.Script.Services.ScriptHandlerFactory" validate="false"/>
</httpHandlers>