text:
Q: Running ASP.NET Core application in full IIS without publishing gives 502.5 error I'm trying to host an ASP.NET Core application in IIS on my local machine, and I'm getting a 502.5 error. My question is different from "ASP.NET Core 1.0 on IIS error 502.5" because I'm not publishing my app, but (for testing purposes) trying to have IIS (not express) on my dev machine serve up the app.
To reproduce:

*

*Open VS2017

*Create a new ASP.NET Core Web Application (.NET Core)

*Choose the "Web API" template and target "ASP.NET Core 1.1" (no authentication)
Your Main looks like this now:
public static void Main(string[] args)
{
    var host = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .UseApplicationInsights()
        .Build();

    host.Run();
}

Your csproj looks like this:
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <Folder Include="wwwroot\" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />
    <PackageReference Include="Microsoft.AspNetCore" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.3" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.2" />
  </ItemGroup>
  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.1" />
  </ItemGroup>

</Project>

*Hit F5 to run and localhost:6565/api/values open up

*Add a "Web Configuration File" to the root of the project

*Uncomment the system.webServer section looking like this:
<system.webServer>
    <handlers>
      <remove name="aspNetCore"/>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
    </handlers>
    <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
</system.webServer>

*Open the IIS Manager GUI

*Choose "Add Website", pick a name and a port, set the path to the folder where the web.config is located

*As per Microsoft's instructions set the Application Pool's ".NET CLR version" to "No Managed Code"

*Browse to your new application, e.g. http://localhost:8089/api/values
Result: HTTP Error 502.5 - Process Failure
Expected: same result as in step 4.
I've tried to exclude all causes mentioned in the top answer to the other question:

*

*Set LocalSystem identity for the app pool

*Check on the console if dotnet --version runs (i.e. is available on the PATH)

In addition I've tried a few other things:

*

*Set processPath to variations of "%LAUNCHER_PATH%\bin\Debug\netcoreapp1.1\WebApplication1.dll

*Set processPath to point to dotnet.exe or its location

*Re-read the docs to distill a way to do this.

With ASP.NET MVC applications on the .NET Framework you could just spin up a new Website in full IIS that points to the MVC project's folder and it would "just work".
What do you need to do to get this to work with ASP.NET Core? Is it even possible to get this flow working without publishing?

A:
What do you need to do to get this to work with ASP.NET Core

Execute all required instructions, not only section you like. You should do publishing.

Is it even possible to get this flow working without publishing?

No.
During publishing your project is compiled and your web.config is modified to run compiled app (without SDK).

A: You can use the new feature of Visual Studio 15.3 and newer called Development time IIS support.
Please see the related issue and the blog post for the new feature.

A: I was able to get ASP.Net Core 2 to run behind IIS in development mode.

*

*Create a new dotnet app.  For example run 'dotnet new react -o my-new-app' from the tutorial.  Run npm install as directed.

*Install AspNetCoreModule.

*In IIS create a new site with no managed code and set the App Pool to run under LocalSystem.  It will need this to write to C:\WINDOWS\system32\config\systemprofile.  Set the physical path to the directory created from step 1.

*Put the following web.config in the directory from step 1.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <!--
    Configure your application settings in appsettings.json. Learn more at http://go.microsoft.com/fwlink/?LinkId=786380
  -->
  <system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
    </handlers>
    <aspNetCore processPath="C:\Program Files\dotnet\dotnet.exe"
                arguments="run --project C:\<your-path-to>\my-new-app"
                stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false">
        <environmentVariables>
          <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
        </environmentVariables>
    </aspNetCore>
  </system.webServer>
</configuration>

From there AspNetCoreModule orchestrates the interaction between IIS and dotnet.exe and the reverse proxy is set up.  As a bonus all the webpack compiling, bundling and hot reloading worked just as they did with 'dotnet run'.

A: As @Dmitry is saying, I'm not sure you can plug IIS on an 'unpublished' folder, but there is something more, as stated in https://learn.microsoft.com/en-us/aspnet/core/publishing/iis, you need a module to enable IIS to plug itself on an ASP.NET Core module which is called ".NET Core Windows Server Hosting", have you installed it?

A: I'm not sure if anything has changed since the previous answers as I've only just started using ASP.NET Core, but see @Sнаđошƒаӽ's answer here. It just worked for me on ASP.NET Core 3.1.
Note that changes in cshtml files won't be reflected without building or publishing. To get runtime compilation of Razor files so that changes appear after just a page refresh, use Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation as explained here.


text:
Q: Delphi 7 IDE - How to disable color for active line? I have changed my IDE color schema few times to and from and now noticed to have active line always coloured. I have searched in editor options > color > something like highlight line, like in XE but didnt find anything thah would mach. Can anyone help?!

A: As you have CNPack installed you need to go to CNPack..IDE Enhancement Settings..Source Highlight Settings and uncheck Enable Background Highlight Current Line (Delphi 7 Below Only)

redpajama_set_name: RedPajamaStackExchange


text:
Q: collapsing vertical menu while using css tables I have a 3 column layout that is made with css tables so each column can fill the browser perfectly. The first column is actually a menu and I need it to hide / move to the left on click and the middle column to fill in that space. It should actually not move completely out of screen but leave a little bit exposed so the user can click that area to have it animate back in.
Heres my fiddle...http://jsfiddle.net/VJmfq/
Right now I noticed the first column wont even move unless you either completely display:none the content inside or animate its content width to 0px(but as I want the column a little exposed I really dont want to be eliminating its content).
I tried animating the inner contents width down but when you animate width it comes in from both sides, so that trick wouldnt work, For example , The inner content should butt up against the right side of the first column but if you use float:right it messes up the content in the middle column, so the content in the first row is up against the side using margin-left...and if I animate the width down it doesnt animate from the left side, the width gets smaller from both sides at the same time.
$(document).ready(function() {
$(".two").click( function(event){
event.preventDefault();
if ($(this).hasClass("isDown") ) {
    //Show before animation!
    $(".one").stop().animate({width:"197px"}, 170);
    $(".one div").stop().animate({width:"137px"}, 310, function(){

    });
    $(this).removeClass("isDown");
} else {
    //Hide after animation!
    $(".one").stop().animate({width:"10px"}, 310);
    $(".one div").stop().animate({width:"5px"}, 310, function(){

    });
    $(this).addClass("isDown");
}
return false;
});
});

like I said I can get it moving without content inside by just reducing its width but the code I supplied is trying to do it with content inside so it doesnt even really work.
I would love to be able to just say first column marginLeft:-185px and pull the middle section over with it but that doesnt even move the column I think because of the css table layout

A: OK, I think it is all about the widths.  You need to remove the width from div.two, and then in your animate functions, make sure that you always end up with div.one being 50px (margin-left) wider than div.one div.  At least, it seems to work for me.  http://jsfiddle.net/VJmfq/1/


text:
Q: How to create single object with multiple keys and elements? I have one array with key and its array elements
When I am converting it from array to object then I am getting index 0 and 1 but here I need index should be array1 and array2

let input = [{
    "array1": [{
      "id": 1,
      "name": "Test 1"
    }, {
      "id": 2,
      "name": "Test 2"
    }]
  },
  {
    "array2": [{
        "id": 1,
        "name": "Test 1"
      },
      {
        "id": 2,
        "name": "Test 2"
      }
    ]
  }
];

function convert(arr) {
  let obj = new Object();

  arr.forEach((value, key) => {
    obj = value;
  });
  return obj;
}
console.log(convert(input))

so after calling this function i am getting following output
{
  "array2": [
     {
      "id": 1,
      "name": "Test 1"
     },
    {
      "id": 2,
      "name": "Test 2"
    }
  ]
}

but here I need output should be like this
{
  "array1": [
    {
      "id": 1,
      "name": "Test 1"
    },
    {
      "id": 2,
      "name": "Test 2"
    }
  ],
  "array2": [
    {
      "id": 1,
      "name": "Test 1"
    },
    {
      "id": 2,
      "name": "Test 2"
    }
  ]
}

If I use the define the array inside the convert function and push it then again i am getting  the index 0 and 1.
How can i get expected result here.

A: For getting a single object with the wanted keys, you could assign all items to a single object with Object.assign with spread syntax ....

let input = [{ array1: [{ id: 1, name: "Test 1" }, { id: 2, name: "Test 2" }] }, { array2: [{ id: 1, name: "Test 1" }, { id: 2, name: "Test 2" }] }],
    object = Object.assign(...input);

console.log(object)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Your code does not work because you take the latest assignment as a result
function convert(arr) {
    let obj = new Object();       // initialization

    arr.forEach((value, key) => {
        obj = value;              // assignment
    });
    return obj;                   // returns last assignment
}

A: Spreading (...) is the key:

let input = [{
    "array1": [{
      "id": 1,
      "name": "Test 1"
    }, {
      "id": 2,
      "name": "Test 2"
    }]
  },
  {
    "array2": [{
        "id": 1,
        "name": "Test 1"
      },
      {
        "id": 2,
        "name": "Test 2"
      }
    ]
  }
];

function convert(arr) {
  return arr.reduce((acc, curr) => ({ ...acc, ...curr }), {});
}
console.log(convert(input))
.as-console-wrapper { max-height: 100% !important; top: auto; }

You could also combine it with Object.assign on the array itself:

let input = [{
    "array1": [{
      "id": 1,
      "name": "Test 1"
    }, {
      "id": 2,
      "name": "Test 2"
    }]
  },
  {
    "array2": [{
        "id": 1,
        "name": "Test 1"
      },
      {
        "id": 2,
        "name": "Test 2"
      }
    ]
  }
];

function convert(arr) {
  return Object.assign(...arr);
}
console.log(convert(input))
.as-console-wrapper { max-height: 100% !important; top: auto; }

A: Using your code
function convert(arr) {
   let obj = new Object();
   arr.forEach((value, key) => {
     obj[key] = value;
   });
   return obj;
}

You were doing obj = value; on each iteration in the forEach which would mean you reassign obj to be the new value every time.

A: You just need to use your key parameter of foreach function in your object. I am attaching the code below you can look.

let input = [{
    "array1": [{
      "id": 1,
      "name": "Test 1"
    }, {
      "id": 2,
      "name": "Test 2"
    }]
  },
  {
    "array2": [{
        "id": 1,
        "name": "Test 1"
      },
      {
        "id": 2,
        "name": "Test 2"
      }
    ]
  }
];

function convert(arr) {
  let obj = new Object();

  arr.forEach((value, key) => {
    obj[key] = value;
  });
  return obj;
}
console.log(convert(input))


text:
Q: Missing some MFC headers I'm using Visual Studio 2012 Ultimate so the MFC library should be included, but I find that I'm missing some header files in the C:\Program Files\Microsoft Visual Studio 11.0\VC\atlmfc\include directory, specifically afxwin.h, afxtempl.h, and afxext.h.
Other than seeing if reinstalling will work, how can I acquire these files?

A: I just realized on a recent installation I forgot to include installation of the MFC files


text:
Q: How does this jenkins groovy script work? This is my groovy Script on Jenkins
def gitURL = "http://bitbucket.webapp.intern.de/scm/myproject.git"
def command = "git ls-remote -h $gitURL"

def proc = command.execute()  // line 3
proc.waitFor()

if ( proc.exitValue() != 0 ) {
   println "Error, ${proc.err.text}"
   System.exit(-1)
}

def branches = proc.in.text.readLines().collect {    // line 9
    it.replaceAll(/[a-z0-9]*\trefs\/heads\//, '')    // line 10
}

return branches

First I do not understand anything. How on line 3 can you call execute on command which is supposed to be a string ??
What type is variable branches in line 9 ???
Is branches a String ??
What is it.replaceAll in line 10 ??? I know replaceAll as method from String. But it has 2 parameters.
I do not see 2 parameters here.
Now I somehow understand branches contains all branches. What I want to do. I only want to have
branches which contain "-REST" it their names. How can I do this ??
My intention was using java. But it does not work.
List<String> branchesNew = new ArrayList<String>();

for(String branch : branchesNew)
{
     if(branch.contains("-REST"))
            branchesNew.add(branch);
}

A: line 3: this is a Groovy feature, see http://groovy-lang.org/groovy-dev-kit.html#process-management
line 9: it's a collection (a list, for instance) given as output of the collect method. see also http://groovy-lang.org/groovy-dev-kit.html#_working_with_collections
line 10: the second argument is ''. it replaces the regexp matches (branch prefixes) with an empty string.
You can filter all your wanted branches using the findAll method on collections. Following the given example:
def branchesNew = proc.in.text.readLines().findAll{ it.contains('-REST') }

Look at Filtering and searching for all related manipulation methods.


text:
Q: develop automated phone dialer in android I am trying to develop an Android application, the app should make a phonecall to an automated external phone service. Analize the response. Dial some extra numbers accordingly.
Now I looked around for how to make a phonecall and all I found is a way to invoke a phone activity. I don't want to show the phone ui or play the phone sound.
I also need to be able to let my app analize it.
I own the phone service and the app is going to be used through my phone. So it is all legal, don't worry.
How do I stream a phonecall to my app?


text:
Q: Случайное выполнение действия К примеру, у меня есть два действия :
echo '1'; // 25% что выполниться, а второе действие нет.

echo '2'; // 75% что выполниться, а первое действие нет.

Как сделать, чтобы действия выполнялись случайно (в каком-то проценте допустим)?
A: То тогда используйте код
 $number =  mt_rand(1,2);
if ($number==1){
echo '1';
}
if ($number==2){
echo '2';
}
__________

$number =  mt_rand(1,2); - это значит, что мы загоняем в переменную $number случайное число от 1 до 2 и с помощью условий проверяем какое в ней значение, если 1 то выводим 1, если 2 то тогда 2 и т.д. Если таких методов будет много то используй конструкцию switch и case
A: ну например:
$random = rand(1, 100);
if($random <= 75) {
    echo 'я буду вызываться чаще';
    //это действие будет выполнятся в 75% случаев
}
else {
    echo 'а я реже :(';
    //соответственно это в 25%
}

В вашем случае имхо самое рациональное решение
A: Если почитать внимательно курс теории вероятности, то вероятность приближается к своему значению при больших количествах повторений, т.е. вероятность 75% это не 3 из 4 и даже не 75 из 100, можно смело брать 7500000 из 10000000. Теперь почитав ВНИМАТЕЛЬНО описание функции rand() и немного оптимизировав код получаем:
echo (rand(0,10000000)>7500000)?2:1;

как-то так, причем чем больше число тем ближе вероятность распределения


text:
Q: Use of OS_creat in cFS It seems that I am not able to create files with OS_creat. I always receive this:
EVS Port1 66/1/TFTP_APP 134: DecodeRequestString(): /tmp/dest.txt, octet EVS Port1 66/1/TFTP_APP 139: TFTP error opening WRQ file /tmp/dest.txt Status = -108
I have tried using OS_creat from other apps but it seems that it does never work for me.
Do you know some typical issues about this that could be the problem?.

A: The OS_creat() call is actually implemented in the OSAL.  The value -108 that you see refers to an OSAL error code, which can be found in the file osapi-os-filesys.h as:
#define OS_FS_ERR_PATH_INVALID         (-108)

It is important to understand that OSAL does not directly use the underlying OS filesystem, but rather uses a system of "virtual mount points".
Every file-related operation such as opening or creating a file will get translated from a virtual file name (e.g. the name you supplied, /tmp/dest.txt) to an actual filename in the underlying system.  It is implemented this way because some RTOS's have different ways of specifying filenames, particularly if the reside on separate block devices and some RTOS's do not have the concept of a UNIX-like unified virtual file system.
This translation is implemented by the OS_TranslatePath() function which in turn references the system volume table, OS_VolumeTable, which is typically defined by the platform support package you are using.  If this translation fails, it returns OS_ERR_PATH_INVALID (-108).
The system volume table has several fields, such as:
{"/eedev0",  "./cf",      FS_BASED,        FALSE,     FALSE,    TRUE,     "CF",      "/cf",     512   },

The source file should have a more complete key as to what all the fields mean, but important to note that on POSIX deployments only FS_BASED modes are really supported, which is a map to the underlying filesystem.  For this mode the PhysDev (2nd parameter) actually refers to the existing path in the underlying filesystem (not a physical device).
To solve your issue, you need to do one of:

*

*Add a mapping for /tmp to your OS_VolumeTable in your PSP, to map it to the underlying file system.

*Use a path that already has a mapping, such as /cf in the example above.

Hope this helps!


text:
Q: How to ignore camera collision when colliding with the back face of a triangle? I was wondering if someone could enlighten me as to how I can ignore camera collision when a camera is colliding with the back face of a triangle. I want to implement this so that my camera cannot get stuck if I, or the player, somehow finds themselves within a model. Here is a video of my camera system:
A Video My Camera System
And here is the code for that collision detection:
private void CheckKeyboardInput(float deltaTime)
        {
            Vector3 previousCameraLocation = Camera.Location;
            KeyboardState state = Keyboard.GetCurrentState();
            Camera.IsAccelerating = state.IsPressed(Key.LeftShift);
            bool isCameraMoving = false;
            if (state.IsPressed(Key.W))
            {
                Camera.TranslateForward(deltaTime);
                isCameraMoving = true;
            }
            if (state.IsPressed(Key.S))
            {
                Camera.TranslateBackward(deltaTime);
                isCameraMoving = true;
            }
            if (state.IsPressed(Key.A))
            {
                Camera.TranslateLeft(deltaTime);
                isCameraMoving = true;
            }
            if (state.IsPressed(Key.D))
            {
                Camera.TranslateRight(deltaTime);
                isCameraMoving = true;
            }
            if (state.IsPressed(Key.E))
            {
                Camera.TranslateUp(deltaTime);
                isCameraMoving = true;
            }
            if (state.IsPressed(Key.Q))
            {
                Camera.TranslateDown(deltaTime);
                isCameraMoving = true;
            }
            /**
             * Process Camera Collisions
             */
            if (Camera.IsCollisionEnabled)
            {
                if (isCameraMoving)
                {
                    Vector3 currentCameraLocation = this.Camera.Location;
                    int totalCollisions = 0;
                    float finalCameraLocationX = Camera.Location.X;
                    float finalCameraLocationY = Camera.Location.Y;
                    float finalCameraLocationZ = Camera.Location.Z;
                    foreach (StaticGeometry geometry in this.StaticGeometry)
                    {
                        if (geometry.IsCameraCollidable)
                        {
                            if (Vector3.Distance(geometry.Location, Camera.Location) <= Camera.CollisionDistance)
                            {
                                for (int i = 0; i < geometry.Mesh.Vertices.Length; i += 3)
                                {
                                    // Get the Vertex Positions for the current Triangle
                                    Vector3 position1 = geometry.Mesh.Vertices[i].Location;
                                    Vector3 position2 = geometry.Mesh.Vertices[i + 1].Location;
                                    Vector3 position3 = geometry.Mesh.Vertices[i + 2].Location;

                                    // Create the rotation matrix using the geometry's current rotation setting.
                                    Matrix rotationMatrix = VoidwalkerMath.CreateRotationMatrix(geometry.Rotation);

                                    // Transform the Coordinate with the Rotation Matrix, then add the geometry's location
                                    Vector3 finalVertexLocation1 = Vector3.TransformCoordinate(position1, rotationMatrix) + geometry.Location;
                                    Vector3 finalVertexLocation2 = Vector3.TransformCoordinate(position2, rotationMatrix) + geometry.Location;
                                    Vector3 finalVertexLocation3 = Vector3.TransformCoordinate(position3, rotationMatrix) + geometry.Location;

                                    Vector3 translationX = new Vector3(currentCameraLocation.X, previousCameraLocation.Y, previousCameraLocation.Z);
                                    Vector3 translationY = new Vector3(previousCameraLocation.X, currentCameraLocation.Y, previousCameraLocation.Z);
                                    Vector3 translationZ = new Vector3(previousCameraLocation.X, previousCameraLocation.Y, currentCameraLocation.Z);
                                    // Test X
                                    BoundingSphere sphereX = new BoundingSphere(translationX, Camera.HardBoundsRadius);
                                    if (sphereX.Intersects(ref finalVertexLocation1, ref finalVertexLocation2, ref finalVertexLocation3))
                                    {
                                        finalCameraLocationX = previousCameraLocation.X;
                                        totalCollisions++;
                                    }
                                    // Test Y
                                    BoundingSphere sphereY = new BoundingSphere(translationY, Camera.HardBoundsRadius);
                                    if (sphereY.Intersects(ref finalVertexLocation1, ref finalVertexLocation2, ref finalVertexLocation3))
                                    {
                                        finalCameraLocationY = previousCameraLocation.Y;
                                        totalCollisions++;
                                    }
                                    // Test Z
                                    BoundingSphere sphereZ = new BoundingSphere(translationZ, Camera.HardBoundsRadius);
                                    if (sphereZ.Intersects(ref finalVertexLocation1, ref finalVertexLocation2, ref finalVertexLocation3))
                                    {
                                        finalCameraLocationZ = previousCameraLocation.Z;
                                        totalCollisions++;
                                    }

                                    /**
                                     * Edge case early termination. If the camera is already colliding
                                     * on all axis, we don't need to test for any further collisions. This seems
                                     * to only trigger when the player is wedged in a corner.
                                     */
                                    if (totalCollisions > 0) // Might not need this.
                                    {
                                        if (
                                            finalCameraLocationX == previousCameraLocation.X &&
                                            finalCameraLocationY == previousCameraLocation.Y &&
                                            finalCameraLocationZ == previousCameraLocation.Z)
                                        {
                                            this.Camera.Location = new Vector3(
                                                finalCameraLocationX,
                                                finalCameraLocationY,
                                                finalCameraLocationZ);
                                            return;
                                        }
                                    }

                                }
                            }
                        }
                    }
                    this.Camera.Location = new Vector3(finalCameraLocationX, finalCameraLocationY, finalCameraLocationZ);
                }
            }
        }

Also my Vertex class, just to show you guys how I have it set up:
using SharpDX;
using System.Runtime.InteropServices;

namespace VoidwalkerEngine.Framework.DirectX.Rendering
{
    [StructLayout(LayoutKind.Sequential)]
    public struct Vertex
    {

        public static Vertex Zero = new Vertex(Vector3.Zero,Vector2.Zero,Vector3.Zero);

        public Vector3 Location;
        public Vector2 TexCoords;
        public Vector3 Normal;

        public const int Size = 32;

        public Vertex(Vector3 position, Vector2 texCoords, Vector3 normal)
        {
            this.Location = position;
            this.Normal = normal;
            this.TexCoords = texCoords;
        }

        public Vertex(Vertex other)
        {
            this.Location = other.Location;
            this.Normal = other.Normal;
            this.TexCoords = other.TexCoords;
        }

        public override string ToString()
        {
            return
                "Location: " + Location.ToString() +
                ", TexCoords: " + TexCoords.ToString() +
                ", Normal: " + Normal.ToString();
        }

    }
}

Updated: Camera Class
using SharpDX;
using System;

namespace VoidwalkerEngine.Framework.DirectX
{
    public enum CameraMode
    {
        FreeLook,
        Orbit
    }

    public class Camera
    {
        /// <summary>
        /// The name of this camera
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// The eye location of this camera
        /// </summary>
        public Vector3 Location { get; set; }
        /// <summary>
        /// The Pitch of this Camera, as Radians
        /// </summary>
        public float Pitch { get; set; }
        /// <summary>
        /// The Yaw of this Camera, as Radians
        /// </summary>
        public float Yaw { get; set; }
        /// <summary>
        /// The Roll of this Camera, as Radians
        /// </summary>
        public float Roll { get; set; }
        /// <summary>
        /// The NearZ of this Camera
        /// </summary>
        public float NearZ { get; set; }
        /// <summary>
        /// The FarZ of this Camera
        /// </summary>
        public float FarZ { get; set; }
        /// <summary>
        /// The Field of View of this Camera, value should be
        /// between 0.70 and 1.20
        /// </summary>
        public float FieldOfView { get; set; }
        public float AspectRatio { get; set; }
        public float LookSpeed { get; set; }
        public float MoveSpeed { get; set; }
        /// <summary>
        /// Determines if this Camera is currently accelerating.
        /// </summary>
        public bool IsAccelerating { get; set; }
        /// <summary>
        /// The acceleration speed multiplier of this Camera.
        /// </summary>
        public float AccelerationMultiplier { get; set; }
        public CameraMode Mode { get; set; }
        public float ViewportWidth;
        public float ViewportHeight;
        public float HardBoundsRadius { get; set; } = 2.0f;
        public float CollisionDistance { get; set; } = 128;
        public bool IsCollisionEnabled { get; set; } = true;

        /// <summary>
        /// The BoundingSphere of this Camera
        /// </summary>
        public BoundingSphere HardBounds
        {
            get
            {
                return new BoundingSphere()
                {
                    Center = this.Location,
                    Radius = HardBoundsRadius
                };
            }
        }

        /// <summary>
        /// The Target Vector of this Camera
        /// </summary>
        public Vector3 Target
        {
            get
            {
                return new Vector3(
                    (float)Math.Sin(this.Yaw),
                    (float)Math.Tan(this.Pitch),
                    (float)Math.Cos(this.Yaw));
            }
        }

        /// <summary>
        /// The Frustum of this Camera
        /// </summary>
        public BoundingFrustum Frustum
        {
            get
            {
                return new BoundingFrustum(this.ModelViewProjectionMatrix);
            }
        }

        public Matrix ModelViewMatrix
        {
            get
            {
                return Matrix.LookAtLH(this.Location, Location + Target, Up);
            }
        }

        public Matrix ProjectionMatrix
        {
            get
            {
                return Matrix.PerspectiveFovRH(FieldOfView, AspectRatio, NearZ, FarZ);
            }
        }

        public Matrix ModelViewProjectionMatrix
        {
            get
            {
                return ModelViewMatrix * ProjectionMatrix;
            }
        }

        //public CardinalDirectionType Direction
        //{
        //    get
        //    {
        //        return VoidwalkerMath.GetCardinalDirection(VoidwalkerMath.ToDegrees(Yaw));
        //    }
        //}

        public Vector3 Forward
        {
            get
            {
                return new Vector3((float)Math.Cos(Pitch), 0, (float)Math.Sin(Pitch));
            }
        }

        public Vector3 Right
        {
            get
            {
                return new Vector3(Forward.Z, 0, -Forward.Z);
            }
        }

        public Vector3 Up
        {
            get
            {
                return new Vector3(-(float)Math.Sin(Roll), (float)Math.Cos(Roll), 0);
            }
        }

        public Camera()
        {

        }

        public Camera(string name)
            : this()
        {
            this.Name = name;
            this.Location = new Vector3();
        }

        public void ToOrigin()
        {
            Transform(Vector3.Zero, 0, 0, 0);
        }

        public void Transform(Vector3 location, float pitch, float yaw, float roll)
        {
            this.Location = location;
            this.Pitch = pitch;
            this.Yaw = yaw;
            this.Roll = roll;
        }

        public float GetCurrentMoveSpeed()
        {
            if (IsAccelerating)
            {
                return this.MoveSpeed * this.AccelerationMultiplier;
            }
            return this.MoveSpeed;
        }

        public void TranslateLeft(float deltaTime)
        {
            float moveSpeed = GetCurrentMoveSpeed();
            this.Location = new Vector3(
                Location.X - (float)Math.Sin(Yaw + MathUtil.PiOverTwo) * moveSpeed * deltaTime,
                Location.Y,
                Location.Z - (float)Math.Cos(Yaw + MathUtil.PiOverTwo) * moveSpeed * deltaTime);
        }

        public void TranslateRight(float deltaTime)
        {
            float moveSpeed = GetCurrentMoveSpeed();
            this.Location = new Vector3(
                Location.X + (float)Math.Sin(Yaw + MathUtil.PiOverTwo) * moveSpeed * deltaTime,
                Location.Y,
                Location.Z + (float)Math.Cos(Yaw + MathUtil.PiOverTwo) * moveSpeed * deltaTime);
        }

        public void TranslateForward(float deltaTime)
        {
            float degreesX = MathUtil.RadiansToDegrees(Pitch) * 0.01745329F; // X rotation
            float degreesY = MathUtil.RadiansToDegrees(Yaw) * 0.01745329F; // Y rotation
            float moveSpeed = GetCurrentMoveSpeed();
            this.Location = new Vector3(
                this.Location.X - (float)(moveSpeed * Math.Sin(degreesY) * Math.Cos(degreesX)) * deltaTime,
                this.Location.Y - (float)(moveSpeed * Math.Sin(degreesX)) * deltaTime,
                this.Location.Z - (float)(moveSpeed * Math.Cos(degreesY) * Math.Cos(degreesX)) * deltaTime);
        }

        public void TranslateBackward(float deltaTime)
        {

            float degreesX = MathUtil.RadiansToDegrees(Pitch) * 0.01745329F; // X rotation
            float degreesY = MathUtil.RadiansToDegrees(Yaw) * 0.01745329F; // Y rotation
            float moveSpeed = GetCurrentMoveSpeed();
            this.Location = new Vector3(
                this.Location.X + (float)(moveSpeed * Math.Sin(degreesY) * Math.Cos(degreesX)) * deltaTime,
                this.Location.Y + (float)(moveSpeed * Math.Sin(degreesX)) * deltaTime,
                this.Location.Z + (float)(moveSpeed * Math.Cos(degreesY) * Math.Cos(degreesX)) * deltaTime);
        }

        public void TransformYawPitch(float dx, float dy)
        {
            Yaw -= dx * LookSpeed;
            Pitch += dy * LookSpeed;
            const float pitchClamp = 1.56f;
            if (Pitch <= -pitchClamp)
            {
                Pitch = -pitchClamp;
            }
            if (Pitch >= pitchClamp)
            {
                Pitch = pitchClamp;
            }
        }

        public void TranslateUp(float deltaTime)
        {
            this.Location = new Vector3(
                this.Location.X,
                this.Location.Y + GetCurrentMoveSpeed() * deltaTime,
                this.Location.Z);
        }

        public void TranslateDown(float deltaTime)
        {
            this.Location = new Vector3(
                this.Location.X,
                this.Location.Y - GetCurrentMoveSpeed() * deltaTime,
                this.Location.Z);
        }

        public void LookAt(Vector3 location, float pitch, float yaw, float roll)
        {
            this.Location = location;
            this.Pitch = pitch;
            this.Yaw = yaw;
            this.Roll = roll;
        }

        public void SetAspectRatio(int width, int height)
        {
            this.ViewportWidth = width;
            this.ViewportHeight = height;
            this.AspectRatio = width / (float)height;
        }
    }
}

I'm already aware that I will need to compare the normal of the triangle, in some form or another. I just don't know how to go about this. If someone knows the answer, I would appreciate it. If any other code is needed, just let me know. Thanks!

A: You can calculate the velocity of the camera with currentCameraLocation - previousCameraLocation and with a simple dot product find out if you hit the back face of a triangle or not:
var cameraVelocity = currentCameraLocation - previousCameraLocation;
bool hitBackFace = Vector3.Dot(cameraVelocity, triangleNormal) > 0;

You might want to calculate the triangle normal with the cross product:
var triangleNormal = Vector3.Cross(finalVertexLocation2 - finalVertexLocation1,
                                   finalVertexLocation3 - finalVertexLocation1);

The reason for this is that the vertex normals are not necessarily the same as the triangle normal. If you think of a triangle on a phong shaded sphere, each of the 3 vertices of that triangle will have a different normal vector, and none of them will be the same as the triangle normal.


text:
Q: EntityFramework fail on update entity - cannot be tracked I'm having this known problem with my application.
I've tried a lot of changes with HasKey and HasAlternateKey, even HasIndex, Unique and other variations on the OnModelCreateCreating() method.
I even re-mapped my entity but still no success!

The instance of entity type 'Imoveis' cannot be tracked because
another instance with the key value '{Cod: 91}' is already being
tracked. When attaching existing entities, ensure that only one entity
instance with a given key value is attached.

My Update() method of my BaseRepository class:
    public T Update(T entity)
    {
        DbContext.Entry(entity).State = EntityState.Modified; <-- Exception happens here
        DbContext.SaveChanges();
        return entity;
    }

How the Update() is called. This problem it's happening on both calls. The second try is a fail way to prevent this error:
public Imoveis InsertOrUpdateUniqueName(Imoveis imoveis)
{
    try
    {
        if (imoveis.Cod > 0)
            Update(imoveis);
        else
            Insert(imoveis);
        return imoveis;
    }
    catch (Exception ex)
    {
        if (imoveis.Cod > 0)
        {
            if (ex is DbUpdateException)
            {
                if ((ex.InnerException as SqlException)?.Number == 2627)
                    return UpdateImovelDuplicado(imoveis);
            }
            else if (ex is InvalidOperationException)
            {
                var local = DbContext
                    .Set<Imoveis>()
                    .Local
                    .FirstOrDefault(x => x.Cod.Equals(imoveis.Cod));
                if (local != null)
                    DbContext.Entry(local).State = EntityState.Detached;
                return Update(imoveis);
            }
        }

        throw ex;
    }
}

A: Solved!
Solutions:
1 - In MY CASE (a console app), I removed async inserts or updates because I use a singleton DbContext. But this is NOT mandatory and depends on the case. You need to understand the life cycle of your DbContext.
2 - I changed my Update() method to recover and detach the original object from the DbContext Set collection.
This is my new Update() method calling a new DetachLocal() method for generic objects.
public T Update(T entity)
{
    DetachLocal(entity);
    DbContext.SaveChanges();
    return entity;
}

public void DetachLocal(T t)
{
    var keyname = GetIdName(t);
    var keyValue = GetIdValue(t);

    var local = DbContext.Set<T>()
        .Local
        .FirstOrDefault(entry => GetIdValue(entry).Equals(keyValue));
    DbContext.Entry(local).State = EntityState.Detached;
    DbContext.Entry(t).State = EntityState.Modified;
}

Thanks to @Crowcoder and @DavidBrowne-Microsoft for the replies that put me in the way to find this solution.


text:
Q: Evaluate the limit $\lim_{x\to a} (a-x) \tan \frac {\pi x}{2a}$
Evaluate:
  $$\lim_{x\to a} (a-x) \tan \dfrac {\pi x}{2a}.$$

My attempts:
$$=\lim_{x\to a} (a-x) \dfrac {\sin \left(\dfrac {\pi x}{2a}\right)}{\cos \left(\dfrac {\pi x}{2a}\right)}=1\cdot\lim_{x\to a} \dfrac {a-x}{\cos \left(\dfrac {\pi x}{2a}\right)}.$$

A: Note that, by letting $t=a-x$,
$$\lim_{x\to a} (a-x) \tan \dfrac {\pi x}{2a}=
\lim_{t\to 0} t \tan \dfrac {\pi a-\pi  t}{2a}=
\lim_{t\to 0} t \tan \left(\dfrac {\pi}{2} -\frac{\pi t}{2a}\right)=
\lim_{t\to 0} \frac{t}{\tan \left(\frac{\pi t}{2a}\right)}=\frac{2a}{\pi}$$
where in the last step we used the fact that $\tan(x)/x\to 1$ as $x\to 0$.

A: Let $a-x=y$.
Thus, $x=a-y$ and
$$\lim_{x\to a} (a-x) \tan \dfrac {\pi x}{2a}=\lim_{y\rightarrow0}y\cot\frac{\pi y}{2a}=\frac{2a}{\pi}\lim_{y\rightarrow0}\frac{\frac{\pi y}{2a}}{\sin\frac{\pi y}{2a}}=\frac{2a}{\pi}$$

A: $$\lim_{x\to a}(a-x)\tan\frac{\pi x}{2a} = \lim_{x\to a}(a-x)\frac{\sin\frac{\pi x}{2a}}{\cos \frac{\pi x}{2a}} = \lim_{x\to a}(a-x)\frac{\sin\frac{\pi x}{2a}}{\sin (-\frac{\pi x}{2a}+\frac{\pi}{2})} = \frac{2a}{\pi}\lim_{x\to a}\frac{\frac{\pi}{2a}(a-x)}{\sin(\frac{\pi}{2a}(a-x))} = \frac{2a}{\pi}.$$

A: Let $y = \frac{\pi x}{2a}$
\begin{align} \lim_{x \to a} \frac{a-x}{\cos \left( \frac{\pi x}{2a}\right)} &= \lim_{y \to \frac{\pi}{2}} \frac{\pi a-(2ay)}{\pi \cos(y)}\\
&=\frac{2a}{\pi} \lim_{y \to \frac{\pi}{2}} \frac{\frac{\pi}2-y}{\cos(y)}\\
&=\frac{2a}{\pi} \lim_{y \to \frac{\pi}{2}} \frac{\frac{\pi}2-y}{\cos\left(y-\frac{\pi}{2} + \frac{\pi}{2}\right)}\\
&= \frac{2a}{\pi} \lim_{y \to \frac{\pi}{2}} \frac{y-\frac{\pi}2}{\sin\left(y-\frac{\pi}{2} \right)}\\
&=\frac{2a}{\pi}\end{align}


text:
Q: Need a string with double quote immediately followed by single quote in python 2.6 I am trying to store a string in variable A which contains:
"'D:\\Work\\B1.tif';'D:\\Work\\B2.tif'"

I have two variables that store the locations of B1.tif and B2.tif:
X = "D:\\Work\\B1.tif"
Y = "D:\\Work\\B2.tif"

However, when I try to combine all the strings into a variable 'A':
A = '"' + "'" + X + "'" + ";" + "'" + Y + "'" + '"'

This is what it stores as:
'"\'D:\\Work\\B1.tif\';\'D:\\Work\\B2.tif\'"'

When I print A it displays:
"'D:\Work\B1.tif';'D:\Work\B2.tif'"

It seems that a backslash (\), that separates double quotes (") and single quotes ("), are automatically stored in the string. How do I store double quotes and single quotes in a string without the backslash separating the quotes?

A: String formatting (and raw strings) is much easier:
A = "\"'D:\\Work\\B1.tif';'D:\\Work\\B1.tif'\""
print A

X = r"D:\Work\B1.tif"
Y = r"D:\Work\B2.tif"

A = '"' + "'" + X + "'" + ";" + "'" + Y + "'" + '"'
print A

A = "\"'%s';'%s'\"" % (X, Y)
print A

Gives:
"'D:\Work\B1.tif';'D:\Work\B1.tif'"
"'D:\Work\B1.tif';'D:\Work\B2.tif'"
"'D:\Work\B1.tif';'D:\Work\B2.tif'"

However, to get the results you show, you have to use repr(), which is what IDLE uses if you just type the variable name in.  If I change all the print statements to print repr(A) I get:
'"\'D:\\Work\\B1.tif\';\'D:\\Work\\B1.tif\'"'
'"\'D:\\Work\\B1.tif\';\'D:\\Work\\B2.tif\'"'
'"\'D:\\Work\\B1.tif\';\'D:\\Work\\B2.tif\'"'

IDLE uses the class's __repr__() method, print uses __str__().  Often they are the same, but sometime, as here, they are not.

A: print '"\'%s\';\'%s\'"' %(X,Y)

A: When you display a variable in Python by just typing it's name, Python tries to print it in a way that if you were to copy and paste it as a variable, it would produce the same object. This works for strings, lists, dictionaries, sets, etc. The consequence is that strings need to be escaped when printed out this way. The backlashes are not actually stored in the string. You can see that by calculating the length:
>>> a = '"' + "'"
>>> a
'"\''
>>> len(a)
2
>>> print a
"'

There are, however, better ways to build the same string you want, as shown by the other answers.

A: Try using str.format() for these complicated formatting situations, you can even use triple quoted strings to make it easier.
A = ''' "'{}';'{}'" '''.format(X,Y)


text:
Q: How to send status information from a Web service while is being executed? I'm new to web development so I'm not sure what's the best option for the problem that I'm having.
Basically I have a web application that calls a web service for processing some data.
This process may take a long time (hours) and I would to know if there is an easy way to send some status information to the client from time to time.
Right now, the client makes the request from the browser and it just waits there until it finishes.
How can I send some information from the web service? I would like to send a percentage and some additional text specifying what is being done.
Thanks

A: Maybe you can poll another method for status?

A: WCF services can be marked as [OneWay] so that they don't return a response.
or, you could have the service kick off the process in an async manner and then just return to the client that the process has/or hasn't kicked off.
Then, the client can poll another method as the other user has suggested.
If you process takes hours you definitely can't use a sync service because you'll hit your execution timeout or rather the connection timeout for the client.

A: If I were you, I would make the original request asynchronous, as in instead of waiting for the response, it just "starts" the task and returns immediately.  Then I would have a separate method on your web service that the app can poll periodically to get the status of the job.  once it completes, it can display the data like the original request was doing.
if you want to do it synchronously, you can turn off Response.Buffer and write directly to the response.


text:
Q: Regular Expression for: 567,"this is a character, known as A" Help me to find Single regex for the strings:

*

*567,"this is a character, known as A."

*567,This is a character, known as A.

*567,"this is a character, known as (/r)
   A."

I have tried the following regex for this:
1.
^([0-9]+)[ ?]*,[ ?]*(?(?=")(("(?:[^"]|"")*"|[^,]*)(,("(?:[^"]|"")*"|[^,]*))*)|([a-z, a-z]*))$

2.
^([0-9]+),(["]{1}[a-z,a-z]*["]{1})$

Comments: regex 1 works fine but gives 6 groups as only 2 groups should be there.
Try following link to check
http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx
Select MultiLine to checked.

A: This regex should do!
^(\d+),("?[\p{L}\p{P}\s\r]*"?)$

\p{L}->would match all upper-lowercase letters
\p{P}->would match all punctuations..
\s->would match space
\r->would match carriage return

A: Try the following.  It assumes that the period is a consistent indication of the end of your pattern and that the begin and end quote are optional.
^(\d+),["]?([^.]*[.])["]?

The c# version of this would be...
            var data = @"567,""this is a character, known as A.""
567,This is a character, known as A.
567,""this is a character, known as
 A.""";
        var pattern = @"^(\d+),[""]?([^.]*[.])[""]?";

        foreach (Match mx in Regex.Matches(data, pattern, RegexOptions.Multiline))
        {
            Console.WriteLine("Group Count: {0}:  Group[1]: {1}, Group[2]: {2}",
                         mx.Groups.Count, mx.Groups[1].Value, mx.Groups[2].Value);
        }

(Note: you will actually get 3 groups because group 0 is always the entire match, but otherwise you get the two groups you would expect)
By the way, this pattern is intentionally general.  It also works for input data like...
678, This is a character, known as 1.

Which isn't in the original requirement.  But it's reasonable to assume you've given a very limited data example and that other characters types would be possible in the data to search.  It is a balancing act to write a pattern that is sufficiently specific to rule out false positives, while not missing ANY legitimate matches.


text:
Q: Unable to adjust the design when using javascript I am trying to just show that you can send your message and not hardcode all the messages in my frontend. I made use of an already developed code by a guy here's the link https://codepen.io/FilipRastovic/pen/pXgqKK
I have added the id="msg" in the input field and id="chatpanel" where class is chat-panel
Image attached. Now, the issue is that the message gets send (just in the display)b but the bubble is placed below the input area
Here's my additional JS code.

function send(){

var msg = document.getElementById("msg").value;
var div1=document.createElement("div");
div1.classList.add("row","no-gutters");

  var div2=document.createElement("div");

  div2.classList.add("col-md-3","offset-md-9");

  var div3=document.createElement("div");
  div3.classList.add("chat-bubble","chat-bubble--right");

var text=document.createTextNode(msg);

  div3.appendChild(text);
  div2.appendChild(div3);
  div1.appendChild(div2);

  var main=document.getElementById("chatpanel");

  main.appendChild(div1);

}

A: It's because the message input box is located in the #chatpanel div. When you append the new message to the #chatpannel div, it will get added after the last element in that div. You need to take the #msg input (and it's containing div) and move it out of the #chatpannel div.
Your code is roughly like this:

        <input type="text" id="msg" />
        <button type="button">Submit</button>

And you need to make it like this:

    <input type="text" id="msg" />
    <button type="button">Submit</button>


text:
Q: CSS hover make div invisible I am trying to create a team page for my site. The main concept is to have on top all the positions and bellow all the members. I want to make on hover on a certain position all the other positions invisible.
The css:
#team1:hover + #id-team-2 #id-team-3{display:none;}

The problem is that the css doesn't work with the way I did it.
The jsfiddle link:
jsfiddle

A: for doing this with pure CSS, you need to change your html code.
look at this code:
jsFiddle is here
HTML:

Team1

Team2

Team3

CSS:
#team1,#team2,#team3{
    float:left;
    width:90px;
    margin:0 5px;
    padding:5px;
    background:#eee;
    text-align:center;
}
#thumbnails{
    float:left;
    width:100%
}
#thumbnails div{
    background:tomato;
    margin:0 5px;
    width:100px;
    height:100px;
    float:left;
}
#team1:hover ~ #thumbnails > #thumbnail2,
#team1:hover ~ #thumbnails > #thumbnail3{
    visibility:hidden;
}
#team2:hover ~ #thumbnails > #thumbnail1,
#team2:hover ~ #thumbnails > #thumbnail3{
    visibility:hidden;
}
#team3:hover ~ #thumbnails > #thumbnail2,
#team3:hover ~ #thumbnails > #thumbnail1{
    visibility:hidden;
}


text:
Q: How to pass data from Activity to DialogFragment I know there are some examples on how to pass data from a activity to a dialog (i.e. Bundle or Intent). However, everything I've tried doesn't work. I keep getting NPE's and the "Unable to find explicit activity class" error. Even when I build a superbasic activity with a dialog it doesn't work. What do I have to put in the code to make it work?
MainActivity:
public class MainActivity extends AppCompatActivity {

  Button button;
  String textIWantToSee;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button) findViewById(R.id.button);

    textIWantToSee = "If this is the text I want to pass form this activity to the Fragment";

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });
  }
}

Dialog:
public class Dialog extends DialogFragment {

  TextView textView;

  @Override
  public android.app.Dialog onCreateDialog(Bundle savedInstanceState) {

    LayoutInflater inflater = getActivity().getLayoutInflater();
    View v = inflater.inflate(R.layout.dialog_layout, null);

    textView = (TextView) v.findViewById(R.id.textView);

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setView(v);

    return builder.create();
  }
}

Update
MainActivity:
public class MainActivity extends AppCompatActivity {

TextView tvIntent;
Button button;
String textIWantToSee;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tvIntent = (TextView) findViewById(R.id.tvIntent);
    button = (Button) findViewById(R.id.button);

    textIWantToSee = "If this is the text I want to pass form this activity to the Fragment";
    tvIntent.setText(textIWantToSee);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String intent = String.valueOf(tvIntent);
            Intent intentToDialog = new Intent(MainActivity.this, Dialog.class);
            intentToDialog.putExtra("keyForIntent", intent);
            startActivity(intentToDialog); //Here is the exception

        }
    });
}

}
Dialog:
public class Dialog extends DialogFragment {

TextView textView;
String intent;

@Override
public android.app.Dialog onCreateDialog(Bundle savedInstanceState) {

    LayoutInflater inflater = getActivity().getLayoutInflater();
    View v = inflater.inflate(R.layout.dialog_layout, null);

    textView = (TextView) v.findViewById(R.id.textView);
    Intent intentFromDialog = new Intent(getActivity().getApplicationContext(),MainActivity.class);
    intent = intentFromDialog.getStringExtra("keyForIntent");
    textView.setText(intent);

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setView(v);

    return builder.create();
}

}
E/AndroidRuntime: FATAL EXCEPTION: main
              Process: nl.blogvandetoekomst.passdatafromactivitytodialog, PID: 2947
              android.content.ActivityNotFoundException: Unable to find explicit activity class {nl.blogvandetoekomst.passdatafromactivitytodialog/nl.blogvandetoekomst.passdatafromactivitytodialog.Dialog}; have you declared this activity in your AndroidManifest.xml?
                  at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1794)
                  at android.app.Instrumentation.execStartActivity(Instrumentation.java:1512)
                  at android.app.Activity.startActivityForResult(Activity.java:3917)
                  at android.app.Activity.startActivityForResult(Activity.java:3877)
                  at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:842)
                  at android.app.Activity.startActivity(Activity.java:4200)
                  at android.app.Activity.startActivity(Activity.java:4168)
                  at nl.blogvandetoekomst.passdatafromactivitytodialog.MainActivity$1.onClick(MainActivity.java:36)
                  at android.view.View.performClick(View.java:5198)
                  at android.view.View$PerformClick.run(View.java:21147)
                  at android.os.Handler.handleCallback(Handler.java:739)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:148)
                  at android.app.ActivityThread.main(ActivityThread.java:5417)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="nl.blogvandetoekomst.passdatafromactivitytodialog">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

A: Your dialog fragment needs a hosting activity, It needs to be Inflated inside an Activity.
To inflate/show the DialogFragment in your MainActivity use:
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Bundle bundle = new Bundle(); //Bundle containing data you are passing to the dialog
        bundle.putString("text", textIWantToSee);

        Dialog dialog = new Dialog(); //Create a new Dialog
        dialog.setArguments(bundle);

        dialog.show(getSupportFragmentManager(), "MY_DIALOG_TAG"); //Inflate the dialog
    }
});

A: This is how you pass data to a DialogFragment from an Activity :
MainActivity.java
public class MainActivity extends AppCompatActivity {

Button button;
String textIWantToSee;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button) findViewById(R.id.button);

    textIWantToSee = "If this is the text I want to pass form this activity to the Fragment";

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Dialog dialogFragment = new Dialog();
            Bundle bundle = new Bundle();
            bundle.putString("TEXT",textIWantToSee);
            dialogFragment.setArguments(bundle);
            dialogFragment.show((MainActivity.this).getSupportFragmentManager(),"Image Dialog");

        }
    });
}
}

Dialog.java
public class Dialog extends DialogFragment {

TextView textView;

@Override
public android.app.Dialog onCreateDialog(Bundle savedInstanceState) {

    LayoutInflater inflater = getActivity().getLayoutInflater();
    View v = inflater.inflate(R.layout.dialog_layout, null);

    Bundle bundle = getArguments();
    String imageLink = bundle.getString("TEXT","");

    textView = (TextView) v.findViewById(R.id.textView);

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setView(v);

    return builder.create();
}
}

A: If you're using the support library you should use android.support.v4.app.DialogFragment instead of android.app.Dialog. Also, could you post the part of the code you're using to show the dialog?
Then you must be using the framework version of DialogFragment, as OBX has pointed:
MainActivity.java
public class MainActivity extends AppCompatActivity {

    Button button;
    String textIWantToSee;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button);

        textIWantToSee = "If this is the text I want to pass form this activity to the Fragment";

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Dialog dialogFragment = new Dialog();
                Bundle bundle = new Bundle();
                bundle.putString("TEXT",textIWantToSee);
                dialogFragment.setArguments(bundle);
                dialogFragment.show(getFragmentManager(),"Image Dialog");
            }
        });
    }
}

Dialog.java
public class Dialog extends DialogFragment {

    TextView textView;

    @Override
    public android.app.Dialog onCreateDialog(Bundle savedInstanceState) {

        LayoutInflater inflater = getActivity().getLayoutInflater();
        View v = inflater.inflate(R.layout.dialog_layout, null);

        Bundle bundle = getArguments();
        String imageLink = bundle.getString("TEXT","");

        textView = (TextView) v.findViewById(R.id.textView);

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(v);
        return builder.create();
    }
}

This way is working perfectly fine for me.
EDITED:
When you do this in onClick:
Intent intentToDialog = new Intent(MainActivity.this, Dialog.class);
intentToDialog.putExtra("keyForIntent", intent);
startActivity(intentToDialog); //Here is the exception

You're not starting an activity, Dialog.class is an extended DialogFragment, you can not show a dialog starting an Activity. Try the last code I've posted.

A: Use newInstance of Dialog fragment.
refer : https://developer.android.com/reference/android/app/DialogFragment.html
   static MyDialogFragment newInstance(int num) {
    MyDialogFragment f = new MyDialogFragment();

    // Supply num input as an argument.
    Bundle args = new Bundle();
    args.putInt("num", num);
    f.setArguments(args);

    return f;
}

If you are using kotlin, try defining the newInstance inside the companion object
companion object {
        fun newInstance(num: Int): MyDialogFragment{
            val f = DimensionDialogFragment()
            val args = Bundle()
            args.putInt("num", num)
            f.setArguments(args)

            return f
        }
    }

A: You can create the Dialog directly into your Activity:
button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        LayoutInflater inflater = MainActivity.this.getLayoutInflater();
        View v = inflater.inflate(R.layout.dialog_layout, null);

        TextView textView = (TextView) v.findViewById(R.id.textView);
        textView.setText(textIWantToSee);

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setView(v);
        builder.show();

        }
    });


text:
Q: dependencies error while installing teamviewer in centOS 6.4 64bit? Hello I am using centos 6.4 64bit. i am trying to install teamviewer. i've downloaded teamviewer rpm from teamviewer site. when i run
rpm -ivh teamviewer_10.0.37742.i686.rpm

it shows me failed dependencies error so i start to install dependencies by using yum but some dependencies unable to install which are
warning: teamviewer_10.0.37742.i686.rpm: Header V4 DSA/SHA1 Signature, key ID 72db573c: NOKEY
error: Failed dependencies:
        libfontconfig.so.1 is needed by teamviewer-10.0.37742-0.i686
        libjpeg.so.62 is needed by teamviewer-10.0.37742-0.i686
        libXinerama.so.1 is needed by teamviewer-10.0.37742-0.i686
        libXrandr.so.2 is needed by teamviewer-10.0.37742-0.i686
        libXrender.so.1 is needed by teamviewer-10.0.37742-0.i686

when i run yum install libfontconfig.so.1
i got this error
    warning: teamviewer_10.0.37742.i686.rpm: Header V4 DSA/SHA1 Signature, key ID 72db573c: NOKEY
    error: Failed dependencies:
            libfontconfig.so.1 is needed by teamviewer-10.0.37742-0.i686
            libjpeg.so.62 is needed by teamviewer-10.0.37742-0.i686
            libXinerama.so.1 is needed by teamviewer-10.0.37742-0.i686
            libXrandr.so.2 is needed by teamviewer-10.0.37742-0.i686
            libXrender.so.1 is needed by teamviewer-10.0.37742-0.i686

Loaded plugins: fastestmirror, protectbase, refresh-packagekit, security
    Loading mirror speeds from cached hostfile
     * base: centos.excellmedia.net
     * epel: ftp.cuhk.edu.hk
     * extras: centos.excellmedia.net
     * linuxtech-release: pkgrepo.linuxtech.net
     * updates: centos.excellmedia.net
     * webtatic: uk.repo.webtatic.com
    0 packages excluded due to repository protections
    Setting up Install Process
    Resolving Dependencies
    --> Running transaction check
    ---> Package fontconfig.i686 0:2.8.0-5.el6 will be installed
    --> Processing Dependency: libexpat.so.1 for package: fontconfig-2.8.0-5.el6.i686
    --> Running transaction check
    ---> Package expat.i686 0:2.0.1-11.el6_2 will be installed
    --> Finished Dependency Resolution
    Error:  Multilib version problems found. This often means that the root
           cause is something else and multilib version checking is just
           pointing out that there is a problem. Eg.:

             1. You have an upgrade for fontconfig which is missing some
                dependency that another package requires. Yum is trying to
                solve this by installing an older version of fontconfig of the
                different architecture. If you exclude the bad architecture
                yum will tell you what the root cause is (which package
                requires what). You can try redoing the upgrade with
                --exclude fontconfig.otherarch ... this should give you an error
                message showing the root cause of the problem.

             2. You have multiple architectures of fontconfig installed, but
                yum can only see an upgrade for one of those arcitectures.
                If you don't want/need both architectures anymore then you
                can remove the one with the missing update and everything
                will work.

             3. You have duplicate versions of fontconfig installed already.
                You can use "yum check" to get yum show these errors.

           ...you can also use --setopt=protected_multilib=false to remove
           this checking, however this is almost never the correct thing to
           do as something else is very likely to go wrong (often causing
           much more problems).

           Protected multilib versions: fontconfig-2.8.0-5.el6.i686 != fontconfig-2.8.0-3.el6.x86_64
     You could try using --skip-broken to work around the problem
     You could try running: rpm -Va --nofiles --nodigest

so what should i do i've tried many things but didn't success?

A: On
# uname -a
Linux centos6.6.6.71092 2.6.32-042stab108.1 #1 SMP Thu Apr 23 19:17:11 MSK 2015 x86_64 x86_64 x86_64 GNU/Linux

This works for me without errors:
# wget http://www.teamviewer.com/download/teamviewer_linux.rpm
# yum install teamviewer_linux.rpm

If you get missing public key error, you can download public key and
  import it using the following command continue

A: TeamViewer for Linux is compiled on x86 (i686) platform, so you must install x86-based dependency packages, which you can find at rpmfind.net.

A: TeamViewer for Linux (OpenSuse, CentOS etc..) is compiled on x86 platform, so you have to install x86-based dependency packages


text:
Q: How to hide the first letter of the span? Here in my HTML page data in span tags given below:-
1 this is a span one.
2 this is a span two.
3 this is a span three.

Output
1 this is a span one.
2 this is a span two.
3 this is a span three.

How I will hide the 1,2,3 values without *REMOVING them and alert them using JQuery when each span is clicked.
Output I want
this is a span one.
this is a span two.
this is a span three.

and alert them on click means if first is clicked then it alert 1 if second then two if third then 3. Thank you

A: Take a look to this:

$('span').each(function(){
    var firstLetter = $(this).text().substr(0,1);
    $(this).html(''+$(this).text().substr(0)+''+$(this).text().substr(1));
    $(this).on('click', function(){
        alert(firstLetter)
    })

})

1 this is a span one.
2 this is a span two.
3 this is a span three.

https://jsfiddle.net/0h1cjxu4/6/

A: To achieve this you can wrap the leading number in the HTML with another span which you can find when the outer span is clicked:

$('span').html(function(i, h) {
  return h.replace(/^(\d+)/, '$1');
}).click(function() {
  var number = $(this).find('.hidden').text();
  console.log(number);
});
.hidden { display: none; }

1 this is a span one.
2 this is a span two.
3 this is a span three.

Alternatively, if the numbers are always incremental then you can simply remove them and display the index of the clicked span:

$('span').html(function(i, h) {
  return h.replace(/^\d+/, '');
}).click(function() {
  var index = $(this).index() + 1;
  console.log(index);
});

  1 this is a span one.
  2 this is a span two.
  3 this is a span three.

A: Note that you don't need jQuery.
You can do the following using native JavaScript:

*

*use a .forEach() to loop through your span elements,

*use a new span element with a new class="hidden" to hide the first letter,

See snippet:

var spans = document.querySelectorAll('span');
spans.forEach(function(span, index) {
  var firstLetter = span.textContent.substr(0, 1);
  span.innerHTML = span.innerHTML.replace(firstLetter, '' + firstLetter + '');
  span.onclick = function() {
    console.log("You clicked span", firstLetter);
  }
});

console.log('Our "span one" HTML:\n', spans[0].innerHTML);
.hidden {
  display: none;
}
1 this is span one.
2 this is span two.
3 this is span three.

⋅
⋅
⋅
Then, you must want to use numbers > 9:

var spans = document.querySelectorAll('span');
spans.forEach(function(span, index) {
  span.innerHTML = span.innerHTML.replace(/^(\d+)/, '$1');
  span.onclick = function() {
    console.log("You clicked span", span.querySelector('.hidden').textContent);
  }
});
.hidden {
  display: none;
}
10 this is a span ten.
42 this is a span forty-two.
144 this is a span one-hundred-forty-four.

Hope it helps.

A: try this:

A: You can do this by below HTML and CSS. Need to change the span to div or p tag.

div.abc::first-letter {
  visibility: hidden;
}

ABCB1

ABCB2

ABCB3

A: Find all span nodes using
const spans = container.find('span');

then iterate each span and add new string value into result variable.

const container = $('#container');
const spans = container.find('span');
let result = '';

spans.each(function( index ) {
 const text = $(this).text();
 const displayText = text.substring(1);
   result += displayText + "\n";
});

console.log(result)

  1 this is a span one.
  2 this is a span two.
  3 this is a span three.


text:
Q: Year dummies versus Macro-specific factors My sample is balanced panel data and includes 6,071 firm-year observations for the period 2002-2014.
I test the book leverage (total debt/total asset) by using lagged factors as follows: 9 firm-specific factors, 2 industry-specific factors, 3 macro-specific factors (inflation, interest rate, and GDP growth), and 3 dummies. At the same time I use 12 year dummies for 13 year analysis.
Can I use only time dummies instead of macro-specific dummies or opposite?
I cannot find any empirical evidence about this usage.

A: Dummy variables are artificial variables created to represent attributes, usually with two or more distinct categories (in your case 13). At first, if your model is correctly specified the firm, industry, and macro factors will capture all the relevant variation. The macro effect will be controlled by the macro factors and your dummies will be not significant (redundant). But what if your macro factors are incomplete (wrong model specification), some dummies will show significance. Then, in your context is a matter of trusting in your model specification to consider or not the dummies. I will choose dummies for years where there is information that a macro effect is not being capture by the other variables.


text:
Q: read values from website continuously at particular time interval in android I am new to android. I had a search and found to post and get response from website. What i need is to read a response from website continuously at a particular time interval. For Example reading weather information and alert to the users. please help me out.

A: As a start you can take a look at WakefulIntentService. Then take a look at FluentHttpBuilder. And the rest is to glue them together :)


text:
Q: Deriving a formula for a function
Let $S$ := {$(x, y) ∈ \mathbb R^2: x^2 + y^2 = 1$} be the unit circle. Let $p = (−1, 0)$ ∈ $S$.
Define a map $F$ from $\mathbb R$ × {$0$} to $S$ as follows: Given $(t, 0)$, let $F((t, 0)) = (x, y)$ ∈ $S$ be the intersection of $S$ with the line through $p$ and $(t, 0)$.
Derive a formula for $F$.
Show that $t$ → $F((t, 0))$ is a bijective map from $\mathbb R$ to $S$ \ {$p$}, and also derive a formula for its
inverse.

How to derive a formula for $F$? If I get the line passing through $p$ and $(t,0)$, I get $(D): y = 0$ which is the x-axis
And I know that to show that $\phi$ : $\mathbb R$ →  $S$ \ {$p$}, I have to show that $\phi$ is injective and surjective

A: I think you got stuck because the problem as stated doesn't work. As pointed out in the comments by Daniel Fischer you probably want $p=(0,-1)$. In that case there is a line between $(t,0)$ and $(0,-1)$ that intersects the circle in exaclty one point and one can show that this gives a bijective map from the real line to $S\setminus \{p\}$.


text:
Q: how to move to the next enclosing brackets in VI Are there any shortcuts to move to the next enclosing brackets. For ex:
int func()
{

 if(true)
 {//this point

   for(int i=0;i<10;i++)
   {//need to jump from here to

    //blah blah blah

   }

 }
}

I can move to the beginning of a function using [[ but not sure how to move to the next enclosing brackets. Thanks for any info...

A: For the next enclosing brace do ]}, but in your example you are looking for the previous. In that case try [{.

A: Can't think of anything easier than /{
[{ will go to an unmatched one, but that isn't what you want.

A: Put the cursor on one bracket and hit the percent key.
Also setting the 'showmatch' option makes the cursor jump to the matching opening bracket when you type the closing bracket.
Adding a declaration like this:
set matchpairs+=<:>

Will add angle brackets to the standard list of match pair brackets.

A: You place your cursor on the opening or closing bracket of which you want to find the matching bracket and then use %. This will lead you to the matching braces.

A: There's always /{
That is, search for the next open brace.


text:
Q: Are the following model assumptions on a data stream too restrictive? Suppose that you were to model a "generic" continuous-time real-world data signal $X$ taking values in a bounded continuum $K\subset\mathbb{R}^d$ (e.g. the body temperature of a patient or its ECG data, in which case $K$ would be a bounded interval).
Question: Would you consider it restrictive or invalid to $-$ for technical reasons $-$ model $X$ as a a continuous stochastic process $X=(X_t)_{t\in I}$ such that

*

*for each $t\in I$, the random variable $X_t$ admits a continuous probability density $\chi_t\in C(\mathbb{R}^d)$ which is strictly positive everywhere on $\mathbb{R}^d$ (instead of $\chi_t$ being supported on $K$ only)?

You may have that $\chi_t$ is arbitrarily small outside of $K$ (that is,  $\sup_{x\in \mathbb{R}^d\setminus K}(\chi_t(x)) \leq \varepsilon$ for an arbitrarily small $\varepsilon > 0$), but still have to assume that

*

*$X_t$ has a continuous density $\chi_t$ on $\mathbb{R}^d$, and

*$\chi_t(x)>0$ (however small) for each $x\in\mathbb{R}^d$.

Any opinions/guesses/intuitions on this issue are welcome.


text:
Q: Why does cv2.imread output a matrix of zeros for a 32-bit image even when using cv.IMREAD_ANYDEPTH? I'm using OpenCV version 4.1.1 in Python and cannot get a legitimate reading for a 32-bit image, even when I use cv.IMREAD_ANYDEPTH. Without cv.IMREAD_ANYDEPTH, it returns as None type; with it, I get a matrix of zeros. The issue persists after reinstalling OpenCV. os.path.isfile returns True. The error was replicated on another computer. The images open in ImageJ, so I wouldn't think they're corrupted. I would rather use Skimage since it reads the images just fine, but I have to use OpenCV for what I'm working on. Any advice is appreciated.
img = cv2.imread(file,cv2.IMREAD_ANYDEPTH)

Link for the image: https://drive.google.com/file/d/1IiHbemsmn2gLW12RG3i9fLYZQW2u8sQw/view?usp=sharing

A: It appears to be some bug in how OpenCV loads such TIFF images. Pillow seems to load the image in a sensible way. Running
from PIL import Image
import numpy as np

img_pil = Image.open('example_image.tiff')
img_pil_cv = np.array(img_pil)
print(img_pil_cv.dtype)
print(img_pil_cv.max())

I get
int32
40950

as an output, which looks reasonable enough.
When I do
import cv2
img_cv = cv2.imread('example_image.tiff', cv2.IMREAD_ANYDEPTH)
print(img_cv.dtype)
print(img_cv.max())

I get
float32
5.73832e-41

which is obviously wrong.
Nevertheless, the byte array holding the pixel data is correct, it's just not being interpreted correctly. You can use numpy.ndarray.view to reinterpret the datatype of a numpy array, so that it's treated as an array if 32bit integers instead.
img_cv = cv2.imread('example_image.tiff', cv2.IMREAD_ANYDEPTH)
img_cv = img_cv.view(np.int32)
print(img_cv.dtype)
print(img_cv.max())

Which prints out
int32
40950

Since the maximum value is small enough for 16bit integer, let's convert the array and see what it looks like
img_cv_16bit = img_cv.astype(np.uint16)
cv2.imwrite('output_cv_16bit.png', img_cv_16bit)

OK, there are some bright spots, and a barely visible pattern. With a little adjustment, we can get something visible:
img_cv_8bit = np.clip(img_cv_16bit // 16, 0, 255).astype(np.uint8)
cv2.imwrite('output_cv_8bit.png', img_cv_8bit)

That looks quite reasonable now.


text:
Q: Using recursion to iterate over XML file I am having an issue with a recursive function I am trying to work on.  I have an XML file that essentially documents a file/folder structure.  These XML nodes (which represent a file/folder) can be N levels deeps.  So, I am trying to write a script that iterates over all the nodes and creates entries into a database.  For the folders, I have a table structure that has an ID, field_name, and parent_id columns.  The parent_id points to the ID of a folder the current folder resides in.  If it's at the root level, the ID is 0.
My problem is that I'm not able to accurately keep track of the parent_id, when I get down lover levels, then comes back up.  Here is an example of XML, but realize the folders can be any number of levels:
<XML>
    <programs>
        <program name ="xxx">
            <groups>
                <group id ="1" name ="yyy">
                    <folder name = "ggg">
                        <file name = "ddfdf"/>
                        <file name = "ddfdf"/>
                        <folder name = "sub" />
                    </folder>
                    <folder name = "sdfsdfs">
                        <file name = "ddfdf"/>
                        <folder name = "sub" >
                            <file name = "ddfdf"/>
                        </folder>
                    </folder>
                </group>
            </groups>
        </program>
    </programs>
</xml>

Script:
   foreach($program as $p){
       //creates root folder and returns ID
        $id = create_folder($folder);
        $rootId = $id;
        $groups = $program->groups;
        if($p->groups){
            foreach($p->groups as $group){
                foreach($group as $folder){
                        process_folder($folder,$id, $rootId);
                }
            }
        }
    }

function process_folder(($folder,$id, $rootId){
    foreach($folder as $key=>$value){
        switch ($key){
           case "folder":
                //creates folder, then returns the ID of the db record
                $parentId = create_folder($folder);
                process_folder($value, $parentId, $rootId);
                //reset ID but this doesnt seem to work
                $parentId = $rootId;
                break;
            case "file":
                break;
        }
    }
}

A: This is not a complete solution but it shows how a recursiveIterator might be used to accomplish what you want to do.
    $strxml='
    <xml>
        <programs>
            <program name ="xxx">
                <groups>
                    <group id ="1" name ="yyy">
                        <folder name = "ggg">
                            <file name = "ddfdf"/>
                            <file name = "ddfdf"/>
                            <folder name = "sub" />
                        </folder>
                        <folder name = "sdfsdfs">
                            <file name = "ddfdf"/>
                            <folder name = "sub" >
                                <file name = "ddfdf"/>
                            </folder>
                        </folder>
                    </group>
                </groups>
            </program>
        </programs>
    </xml>';

    class RecursiveDOMIterator implements RecursiveIterator {
        private $index;
        private $list;

        public function __construct(DOMNode $domNode){
            $this->index = 0;
            $this->list = $domNode->childNodes;
        }
        public function current(){
            return $this->list->item($this->index);
        }
        public function getChildren(){
            return new self( $this->current() );
        }
        public function hasChildren(){
            return $this->current()->hasChildNodes();
        }
        public function key(){
            return $this->index;
        }
        public function next(){
            $this->index++;
        }
        public function rewind(){
            $this->index = 0;
        }
        public function valid(){
            return $this->index < $this->list->length;
        }
    }

    $xml=new DOMDocument;
    $xml->loadXML( $strxml );
    $rootnode=$xml->getElementsByTagName('programs')->item(0);

    $nodeItr=new RecursiveDOMIterator( $rootnode );
    $itr=new RecursiveIteratorIterator( $nodeItr, RecursiveIteratorIterator::SELF_FIRST );
    foreach( $itr as $node ) {
        if( $node->nodeType === XML_ELEMENT_NODE ) {
            $id=$node->hasAttribute('id') ? $node->getAttribute('id') : false;
            $attr=$node->hasAttribute('name') ? $node->getAttribute('name') : false;
            echo $id.' '.$node->nodeName . ' ' . $node->nodeValue. ' ' . $attr .' '.$node->parentNode->tagName . ' ' . '<br />';
        }
    }
    $dom=$rootnode=$itr=$nodeItr=null;

A: Consider using XSLT to simplify your XML to a one child level format. Then run a simple PHP loop to extract parent id and folder data for database migration. In fact, if using MySQL you can import this exact transformed XML document into database with LoadXML(), should node names match column names.
As information, XSLT is a special-purpose, declarative programming language (same type as SQL) used to re-structure XML documents to various structures for end use needs. Like all general purpose languages including C#, Java, Python, Perl, VB, PHP maintains an XSLT processor. Below is an XSLT script (which you can add to for each nest in XML document) and PHP script (to transform and iterate through output).
XSLT Script (save as .xsl or .xslt)
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output version="1.0" encoding="UTF-8" indent="yes" />
<xsl:strip-space elements="*"/>

  <xsl:template match="/">
    <root>
      <xsl:apply-templates select="*"/>
    </root>
  </xsl:template>

  <xsl:template match="folder" name="foldertemplate">
    <row>
      <parent_id>0</parent_id>
      <field_name><xsl:value-of select="@name"/></field_name>
    </row>

    <!-- ADD LEVELS FOR EACH NEST IN XML DOCUMENT -->
    <row>
      <parent_id><xsl:value-of select="@name"/></parent_id>
      <field_name><xsl:value-of select="folder/@name"/></field_name>
    </row>

    <!-- EXAMPLE NEXT LEVEL -->
    <!-- <row> -->
    <!--   <parent_id><xsl:value-of select="folder/@name"/></parent_id> -->
    <!--   <field_name><xsl:value-of select="folder/folder/@name"/></field_name> -->
    <!-- </row> -->
  </xsl:template>

</xsl:transform>

TRANSFORMED XML OUTPUT (easier to parse and iterate over)
<?xml version="1.0" encoding="UTF-8"?>
<root>
  <row>
    <parent_id>0</parent_id>
    <field_name>ggg</field_name>
  </row>
  <row>
    <parent_id>ggg</parent_id>
    <field_name>sub</field_name>
  </row>
  <row>
    <parent_id>0</parent_id>
    <field_name>sdfsdfs</field_name>
  </row>
  <row>
    <parent_id>sdfsdfs</parent_id>
    <field_name>sub</field_name>
  </row>
</root>

PHP Script (to transform and loop through output)
// Set current directory
$cd = dirname(__FILE__);

// Load the XML source and XSLT file
$doc = new DOMDocument();
$doc->load($cd.'/Input.xml');

$xsl = new DOMDocument;
$xsl->load($cd.'/XSLTScript.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl);

// Transform XML source
$newXml = $proc->transformToXML($doc);

// Save output to file
$xmlfile = $cd.'/Output.xml';
file_put_contents($xmlfile, $newXml);

// Load new XML with SimpleXML
$newdoc = simplexml_load_file($cd.'/Output.xml');

$data = [];
$node = $newdoc->xpath('//row');
$parents = $newdoc->xpath('//row/parent_id');
$folders = $newdoc->xpath('//row/field_name');

// Loop through folder names and parent
for($i=0; $i < sizeof($node); $i++) {
    echo 'parent: '.$parents[$i]. ' folder: ' . $folders[$i]."\n";
}

#parent: 0 folder: ggg
#parent: ggg folder: sub
#parent: 0 folder: sdfsdfs
#parent: sdfsdfs folder: sub


text:
Q: Why doesn't my view fill the parent? I have two layouts, this is the parent layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/layoutTop"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="90"
        android:background="#FF0000"
        android:gravity="center"
        android:orientation="vertical" >
    </LinearLayout>

    <LinearLayout
        android:id="@+id/layoutBottom"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="10"
        android:gravity="center"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/txtTimer"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Time: 00:00:00"
            android:textColor="#FF0000"
            android:textSize="25dip" />
    </LinearLayout>

</LinearLayout>

And this is the child layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00FF00"
    android:orientation="vertical" >

        <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="fill_parent">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="fill_parent"
                android:gravity="center"
                android:text="Hello World" />

        </LinearLayout>
</LinearLayout>

However, when I put the child view in id/layoutTop, it doesn't fill the parent like it's supposed to. This is the result:

This is the code where the id/layoutTop's content is replaced: (This gets called via an event from the child be removed)
public void OnVictory(GamePanel sender, GamePanel next) {
    if(next != null){
        gamePanel.removeView(sender);
        gamePanel.addView(next);
        next.triggerOnDisplay();
    }else{
        Toast.makeText(getBaseContext(), "Victory!", Toast.LENGTH_LONG).show();
    }
}

sender is the old view there, next is the one to be put in place, and gamePanel is id/layoutTop
And this is how the inner layout is created:
private void initialize() {
   LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   layoutInflater.inflate(R.layout.appetizerfakeout,this);
}

Why is my inner view not filling the parent?


text:
Q: How to extract data from xlsx file in Oracle Apex (data parser) using worksheet name rather than worksheet code name? How can I extract or read data from xlsx file in Oracle apex data parser using the worksheet name instead of worksheet code:
In the sample code below, we can see that what is used is the file worksheet code name:
SELECT line_number,
   col001,
   col002,
   col003 FROM TABLE (apex_data_parser.parse (p_content           => (SELECT file_content
                                                            FROM loader_files
                                                           WHERE id = 1),
                                  p_file_name         => 'data.xlsx',
                                  **p_xlsx_sheet_name   => 'sheet1.xml',**
                                  p_skip_rows         => 0));

My requirement is to instead of using the code name "sheet1.xml" that I use the worksheet name "employees", the reason is that we need to extract data from multiple worksheets and the position of the worksheets might change, changing the worksheet code names and therefore breaking my code.
Is there anyway this can be done?

A: Use the function GET_XLSX_WORKSHEETS to convert a SHEET_DISPLAY_NAME into a SHEET_FILE_NAME:
select
    line_number, col001, col002, col003
from table
(
    apex_data_parser.parse
    (
        p_content           => (select file_content from loader_files where id = 1),
        p_file_name         => 'data.xlsx',
        p_skip_rows         => 0,
        p_xlsx_sheet_name   =>
        (
            select sheet_file_name
            from table
            (
                apex_data_parser.get_xlsx_worksheets
                (
                    p_content => (select file_content from loader_files where id = 1)
                )
            )
            where sheet_display_name = 'employees'
        )
    )
);


text:
Q: MS Exchange 2016: REST API - get calendar of another user i need to get calendar of another person in simillar way i am getting my via
https://exchange/api/v2.0/Users('username@domain.com')/calendarview?StartDateTime=XY&EndDateTime=XY
the request for another person doesn't work
https://exchange/api/v2.0/Users('anotherUser@domain.com')/calendarview?StartDateTime=XY&EndDateTime=XY
results>> REST APIs for this mailbox are currently in preview etc..
I found out there's way in rest api v1.0 but didn't find same possibility in v 2.0.
https://docs.microsoft.com/en-us/graph/api/user-list-calendarview?view=graph-rest-1.0&tabs=cs
Does exists way in api/v2.0 for this?
Thx


text:
Q: Error in Postman 500 Internal server error post method It's my first time using Next Js, Mongo DB and Postman. I am building an app and when sending the information I get a 500 error in postman.

In VSC all is ok and the console does not have any errors

Can you guide me with some ideas to fix it?
I hope that the information is sent correctly and that it gives me a 201 code. As in the screenshot of the tutorial
Link to tutorial:https://www.youtube.com/watch?v=Z-hACIsjv4E&t=3115s
I'am using mongoose to...
import mongoose from "mongoose";
const MONGO_URL = process.env.MONGO_URL;
console.log(process.env.MONGO_URL);

if (!MONGO_URL) {
  throw new Error(
    "Please define the MONGO_URL environment variable inside .env.local"
  );
}

let cached = global.mongoose;

if (!cached) {
  cached = global.mongoose = { conn: null, promise: null };
}

async function dbConnect() {
  if (cached.conn) {
    return cached.conn;
  }

  if (!cached.promise) {
    const opts = {
      bufferCommands: false,
    };

    cached.promise = mongoose.connect(MONGO_URL, opts).then((mongoose) => {
      return mongoose;
    });
  }
  cached.conn = await cached.promise;
  return cached.conn;
}

export default dbConnect;

import dbConnect from "../../../util/mongo";
import Product from "../../../models/Product";

export default async function handler(req, res) {
  const { method } = req;

  dbConnect();

  if (method === "GET") {
    try {
    } catch (err) {}
  }

  if (method === "POST") {
    try {
      const product = await Product.create(req.body);
      req.status(201).json(product);
    } catch (err) {
      res.status(500).json(err);
    }
  }
}

import mongoose from "mongoose";

const OrderSchema = new mongoose.Schema(
  {
    customer: {
      type: String,
      required: true,
      maxlength: 60,
    },
    address: {
      type: String,
      required: true,
      maxlength: 200,
    },
    total: {
      type: Number,
      required: true,
    },
    status: {
      type: Number,
      default: 0,
    },
    method: {
      type: Number,
      required: true,
    },
  },
  { timestamps: true }
);

export default mongoose.models.Order || mongoose.model("Order", OrderSchema);


text:
Q: C++ user input closes program debug I got a C++ program that waits for user input and only closes if the user inputs 'q', and will loop back to the menu if anything else is entered.
At least that's what it's supposed to do.  Instead of looping back, the program closes anyway.
int main()
{
    Hierarchy roster;
    char input=' ';
    bool done = false;
    string first, last, full, boss, title;
    while (done != true){
    cout << "Organizational Chart builder, version 0.1" << endl;
    cout << "Please choose your next command: /n";
    cout << "    q   to quit the program " << endl;
    cout << "    a   to add a person " << endl;
    cout << "    c   to count the number of people under someone" << endl;
    cout << "    p   to print the hierarchy " << endl;
    cout << "    r   to remove someone from the hierarchy " << endl;

    cin >> input;

    switch(input)
    {
    case 'q':
        done = true;
        break;
    case 'a':

        cout << "Please enter the person't first name:  ";
        cin >> first;
        cout << "Please enter the person's last name:  ";
        cin >> last;
        cout << "Please enter the person's title";
        cin >> title;
        cout << "Please enter " + first + last +"'s boss. Please enter the full name and title.  If there is none, type none:";
        cin >> boss;
        if (boss == "none")
        roster.insert(full);
        else
        roster.contains(boss);
        roster.insert(full);
        break;

    case'c':

        cout << "Enter the first name of the person you are searching for:   ";
        cin >> first;
        cout << "Enter the last name:  ";
        cin >> last;
        cout << "What is the person's title:";
        cin >> title;
        full = first + " " + last + " " + title;
        roster.contains(full);
        roster.countb(full);
        break;

    case 'p':
        roster.print();
        break;

    case 'r':

        cout << "Please enter the first, last, and title of the person you want removed:  ";
        cin >> full;
        roster.removeNode(full);
        break;

    }
  }
cout << "Program closed.  " << endl;
return 0;
    }

EDIT: Got it working now.  Thanks

A: Your return statement is in your while loop. Take it out and you should be okay.
ie. return 0;}} -> } return 0;}


text:
Q: How to add a standard normal pdf over a seaborn histogram I would like to add a standard normal pdf curve over a histogram built with seaborn.
import numpy as np
import seaborn as sns
x = np.random.standard_normal(1000)
sns.distplot(x, kde = False)

Any help would be appreciated!

A: *

*scipy.stats.norm gives easy access to the pdf of a normal distribution with
known parameters; by default it corresponds to the standard normal, mu=0, sigma=1.

*

*This answer works regardless of where the data mean is located (e.g. mu=0 or mu=10)

*Tested in python 3.8.11, matplotlib 3.4.2, seaborn 0.11.2

*This question and answer are for axes-level plots; for figure-level plots, see How to draw a normal curve on seaborn displot
Imports and Data
import numpy as np
import seaborn as sns
from scipy import stats
import matplotlib.pyplot as plt

# data
np.random.seed(365)
x = np.random.standard_normal(1000)

seaborn.histplot
ax = sns.histplot(x, kde=False, stat='density', label='samples')

# calculate the pdf
x0, x1 = ax.get_xlim()  # extract the endpoints for the x-axis
x_pdf = np.linspace(x0, x1, 100)
y_pdf = scipy.stats.norm.pdf(x_pdf)

ax.plot(x_pdf, y_pdf, 'r', lw=2, label='pdf')
ax.legend()

seaborn.distplot - deprecated

*

*For this to correspond correctly to your sampled data, the histogram should
display densities and not counts, so use norm_hist=True in the seaborn.distplot call.

ax = sns.distplot(x, kde = False, norm_hist=True, hist_kws={'ec': 'k'}, label='samples')

# calculate the pdf
x0, x1 = ax.get_xlim()  # extract the endpoints for the x-axis
x_pdf = np.linspace(x0, x1, 100)
y_pdf = scipy.stats.norm.pdf(x_pdf)

ax.plot(x_pdf, y_pdf, 'r', lw=2, label='pdf')
ax.legend()


text:
Q: Estimation of average treatment effect based on nearest neighbor matching I would like to use R to duplicate the treatment effect estimation method used in Stata.  Specifically, this is the Stata method I would like to duplicate.
I have tried the package MatchIt and Zelig in R, but the result was quite different from the result I had in Stata.
m.out1 = matchit(treatment ~ high_peak + hour, method="nearest", data=regres_LNG)
z.out1 = zelig(IPPLNG.gen ~ high_peak + hour,
               data=match.data(m.out1,"control"), model="ls")
x.out1 = setx(z.out1, data=match.data(m.out1, "treat", cond=TRUE))

s.out1 = sim(z.out1, x=x.out1)
summary(s.out1)

z.out2  = zelig(IPPLNG.gen~hour+high_peak,
                data=match.data(m.out1,"treat"), model="ls")
x.out2  = setx(z.out2, data=match.data(m.out1,"control"), cond=TRUE)
s.out2  = sim(z.out2, x=x.out2)
ate.all = c(s.out1$sim.out[[1]][1][[1]][[1]], -s.out2$sim.out[[1]][1][[1]][[1]])

(Also, I learned this method in the pdf)
Besides, I tried the linear regression model including treatment as a independent variable, but the coefficient and p-value was still different.
m.data   = match.data(m.out1)
lm_treat = lm(IPPLNG.gen~事件+hour+high_peak, data=m.data)
summary(lm_treat)

Hence, I would like to know how to duplicate the treatment effect estimation within nearest neighborhood matching in Stata to R and the difference between these two methods.

A: Despite good documentation for teffects nnmatch and the R package Matching, the answers are slightly different, but I'm not exactly sure why. However, here is how you can get close to a similar answer in R:
d <- haven::read_dta("http://www.stata-press.com/data/r13/cattaneo2.dta")
library(Matching)
m.out <- with(d, Match(Y = bweight,
                       Tr = mbsmoke,
                       X = data.frame(fage, mage, mmarried, prenatal1),
                       Z = data.frame(fage, mage),
                       estimand = "ATE",
                       BiasAdjust = TRUE,
                       exact = c(fage = FALSE, mage = FALSE,
                                 mmarried = TRUE, prenatal1 = TRUE)))
summary(m.out)

The MatchIt package cannot do this kind of analysis. The philosophy behind it is different from that underlying teffects nnmatch. The Matching package comes quite close in that it has many of the same options as teffects nnmatch and was built on a similar philosophy (and even uses fairly similar syntax elements). Using this code, I get an ATE of -250.18 (27.807), whereas teffects nnmatch in the video gave an ATE of -244.32 (27.269), which lead to the same substantive conclusion.