问:
Can I make an onclick function not execute if the click opens a link in a new tab?
I have a large  that show a random piece of text from a .json - file whenever it is clicked. Now sometimes the text involves links, which are set to open in a new tab. Works perfectly fine!

However, I'd like to not have the onclick function execute, when a new tab is opened. The same as if the user opens the link by right-clicking and opening in a new tab.

Is that possible using plain javascript? I include the selectPodcast - function to show how the link is generated.

As I'm at it: I haven't been programming for long and I'd love to know what my code looks like to an experienced programmer. I'd imagine it's kinda cute, like when a child starts forming sentences :-)

I tried to add a.onclick = "return false;"; to the selectPodcast - function, but that didn't work.

```<code>function getPodcast() {
    var url = "json/podcasts.json";
    var request = new XMLHttpRequest();
    request.open("GET", url);
    request.onload = function() {
        if (request.status == 200) {
            selectPodcast(request.responseText);
        }
    };
    request.send(null);
};

function selectPodcast(responseText) {
    var items = JSON.parse(responseText);
    var choice = [Math.floor(Math.random() * items.length)];
    var title = items[choice].title;
    var link = items[choice].link;
    var description = items[choice].description;
    var a = document.createElement("a");
    var br = document.createElement("br");
    var p = document.createElement("p");
    a.href = link;
    a.target = "_blank";
    a.innerHTML = title;
    p.innerHTML = description;
    var div = document.getElementById("podcast");
    div.innerHTML = "";
    div.appendChild(a);
    div.appendChild(br);
    div.appendChild(p);
};
</code>```

答:
If this is what you want, you can check if target is  tag (link)by passing e as callback function parameter which contains click event information like position, target, offset position, etc.

instanceof keyword checks if object is instance of HTMLAnchorElement.

function onclick(e){
  if(e.target instanceof HTMLAnchorElement) return console.log('Link');

  //body
  console.log('Not a link');
}

test.onclick = onclick;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='test'>Some text Some link</div></code>```

Body:
I have a large  that show a random piece of text from a .json - file whenever it is clicked. Now sometimes the text involves links, which are set to open in a new tab. Works perfectly fine!

However, I'd like to not have the onclick function execute, when a new tab is opened. The same as if the user opens the link by right-clicking and opening in a new tab.

Is that possible using plain javascript? I include the selectPodcast - function to show how the link is generated.

As I'm at it: I haven't been programming for long and I'd love to know what my code looks like to an experienced programmer. I'd imagine it's kinda cute, like when a child starts forming sentences :-)

I tried to add a.onclick = "return false;"; to the selectPodcast - function, but that didn't work.

function getPodcast() {
    var url = "json/podcasts.json";
    var request = new XMLHttpRequest();
    request.open("GET", url);
    request.onload = function() {
        if (request.status == 200) {
            selectPodcast(request.responseText);
        }
    };
    request.send(null);
};

function selectPodcast(responseText) {
    var items = JSON.parse(responseText);
    var choice = [Math.floor(Math.random() * items.length)];
    var title = items[choice].title;
    var link = items[choice].link;
    var description = items[choice].description;
    var a = document.createElement("a");
    var br = document.createElement("br");
    var p = document.createElement("p");
    a.href = link;
    a.target = "_blank";
    a.innerHTML = title;
    p.innerHTML = description;
    var div = document.getElementById("podcast");
    div.innerHTML = "";
    div.appendChild(a);
    div.appendChild(br);
    div.appendChild(p);
};

Body:
If this is what you want, you can check if target is <a></a> tag (link)by passing e as callback function parameter which contains click event information like position, target, offset position, etc.

instanceof keyword checks if object is instance of HTMLAnchorElement.

function onclick(e){
  if(e.target instanceof HTMLAnchorElement) return console.log('Link');

  //body
  console.log('Not a link');
}

test.onclick = onclick;

<div id='test'>Some text <a href='#some_link'>Some link</a></div>


来源: stackexchange

问:
Is there a function in Python3 to copy the 3 smallest values in a row into a data frame, for m rows?
I'm trying to find the three smallest values for each row of a dataframe, and put them in a separate dataframe. I don't need to know which column they came from, but I do need to cycle through m rows where m might change for each dataframe I use.

I wanted to use heaps.nsmallest, but I'm not sure how to loop through each row and add the results to a new line of a dataframe each time. I seem to just get a single line of results as output.

```<code> for x in range(len(df1)):
        heap=pd.DataFrame(heapq.nsmallest(3, df1[x]))
</code>```

I expected this to loop through values of x, but it only produces one column with len(df1) rows. I think it's overwriting the previous results, as it always gives the three minimum values from the last row.

答:
```<code>df2 = pd.DataFrame([heapq.nsmallest(3, df1[x])
                   for x in range(len(df1))])
</code>```

or, use sorted(df1[x])[:3]

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to find the three smallest values for each row of a dataframe, and put them in a separate dataframe. I don't need to know which column they came from, but I do need to cycle through m rows where m might change for each dataframe I use.

I wanted to use heaps.nsmallest, but I'm not sure how to loop through each row and add the results to a new line of a dataframe each time. I seem to just get a single line of results as output.

 for x in range(len(df1)):
        heap=pd.DataFrame(heapq.nsmallest(3, df1[x]))

I expected this to loop through values of x, but it only produces one column with len(df1) rows. I think it's overwriting the previous results, as it always gives the three minimum values from the last row.

Body:
df2 = pd.DataFrame([heapq.nsmallest(3, df1[x])
                   for x in range(len(df1))])

or, use sorted(df1[x])[:3]


问:
Unity - Why is my Material on a GameObject black?

Unity

I added a .PNG-File in my Textures-Folder and then make a material out of it in my Materials-Folder and then I add this material to a GameObject in the current Scene, but the Material on the GameObject don't look like the preview. It's only black.Look here

I'm frustrated, can anyone help me?

Lightning SettingsLightning Settings

答:
Your scene probably have no light on it.
Maybe you should add a light source or re-activate the ambient light by going in: Window -> Rendering -> Lightning Settings and update the Environment -> Intensity Multiplier value to 1 or something else you like.

Hope it helps!

OwnerDisplayName: Snowappix


问:
bootstrap - apply class based on screen size
Can I do this without using @media only screen ? Or is this the best way?

For example can I write this in CSS?:

```<code>@include media-breakpoint-up(md) {
  .card {
    transform: translate(0px, -75px);
    z-index: 200;
  }
}
</code>```

I also want to hide/show a div based on screen size.

答:
What you could do is create multiple css style sheets based on your media screen sizes. then inside one of your css style sheets for that particular screen size you can hide your div.

Example link in your html:

```<code><link rel = "stylesheet" media="screen and (min-width: 480px) and (max-width: 1920px)" href= "styles/desktop.css"/>
</code>```

then inside desktop.css you can have:

```<code>.card { display = none; }
</code>```

This will hide your div when the screen size is between 480px and 1920px.

Body:
Can I do this without using @media only screen ? Or is this the best way?

For example can I write this in CSS?:

@include media-breakpoint-up(md) {
  .card {
    transform: translate(0px, -75px);
    z-index: 200;
  }
}

I also want to hide/show a div based on screen size.

Body:
What you could do is create multiple css style sheets based on your media screen sizes. then inside one of your css style sheets for that particular screen size you can hide your div.

Example link in your html:

<link rel = "stylesheet" media="screen and (min-width: 480px) and (max-width: 1920px)" href= "styles/desktop.css"/>

then inside desktop.css you can have:

.card { display = none; }

This will hide your div when the screen size is between 480px and 1920px.


问:
Sending an Email via Python
I'm attempting to send an email with Python. From what I can tell, all the following code needs is a valid recipient and a host HOST. I'm unsure on how to get the host. What is the simplest way?

```<code>import smtplib
import string

SUBJECT = "Test email from Python"
TO = "python@mydomain.com"
FROM = "python@mydomain.com"
text = "blah blah blah"
BODY = string.join((
        "From: %s" % FROM,
        "To: %s" % TO,
        "Subject: %s" % SUBJECT ,
        "",
        text
        ), "\r\n")
server = smtplib.SMTP(HOST)
server.sendmail(FROM, [TO], BODY)
server.quit()
</code>```

答: The HOST is the SMTP relay provided by your ISP (typically related to the domain name of your from address).  If you use a desktop mail client, you'll be able to see the SMTP server listed in your mail settings.  If you're hosting using shared hosting, your hosting provider should be able to provide an SMTP server for you to use.</p>

ContentLicense: CC BY-SA 3.0

Title: Sending an Email via Python

Body:
I'm attempting to send an email with Python. From what I can tell, all the following code needs is a valid recipient and a host HOST. I'm unsure on how to get the host. What is the simplest way?

import smtplib
import string

SUBJECT = "Test email from Python"
TO = "python@mydomain.com"
FROM = "python@mydomain.com"
text = "blah blah blah"
BODY = string.join((
        "From: %s" % FROM,
        "To: %s" % TO,
        "Subject: %s" % SUBJECT ,
        "",
        text
        ), "\r\n")
server = smtplib.SMTP(HOST)
server.sendmail(FROM, [TO], BODY)
server.quit()


问:
ShaderLab offset not rendering one polygon above the other
I have two shaders, UnlitRGBA and TransparentNoOverlap. They are as follows:

UnlitRGBA.shaderlab

```<code>// Unity built-in shader source. Copyright (c) 2016 Unity Technologies. MIT license (see license.txt)
// modified by rbjacob101

Shader "Particles/Standard Unlit (RGBA)"
{
    Properties
    {
        _MainTex("Albedo", 2D) = "white" {}
    _Color("Color", Color) = (1,1,1,1)

        _Cutoff("Alpha Cutoff", Range(0.0, 1.0)) = 0.5

        _BumpScale("Scale", Float) = 1.0
        _BumpMap("Normal Map", 2D) = "bump" {}

    _EmissionColor("Color", Color) = (0,0,0)
        _EmissionMap("Emission", 2D) = "white" {}

    _DistortionStrength("Strength", Float) = 1.0
        _DistortionBlend("Blend", Range(0.0, 1.0)) = 0.5

        _SoftParticlesNearFadeDistance("Soft Particles Near Fade", Float) = 0.0
        _SoftParticlesFarFadeDistance("Soft Particles Far Fade", Float) = 1.0
        _CameraNearFadeDistance("Camera Near Fade", Float) = 1.0
        _CameraFarFadeDistance("Camera Far Fade", Float) = 2.0

        // Hidden properties
        [HideInInspector] _Mode("__mode", Float) = 0.0
        [HideInInspector] _ColorMode("__colormode", Float) = 0.0
        [HideInInspector] _FlipbookMode("__flipbookmode", Float) = 0.0
        [HideInInspector] _LightingEnabled("__lightingenabled", Float) = 0.0
        [HideInInspector] _DistortionEnabled("__distortionenabled", Float) = 0.0
        [HideInInspector] _EmissionEnabled("__emissionenabled", Float) = 0.0
        [HideInInspector] _BlendOp("__blendop", Float) = 0.0
        [HideInInspector] _SrcBlend("__src", Float) = 1.0
        [HideInInspector] _DstBlend("__dst", Float) = 0.0
        [HideInInspector] _ZWrite("__zw", Float) = 1.0
        [HideInInspector] _Cull("__cull", Float) = 2.0
        [HideInInspector] _SoftParticlesEnabled("__softparticlesenabled", Float) = 0.0
        [HideInInspector] _CameraFadingEnabled("__camerafadingenabled", Float) = 0.0
        [HideInInspector] _SoftParticleFadeParams("__softparticlefadeparams", Vector) = (0,0,0,0)
        [HideInInspector] _CameraFadeParams("__camerafadeparams", Vector) = (0,0,0,0)
        [HideInInspector] _ColorAddSubDiff("__coloraddsubdiff", Vector) = (0,0,0,0)
        [HideInInspector] _DistortionStrengthScaled("__distortionstrengthscaled", Float) = 0.0
    }

        Category
    {
        SubShader
    {
        Tags{ "RenderType" = "Opaque" "IgnoreProjector" = "True" "PreviewType" = "Plane" "PerformanceChecks" = "False" }

        BlendOp[_BlendOp]
        Blend[_SrcBlend][_DstBlend]
        ZWrite[_ZWrite]
        Offset -1, -1
        Cull[_Cull]
        ColorMask RGBA

        GrabPass
    {
        Tags{ "LightMode" = "Always" }
        "_GrabTexture"
    }

        Pass
    {
        Name "ShadowCaster"
        Tags{ "LightMode" = "ShadowCaster" }

        BlendOp Add
        Blend One Zero
        ZWrite On
        Cull Off

        CGPROGRAM
#pragma target 2.5

#pragma shader_feature _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON _ALPHAMODULATE_ON
#pragma shader_feature _ _COLOROVERLAY_ON _COLORCOLOR_ON _COLORADDSUBDIFF_ON
#pragma shader_feature _REQUIRE_UV2
#pragma multi_compile_shadowcaster
#pragma multi_compile_instancing
#pragma instancing_options procedural:vertInstancingSetup

#pragma vertex vertParticleShadowCaster
#pragma fragment fragParticleShadowCaster

#include "UnityStandardParticleShadow.cginc"
        ENDCG
    }

        Pass
    {
        Tags{ "LightMode" = "ForwardBase" }

        CGPROGRAM
#pragma multi_compile __ SOFTPARTICLES_ON
#pragma multi_compile_fog
#pragma target 2.5

#pragma shader_feature _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON _ALPHAMODULATE_ON
#pragma shader_feature _ _COLOROVERLAY_ON _COLORCOLOR_ON _COLORADDSUBDIFF_ON
#pragma shader_feature _NORMALMAP
#pragma shader_feature _EMISSION
#pragma shader_feature _FADING_ON
#pragma shader_feature _REQUIRE_UV2
#pragma shader_feature EFFECT_BUMP

#pragma vertex vertParticleUnlit
#pragma fragment fragParticleUnlit
#pragma multi_compile_instancing
#pragma instancing_options procedural:vertInstancingSetup

#include "UnityStandardParticles.cginc"
        ENDCG
    }
    }
    }

        Fallback "VertexLit"
        CustomEditor "StandardParticlesShaderGUI"
}
</code>```

TransparentNoOverlap.shader

```<code>// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'

/*
 * Taken from:
 * https://forum.unity.com/threads/transparent-depth-shader-good-for-ghosts.149511/
 */

Shader "Transparent/TransparentNoOverlap" {
Properties {
     [PerRendererData]_Color ("Main Color", Color) = (1,1,1,1)
    _MainTex ("Base (RGB) Trans (A)", 2D) = "white" {}
}

SubShader {
    Tags {"RenderType"="Transparent" "Queue"="Transparent" "IgnoreProjector"="True"}
    LOD 200

    Pass {
        Name "TRANSPARENT"

        ZWrite On
        ZTest LEqual
        Blend SrcAlpha OneMinusSrcAlpha
        ColorMask RGBA

        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        #include "UnityCG.cginc"

        fixed4 _Color;

        struct v2f {
            float4 pos : SV_POSITION;
        };

        v2f vert (appdata_base v)
        {
            v2f o;
            o.pos = UnityObjectToClipPos (v.vertex);
            return o;
        }

        half4 frag (v2f i) : COLOR
        {
            return _Color;
        }
        ENDCG
    }

    CGPROGRAM
    #pragma surface surf Lambert alpha
    #pragma debug

    sampler2D _MainTex;
    fixed4 _Color;

    struct Input {
        float2 uv_MainTex;
    };

    void surf (Input IN, inout SurfaceOutput o) {
        fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color;
        o.Albedo = c.rgba;
        o.Alpha = c.a;
    }
    ENDCG
}

Fallback "Transparent/Diffuse"
}
</code>```

I want materials using UnlitRGBA to always render over TransparentNoOverlap. What would I do in order to achieve this result? I have tried adding Offset -1, -1 or Offset 0, -1 to UnlitRGBA. When testing this against the standard surface shader, it works fine and the UnlitRGBA consistently renders on top. But when rendering with TransparentNoOverlap, either there is z-fighting or TransparentNoOverlap always renders on top. Why is this? I think that perhaps it has something to do with ZTests or ZWrites, but I am ultimately unsure.

I apologize for the large code samples... Thanks for any help you can provide.

rbjacob

答:
Note that the expected result and the setup are slightly ambiguous, so there might be several ways to go.

Simply put: Material with shader A (Unlit) is covered up by B (Transparent) because B is drawn after it. "Queue"="Transparent" is the flag responsible for that effect in B.
Shader A doesn't have it so it uses the default "Geometry" queue. (You can read about the index value used under the hood here: https://docs.unity3d.com/Manual/SL-SubShaderTags.html).
So in this regard you could specify the queue indices explicitly, and make sure they match your expected behavior.

This disregards another aspect: the ZBuffer, which deals with occlusion of one mesh by another, made so that they are actually not dependent on that draw order. Pixels can be discarded based on a depth test, and depth can be written by object if specified to do so. (https://docs.unity3d.com/Manual/SL-CullAndDepth.html)

Meshes display z-fighting if both of them write and test, and are co-planar (in the same spot) or the buffer has low precision so the values stored make it seems like they are.

Provided that both your meshes need to be occluded and occlude others and themselves, one way would be to set B (Transparent) to use ZTest Less, so that it only appears when A is not present at all, even if drawn after A, and even if co-planar with A.

Body:
I have two shaders, UnlitRGBA and TransparentNoOverlap. They are as follows:

UnlitRGBA.shaderlab

// Unity built-in shader source. Copyright (c) 2016 Unity Technologies. MIT license (see license.txt)
// modified by rbjacob101

Shader "Particles/Standard Unlit (RGBA)"
{
    Properties
    {
        _MainTex("Albedo", 2D) = "white" {}
    _Color("Color", Color) = (1,1,1,1)

        _Cutoff("Alpha Cutoff", Range(0.0, 1.0)) = 0.5

        _BumpScale("Scale", Float) = 1.0
        _BumpMap("Normal Map", 2D) = "bump" {}

    _EmissionColor("Color", Color) = (0,0,0)
        _EmissionMap("Emission", 2D) = "white" {}

    _DistortionStrength("Strength", Float) = 1.0
        _DistortionBlend("Blend", Range(0.0, 1.0)) = 0.5

        _SoftParticlesNearFadeDistance("Soft Particles Near Fade", Float) = 0.0
        _SoftParticlesFarFadeDistance("Soft Particles Far Fade", Float) = 1.0
        _CameraNearFadeDistance("Camera Near Fade", Float) = 1.0
        _CameraFarFadeDistance("Camera Far Fade", Float) = 2.0

        // Hidden properties
        [HideInInspector] _Mode("__mode", Float) = 0.0
        [HideInInspector] _ColorMode("__colormode", Float) = 0.0
        [HideInInspector] _FlipbookMode("__flipbookmode", Float) = 0.0
        [HideInInspector] _LightingEnabled("__lightingenabled", Float) = 0.0
        [HideInInspector] _DistortionEnabled("__distortionenabled", Float) = 0.0
        [HideInInspector] _EmissionEnabled("__emissionenabled", Float) = 0.0
        [HideInInspector] _BlendOp("__blendop", Float) = 0.0
        [HideInInspector] _SrcBlend("__src", Float) = 1.0
        [HideInInspector] _DstBlend("__dst", Float) = 0.0
        [HideInInspector] _ZWrite("__zw", Float) = 1.0
        [HideInInspector] _Cull("__cull", Float) = 2.0
        [HideInInspector] _SoftParticlesEnabled("__softparticlesenabled", Float) = 0.0
        [HideInInspector] _CameraFadingEnabled("__camerafadingenabled", Float) = 0.0
        [HideInInspector] _SoftParticleFadeParams("__softparticlefadeparams", Vector) = (0,0,0,0)
        [HideInInspector] _CameraFadeParams("__camerafadeparams", Vector) = (0,0,0,0)
        [HideInInspector] _ColorAddSubDiff("__coloraddsubdiff", Vector) = (0,0,0,0)
        [HideInInspector] _DistortionStrengthScaled("__distortionstrengthscaled", Float) = 0.0
    }

        Category
    {
        SubShader
    {
        Tags{ "RenderType" = "Opaque" "IgnoreProjector" = "True" "PreviewType" = "Plane" "PerformanceChecks" = "False" }

        BlendOp[_BlendOp]
        Blend[_SrcBlend][_DstBlend]
        ZWrite[_ZWrite]
        Offset -1, -1
        Cull[_Cull]
        ColorMask RGBA

        GrabPass
    {
        Tags{ "LightMode" = "Always" }
        "_GrabTexture"
    }

        Pass
    {
        Name "ShadowCaster"
        Tags{ "LightMode" = "ShadowCaster" }

        BlendOp Add
        Blend One Zero
        ZWrite On
        Cull Off

        CGPROGRAM
#pragma target 2.5

#pragma shader_feature _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON _ALPHAMODULATE_ON
#pragma shader_feature _ _COLOROVERLAY_ON _COLORCOLOR_ON _COLORADDSUBDIFF_ON
#pragma shader_feature _REQUIRE_UV2
#pragma multi_compile_shadowcaster
#pragma multi_compile_instancing
#pragma instancing_options procedural:vertInstancingSetup

#pragma vertex vertParticleShadowCaster
#pragma fragment fragParticleShadowCaster

#include "UnityStandardParticleShadow.cginc"
        ENDCG
    }

        Pass
    {
        Tags{ "LightMode" = "ForwardBase" }

        CGPROGRAM
#pragma multi_compile __ SOFTPARTICLES_ON
#pragma multi_compile_fog
#pragma target 2.5

#pragma shader_feature _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON _ALPHAMODULATE_ON
#pragma shader_feature _ _COLOROVERLAY_ON _COLORCOLOR_ON _COLORADDSUBDIFF_ON
#pragma shader_feature _NORMALMAP
#pragma shader_feature _EMISSION
#pragma shader_feature _FADING_ON
#pragma shader_feature _REQUIRE_UV2
#pragma shader_feature EFFECT_BUMP

#pragma vertex vertParticleUnlit
#pragma fragment fragParticleUnlit
#pragma multi_compile_instancing
#pragma instancing_options procedural:vertInstancingSetup

#include "UnityStandardParticles.cginc"
        ENDCG
    }
    }
    }

        Fallback "VertexLit"
        CustomEditor "StandardParticlesShaderGUI"
}

TransparentNoOverlap.shader

// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'

/*
 * Taken from:
 * https://forum.unity.com/threads/transparent-depth-shader-good-for-ghosts.149511/
 */

Shader "Transparent/TransparentNoOverlap" {
Properties {
     [PerRendererData]_Color ("Main Color", Color) = (1,1,1,1)
    _MainTex ("Base (RGB) Trans (A)", 2D) = "white" {}
}

SubShader {
    Tags {"RenderType"="Transparent" "Queue"="Transparent" "IgnoreProjector"="True"}
    LOD 200

    Pass {
        Name "TRANSPARENT"

        ZWrite On
        ZTest LEqual
        Blend SrcAlpha OneMinusSrcAlpha
        ColorMask RGBA

        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        #include "UnityCG.cginc"

        fixed4 _Color;

        struct v2f {
            float4 pos : SV_POSITION;
        };

        v2f vert (appdata_base v)
        {
            v2f o;
            o.pos = UnityObjectToClipPos (v.vertex);
            return o;
        }

        half4 frag (v2f i) : COLOR
        {
            return _Color;
        }
        ENDCG
    }

    CGPROGRAM
    #pragma surface surf Lambert alpha
    #pragma debug

    sampler2D _MainTex;
    fixed4 _Color;

    struct Input {
        float2 uv_MainTex;
    };

    void surf (Input IN, inout SurfaceOutput o) {
        fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color;
        o.Albedo = c.rgba;
        o.Alpha = c.a;
    }
    ENDCG
}

Fallback "Transparent/Diffuse"
}

I want materials using UnlitRGBA to always render over TransparentNoOverlap. What would I do in order to achieve this result? I have tried adding Offset -1, -1 or Offset 0, -1 to UnlitRGBA. When testing this against the standard surface shader, it works fine and the UnlitRGBA consistently renders on top. But when rendering with TransparentNoOverlap, either there is z-fighting or TransparentNoOverlap always renders on top. Why is this? I think that perhaps it has something to do with ZTests or ZWrites, but I am ultimately unsure.

I apologize for the large code samples... Thanks for any help you can provide.

rbjacob


问:
Multiple arguments in Python function
The code I have is works for one argument. But I am trying to pass through multiple arguments at a time.

```<code>def day(x):
    mydict = { 2.4:104.2 , 5:109.2, 5.5:112.2, 2.1:110.2, 5.7:114}
    keylist=sorted(mydict.keys())

    if x in mydict:
        return mydict[x]

    elif x> max(mydict.keys()):
        return mydict[max(mydict.keys())]

    elif x< min(mydict.keys()):
        return 'NaN'

    else:
        y=len(keylist)-1
        for i in keylist:
            if x>keylist[y]:
                return mydict[keylist[y]]
            else:
                y=y-1
</code>```

The code I tried for the multiple arguments used

```<code>def day(*z):

for x in z:
 #rest of code
continue
</code>```

how ever this only seemed to return one answer, that being the first value from the list z.
Where am I going wrong?

Thanks

答: You want to return one value for each element on te iterable ? Try to use yield instead of return.

Title: Multiple arguments in Python function

Body:
The code I have is works for one argument. But I am trying to pass through multiple arguments at a time.

def day(x):
    mydict = { 2.4:104.2 , 5:109.2, 5.5:112.2, 2.1:110.2, 5.7:114}
    keylist=sorted(mydict.keys())

    if x in mydict:
        return mydict[x]

    elif x> max(mydict.keys()):
        return mydict[max(mydict.keys())]

    elif x< min(mydict.keys()):
        return 'NaN'

    else:
        y=len(keylist)-1
        for i in keylist:
            if x>keylist[y]:
                return mydict[keylist[y]]
            else:
                y=y-1

The code I tried for the multiple arguments used

def day(*z):

for x in z:
 #rest of code
continue

how ever this only seemed to return one answer, that being the first value from the list z.
Where am I going wrong?

Thanks


问:
How to join a dataframe and dictionary on two rows
I have a dictionary and a dataframe. The dictionary contains a mapping of one letter to one number and the dataframe has a row containing these specific letters and another row containing these specific numbers, adjacent to each other (not that it necessarily matters).

I want to update the row containing the numbers by matching each letter in the row of the dataframe with the letter in the dictionary and then replacing the corresponding number (number in the same column as the letter) with the value of that letter from the dictionary.

```<code>df = pd.DataFrame(np.array([[4, 5, 6], ['a', 'b', 'c'], [7, 8, 9]]))

dict = {'a':2, 'b':3, 'c':5}
</code>```

Let's say dict is the dictionary and df is the dataframe I want the result to be df2.

```<code>df2 = pd.DataFrame(np.array([[3, 2, 5], ['b', 'a', 'c'], [7, 8, 9]]))
</code>```

df

```<code>   0  1  2
0  4  5  6
1  a  b  c
2  7  8  9
</code>```

dict

```<code>{'a': 2, 'b': 3, 'c': 5}
</code>```

df2

```<code>   0  1  2
0  2  3  5
1  a  b  c
2  7  8  9
</code>```

I do not know how to use merge or join to fix this, my initial thoughts are to make the dictionary a dataframe object but I am not sure where to go from there.

答:
It's a little weird, but:

df = pd.DataFrame(np.array([[4, 5, 6], ['a', 'b', 'c'], [7, 8, 9]]))
d = {'a': 2, 'b': 3, 'c': 5}
df.iloc[0] = df.iloc[1].map(lambda x: d[x] if x in d.keys() else x)

df
#    0  1  2
# 0  2  3  5
# 1  a  b  c
# 2  7  8  9
```

<p>I couldn't bring myself to redefine <code>dict</code> to be a particular dictionary. :D</p>

<p>After receiving a much-deserved smackdown regarding the speed of <code>apply</code>, I present to you the theoretically faster approach below:</p>

<pre class="lang-py prettyprint-override"><code>df.iloc[0] = df.iloc[1].map(d).where(df.iloc[1].isin(d.keys()), df.iloc[0])
</code>```

This gives you the dictionary value of d (df.iloc[1].map(d)) if the value in row 1 is in the keys of d (.where(df.iloc[1].isin(d.keys()), ...), otherwise gives you the value in row 0 (...df.iloc[0])).

Hope this helps!

Body:
I have a dictionary and a dataframe. The dictionary contains a mapping of one letter to one number and the dataframe has a row containing these specific letters and another row containing these specific numbers, adjacent to each other (not that it necessarily matters).

I want to update the row containing the numbers by matching each letter in the row of the dataframe with the letter in the dictionary and then replacing the corresponding number (number in the same column as the letter) with the value of that letter from the dictionary.

df = pd.DataFrame(np.array([[4, 5, 6], ['a', 'b', 'c'], [7, 8, 9]]))

dict = {'a':2, 'b':3, 'c':5}

Let's say dict is the dictionary and df is the dataframe I want the result to be df2.

df2 = pd.DataFrame(np.array([[3, 2, 5], ['b', 'a', 'c'], [7, 8, 9]]))

df

   0  1  2
0  4  5  6
1  a  b  c
2  7  8  9

dict

{'a': 2, 'b': 3, 'c': 5}

df2

   0  1  2
0  2  3  5
1  a  b  c
2  7  8  9

I do not know how to use merge or join to fix this, my initial thoughts are to make the dictionary a dataframe object but I am not sure where to go from there.

Body:
It's a little weird, but:

df = pd.DataFrame(np.array([[4, 5, 6], ['a', 'b', 'c'], [7, 8, 9]]))
d = {'a': 2, 'b': 3, 'c': 5}
df.iloc[0] = df.iloc[1].map(lambda x: d[x] if x in d.keys() else x)

df
#    0  1  2
# 0  2  3  5
# 1  a  b  c
# 2  7  8  9

I couldn't bring myself to redefine dict to be a particular dictionary. :D

After receiving a much-deserved smackdown regarding the speed of apply, I present to you the theoretically faster approach below:

df.iloc[0] = df.iloc[1].map(d).where(df.iloc[1].isin(d.keys()), df.iloc[0])

This gives you the dictionary value of d (df.iloc[1].map(d)) if the value in row 1 is in the keys of d (.where(df.iloc[1].isin(d.keys()), ...), otherwise gives you the value in row 0 (...df.iloc[0])).

Hope this helps!


问:
Curly braces around a parameter in Angular
Looking at some Angular code:

    @Component({
      selector: 'my-app',
      templateUrl: 'kendoGrid.component.html'
    })
    export class AppComponent implements OnInit {

        public editDataItem: Product;
        public isNew: boolean;
        private editService: EditService;

        public editHandler({dataItem}) { // What does wrapping a parameter in curly braces do?
            this.editDataItem = dataItem;
            this.isNew = false;
        }
    }
```

I could not find much result when I try to google curly braces / moustache with parameter in the context of Angular. What effect is achieved by wrapping a parameter in curly braces in Angular?

Thanks.

答:
Instead of adding an object like

```<code>const dataItem = {test: "test"};
</code>```

and pass it to a function, in ES6 we can directly pass an object like the one below.

```<code>public editHandler({test: "test"}) {
        this.editDataItem = test;
        this.isNew = false;
    }
</code>```

curly braces are nothing but an object.

Body:
Looking at some Angular code:

    @Component({
      selector: 'my-app',
      templateUrl: 'kendoGrid.component.html'
    })
    export class AppComponent implements OnInit {

        public editDataItem: Product;
        public isNew: boolean;
        private editService: EditService;

        public editHandler({dataItem}) { // What does wrapping a parameter in curly braces do?
            this.editDataItem = dataItem;
            this.isNew = false;
        }
    }

I could not find much result when I try to google curly braces / moustache with parameter in the context of Angular. What effect is achieved by wrapping a parameter in curly braces in Angular?

Thanks.

Body:
Instead of adding an object like

const dataItem = {test: "test"};

and pass it to a function, in ES6 we can directly pass an object like the one below.

public editHandler({test: "test"}) {
        this.editDataItem = test;
        this.isNew = false;
    }

curly braces are nothing but an object.


问:
Hide NSWindowToolbarButton
What do I have to do for hiding this NSWindowToolbarButton in windows with a NSToolbar?

答: FYI, if you ever need access to any of the window buttons, or to find out if a particular window even has a certain button, you can use standardWindowButton: Take a look at the corresponding Apple Docs

OwnerDisplayName: xPablo

ContentLicense: CC BY-SA 2.5

Title: Hide NSWindowToolbarButton

OwnerDisplayName: Alex


问:
resource for practical javascript exercise
I am beginner to webprogramming &  Javascript. I have went through few tutorials and learned the basics. Could someone suggest me the best resource with practical exercise with solutions.

I found "pagetutor.com" which has practical javascript exercises, but it's paid! Please
suggest any paid sites too which is really worth for practical learning.

答:
I learned that from books.
Basics: W3schools javaScript

For advanced I suggest these books:
Advanced JavaScript(TM), Third Edition
Pro JavaScript Techniques

Professional JavaScript for Web Developers (Wrox Programmer to Programmer)

Books are cheap :)

Also I bought W3Schools books about HTML, JavaScript and CSS and I like it :)


问:
How to set breakpoints in inline Javascript in Google Chrome?
When I open Developer Tools in Google Chrome, I see all kinds of features like Profiles, Timelines, and Audits, but basic functionality like being able to set breakpoints both in js files and within html and javascript code is missing! I tried to use the javascript console, which itself is buggy - for example, once it encounters a JS error, I cannot get out of it unless I refresh the whole page. Can someone help? </p>

答:
I know the Q is not about Firefox but I did not want to add a copy of this question to just answer it myself.

For Firefox you need to add  debugger; to be able to do what @matt-ball suggested for the script tag.

So on your code, you add debugger above the line you want to debug and then you can add breakpoints. If you just set the breakpoints on the browser it won't stop.

If this is not the place to add a Firefox answer given that the question is about Chrome. Don't :( minus the answer just let me know where I should post it and I'll happily move the post. :)


问:
Obtain the indices of neighboring elements within a radius
I have a NxN matrix and I want to find indices (or at least count) of non-zero elements within a radius R for each element in matrix. The matrix will be large so I plan to do the calculations using Numpy, and I need the indices because this matrix is linked to another with data-storage (which is a python list [[]] of objects).

The matrix looks like this:

where Green is the selected cell, Yellow - the surrounding area.

The main problem is the moving stencil, either in loop or vectorized.

I tried the following code which gives the correct coordinates (all within radius and excluding center) relative to the point, but I dont know how to apply it to the numpy array:

r = 2
neighbor_coords = []
for i in list(itertools.product(range(-r, r+1), repeat=2)):
    if any(i) and np.sqrt(i[0]**2 + i[1]**2) <= r:
        neighbor_coords.append(i)

>>> [(-2, 0), (-1, -1), (-1, 0), (-1, 1), (0, -2), (0, -1), (0, 1), (0, 2), (1, -1), (1, 0), (1, 1), (2, 0)]
```

Expected output is the indices or count of neighboring elements.

答:
This might get you part way there.  You can use the convolve function in scipy to convolve your matrix with a kernel that you generate.  This below will count the non-zero entries within the reach of the kernel.  Note that I transformed the input matrix to ones so that it was summing the non-zero locations, not the values.

```<code>In [74]: import numpy as np

In [75]: from scipy.ndimage.filters import *

In [76]: a
Out[76]:
array([[1, 2, 0, 0],
       [1, 1, 0, 0],
       [0, 0, 0, 0],
       [5, 5, 5, 5]])

In [77]: a_ones = np.where(a>0, 1, 0)

In [78]: a_ones
Out[78]:
array([[1, 1, 0, 0],
       [1, 1, 0, 0],
       [0, 0, 0, 0],
       [1, 1, 1, 1]])

In [79]: k
Out[79]:
array([[0, 1, 0],
       [1, 0, 1],
       [0, 1, 0]])

In [80]: convolve(a_ones, k, mode='constant')
Out[80]:
array([[2, 2, 1, 0],
       [2, 2, 1, 0],
       [2, 2, 1, 1],
       [1, 2, 2, 1]])

In [81]:
</code>```

Body:
I have a NxN matrix and I want to find indices (or at least count) of non-zero elements within a radius R for each element in matrix. The matrix will be large so I plan to do the calculations using Numpy, and I need the indices because this matrix is linked to another with data-storage (which is a python list [[]] of objects).

The matrix looks like this:

where Green is the selected cell, Yellow - the surrounding area.

The main problem is the moving stencil, either in loop or vectorized.

I tried the following code which gives the correct coordinates (all within radius and excluding center) relative to the point, but I dont know how to apply it to the numpy array:

r = 2
neighbor_coords = []
for i in list(itertools.product(range(-r, r+1), repeat=2)):
    if any(i) and np.sqrt(i[0]**2 + i[1]**2) <= r:
        neighbor_coords.append(i)

>>> [(-2, 0), (-1, -1), (-1, 0), (-1, 1), (0, -2), (0, -1), (0, 1), (0, 2), (1, -1), (1, 0), (1, 1), (2, 0)]

Expected output is the indices or count of neighboring elements.

Body:
This might get you part way there.  You can use the convolve function in scipy to convolve your matrix with a kernel that you generate.  This below will count the non-zero entries within the reach of the kernel.  Note that I transformed the input matrix to ones so that it was summing the non-zero locations, not the values.

In [74]: import numpy as np

In [75]: from scipy.ndimage.filters import *

In [76]: a
Out[76]:
array([[1, 2, 0, 0],
       [1, 1, 0, 0],
       [0, 0, 0, 0],
       [5, 5, 5, 5]])

In [77]: a_ones = np.where(a>0, 1, 0)

In [78]: a_ones
Out[78]:
array([[1, 1, 0, 0],
       [1, 1, 0, 0],
       [0, 0, 0, 0],
       [1, 1, 1, 1]])

In [79]: k
Out[79]:
array([[0, 1, 0],
       [1, 0, 1],
       [0, 1, 0]])

In [80]: convolve(a_ones, k, mode='constant')
Out[80]:
array([[2, 2, 1, 0],
       [2, 2, 1, 0],
       [2, 2, 1, 1],
       [1, 2, 2, 1]])

In [81]:


问:
Saving then reusing CNN models - preserving initializations
I wish to repeat a series of image classification experiments by reusing a CNN with the same CNN with identical hyperparameters especially initializations. So, if I save a model after I have instantiated it and before I train it, does that also save the initializations so I then reload it later and train with a different data set and labels, does it start this new model with the same hyperparameters and initializations as the first model I trained with the first data set/classification labels? I am currently using fastai which is, of course, a library/set of API's, built on Pythorch but I think that everyone would be helped with a more general explanation that covers all CNN's using any library.

I expect an answer that says, "after this point in the workflow creating a CNN, the model is initialized and if you save it at this point, you can reload it later and use the same hyperparameters and initializations in your next model."

答:
you can save the learner as soon it is created.

Example:

```<code>learn = cnn_learner(data,models.resnet34,metrics=error_rate)
learn.save('init')
</code>```

later on:

```<code>learn.load('init)
</code>```

Body:
you can save the learner as soon it is created.

Example:

learn = cnn_learner(data,models.resnet34,metrics=error_rate)
learn.save('init')

later on:

learn.load('init)


问:
Getting the parent pages of Page DataObject in SilverStripe
I am developing a SilverStripe project. Now I am trying to get the Page object by ID in the controller like this.

```<code>$currentPage = Page::get()->byID($this->ID);
</code>```

Also, I want to all the parents/parent of the $currentPage too. But I cannot find related columns in the database table for Page like parent_page_id or whatsoever. How can I get all the parent pages of Page data object?

答:
A Page is broadly speaking a SiteTree object. The ParentID column exists on the SiteTree database table. You can access a page's parent like so:

$parent = $currentPage->Parent();
```

<p>You can also use <code>SiteTree::getParent()</code> for the same result:</p>

<pre class="lang-php prettyprint-override"><code>$parent = $currentPage->getParent();
</code>```

If you need to get all parents recursively, you can do that in a loop until ->Parent() returns falsy.

Also, as SiteTree uses Hierarchy for the Parent/Children logic, you can also use getAncestors() to get all parents and grandparents. See the API documentation.

Body:
I am developing a SilverStripe project. Now I am trying to get the Page object by ID in the controller like this.

$currentPage = Page::get()->byID($this->ID);

Also, I want to all the parents/parent of the $currentPage too. But I cannot find related columns in the database table for Page like parent_page_id or whatsoever. How can I get all the parent pages of Page data object?

Body:
A Page is broadly speaking a SiteTree object. The ParentID column exists on the SiteTree database table. You can access a page's parent like so:

$parent = $currentPage->Parent();

You can also use SiteTree::getParent() for the same result:

$parent = $currentPage->getParent();

If you need to get all parents recursively, you can do that in a loop until ->Parent() returns falsy.

Also, as SiteTree uses Hierarchy for the Parent/Children logic, you can also use getAncestors() to get all parents and grandparents. See the API documentation.


问:
How to create 2 records with different IDs?
I have a project where people need to trade credits between them.

I'm doing this

User model

```<code>class User < ApplicationRecord
  after_create :create_bank_account

  has_one :bank_account, inverse_of: :user, dependent: :destroy
  has_many :account_transactions, inverse_of: :user, through: :bank_account
end
</code>```

Bank model

```<code>class BankAccount < ApplicationRecord
  belongs_to :user, inverse_of: :bank_account

  validates :balance, presence: true, numericality: true
  validates :user, presence: true

  has_many :account_transactions, inverse_of: :bank_account, dependent: :destroy
  accepts_nested_attributes_for :account_transactions

  before_validation :load_defaults

  def load_defaults
    if self.new_record?
    self.balance = 4.0
  end
end
</code>```

Account transactions model

```<code>class AccountTransaction < ApplicationRecord
  after_initialize :set_default_status, if: :new_record?
  after_commit :transfer, on: :create

  belongs_to :bank_account, inverse_of: :account_transactions

  enum transaction_type: [ :Received, :Sent ]
  enum status: [ :Approved, :Canceled ]

  def set_default_status
    self.status ||= :"Approved"
  end

  private

  def transfer
    source_account = BankAccount.find(source)
    target_account = BankAccount.find(target)
    ActiveRecord::Base.transaction do
      source_account.balance -= amount
      target_account.balance += amount
      source_account.save!
      target_account.save!
    end
  end
end
</code>```

The credit transfer is working fine.

But I need to create the records with the bank_id of each user.

How would i create those 2 account transactions records?

A record with bank_id of user A and another record with bank_id of user B.

I do not know if the best way to handle transactions between users would be this way

答:
Why you need 2 records for AccountTransaction?
I strongly recommend you to save 2 bank_account ids in the AccountTransaction model, see:

# acount_transaction.rb
class AccountTransaction < ApplicationRecord
  after_initialize :set_default_status, if: :new_record?
  after_commit :transfer, on: :create

  belongs_to :target_bank_account, foreign_key: 'target_id', class_name: 'BankAccount'
  belongs_to :source_bank_account, foreign_key: 'source_id', class_name: 'BankAccount'

  enum transaction_type: [ :Received, :Sent ]
  enum status: [ :Approved, :Canceled ]

  def set_default_status
    self.status ||= :"Approved"
  end

  private

  def transfer
    ActiveRecord::Base.transaction do
      self.source_bank_account.balance -= amount
      self.target_bank_account.balance += amount
      source_bank_account.save!
      target_bank_account.save!
    end
  end
end
```
<p>You just need to create a new migration adding the <code>target_id</code> and <code>source_id</code> to <code>AcountTransaction</code>.</p>
<p>If you do it, you will be able to save in just 1 record the <code>source_account</code> and the <code>target_account</code>, this makes more sense, what do you think?</p>
<h1>Update</h1>
<p>You should remove the <code>bank_id</code> and create 2 new <code>foreing_keys</code>: <code>target_bank_id</code> and <code>source_bank_id</code> for <code>AccountModel</code>.</p>
<p>In the <code>BankAccount</code> model, you can add the following lines:</p>
<pre class="lang-rb prettyprint-override"><code># bank_account.rb
has_many incoming_transfers, foreign_key: 'target_bank_id', class_name: 'AccountTransaction'
has_many made_transfers
, foreign_key: 'source_bank_id', class_name: 'AccountTransaction'

</code>```

After it, you can check for each BankAccount how many transfers are made and received!

You can see more about this kind of association clicking here!

Body:
I have a project where people need to trade credits between them.

I'm doing this

User model

class User < ApplicationRecord
  after_create :create_bank_account

  has_one :bank_account, inverse_of: :user, dependent: :destroy
  has_many :account_transactions, inverse_of: :user, through: :bank_account
end

Bank model

class BankAccount < ApplicationRecord
  belongs_to :user, inverse_of: :bank_account

  validates :balance, presence: true, numericality: true
  validates :user, presence: true

  has_many :account_transactions, inverse_of: :bank_account, dependent: :destroy
  accepts_nested_attributes_for :account_transactions

  before_validation :load_defaults

  def load_defaults
    if self.new_record?
    self.balance = 4.0
  end
end

Account transactions model

class AccountTransaction < ApplicationRecord
  after_initialize :set_default_status, if: :new_record?
  after_commit :transfer, on: :create

  belongs_to :bank_account, inverse_of: :account_transactions

  enum transaction_type: [ :Received, :Sent ]
  enum status: [ :Approved, :Canceled ]

  def set_default_status
    self.status ||= :"Approved"
  end

  private

  def transfer
    source_account = BankAccount.find(source)
    target_account = BankAccount.find(target)
    ActiveRecord::Base.transaction do
      source_account.balance -= amount
      target_account.balance += amount
      source_account.save!
      target_account.save!
    end
  end
end

The credit transfer is working fine.

But I need to create the records with the bank_id of each user.

How would i create those 2 account transactions records?

A record with bank_id of user A and another record with bank_id of user B.

I do not know if the best way to handle transactions between users would be this way

Body:
Why you need 2 records for AccountTransaction?
I strongly recommend you to save 2 bank_account ids in the AccountTransaction model, see:

# acount_transaction.rb
class AccountTransaction < ApplicationRecord
  after_initialize :set_default_status, if: :new_record?
  after_commit :transfer, on: :create

  belongs_to :target_bank_account, foreign_key: 'target_id', class_name: 'BankAccount'
  belongs_to :source_bank_account, foreign_key: 'source_id', class_name: 'BankAccount'

  enum transaction_type: [ :Received, :Sent ]
  enum status: [ :Approved, :Canceled ]

  def set_default_status
    self.status ||= :"Approved"
  end

  private

  def transfer
    ActiveRecord::Base.transaction do
      self.source_bank_account.balance -= amount
      self.target_bank_account.balance += amount
      source_bank_account.save!
      target_bank_account.save!
    end
  end
end

You just need to create a new migration adding the target_id and source_id to AcountTransaction.

If you do it, you will be able to save in just 1 record the source_account and the target_account, this makes more sense, what do you think?

Update

You should remove the bank_id and create 2 new foreing_keys: target_bank_id and source_bank_id for AccountModel.

In the BankAccount model, you can add the following lines:

# bank_account.rb
has_many incoming_transfers, foreign_key: 'target_bank_id', class_name: 'AccountTransaction'
has_many made_transfers
, foreign_key: 'source_bank_id', class_name: 'AccountTransaction'

After it, you can check for each BankAccount how many transfers are made and received!

You can see more about this kind of association clicking here!


问:
How to print PDF document from Windows Service
I have windows service that must periodically print PDF document from server. My function is

```<code>private void PrintFormPdfData(byte[] formPdfData)
{
    string tempFile;

    tempFile = Path.GetTempFileName();

    using (FileStream fs = new FileStream(tempFile, FileMode.Create))
    {
        fs.Write(formPdfData, 0, formPdfData.Length);
        fs.Flush();
    }

    string pdfArguments = string.Format("/p /h\"{0}\"", tempFile);

    string pdfPrinterLocation = @"C:\Program Files (x86)\Adobe\Reader 9.0\Reader\AcroRd32.exe";

    ProcessStartInfo newProcess = new ProcessStartInfo(pdfPrinterLocation, pdfArguments);
    newProcess.CreateNoWindow = true;
    newProcess.RedirectStandardOutput = true;
    newProcess.UseShellExecute = false;
    newProcess.RedirectStandardError = true;

    Process pdfProcess = new Process();
    pdfProcess.StartInfo = newProcess;
    pdfProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    pdfProcess.Start();
    pdfProcess.WaitForExit();
}
</code>```

When I implement this in Windows Application it works, but when I implement in Windows service it does not work.

Can you help me?

答:
I solved problem with Session 0. I use this class:

```<code>public class ProcessStarter : IDisposable
{
    #region Import Section

    private static uint STANDARD_RIGHTS_REQUIRED = 0x000F0000;
    private static uint STANDARD_RIGHTS_READ = 0x00020000;
    private static uint TOKEN_ASSIGN_PRIMARY = 0x0001;
    private static uint TOKEN_DUPLICATE = 0x0002;
    private static uint TOKEN_IMPERSONATE = 0x0004;
    private static uint TOKEN_QUERY = 0x0008;
    private static uint TOKEN_QUERY_SOURCE = 0x0010;
    private static uint TOKEN_ADJUST_PRIVILEGES = 0x0020;
    private static uint TOKEN_ADJUST_GROUPS = 0x0040;
    private static uint TOKEN_ADJUST_DEFAULT = 0x0080;
    private static uint TOKEN_ADJUST_SESSIONID = 0x0100;
    private static uint TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY);
    private static uint TOKEN_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE | TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID);

    private const uint NORMAL_PRIORITY_CLASS = 0x0020;

    private const uint CREATE_UNICODE_ENVIRONMENT = 0x00000400;

    private const uint MAX_PATH = 260;

    private const uint CREATE_NO_WINDOW = 0x08000000;

    private const uint INFINITE = 0xFFFFFFFF;

    [StructLayout(LayoutKind.Sequential)]
    public struct SECURITY_ATTRIBUTES
    {
        public int nLength;
        public IntPtr lpSecurityDescriptor;
        public int bInheritHandle;
    }

    public enum SECURITY_IMPERSONATION_LEVEL
    {
        SecurityAnonymous,
        SecurityIdentification,
        SecurityImpersonation,
        SecurityDelegation
    }

    public enum TOKEN_TYPE
    {
        TokenPrimary = 1,
        TokenImpersonation
    }

    public enum WTS_CONNECTSTATE_CLASS
    {
        WTSActive,
        WTSConnected,
        WTSConnectQuery,
        WTSShadow,
        WTSDisconnected,
        WTSIdle,
        WTSListen,
        WTSReset,
        WTSDown,
        WTSInit
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    public struct STARTUPINFO
    {
        public Int32 cb;
        public string lpReserved;
        public string lpDesktop;
        public string lpTitle;
        public Int32 dwX;
        public Int32 dwY;
        public Int32 dwXSize;
        public Int32 dwYSize;
        public Int32 dwXCountChars;
        public Int32 dwYCountChars;
        public Int32 dwFillAttribute;
        public Int32 dwFlags;
        public Int16 wShowWindow;
        public Int16 cbReserved2;
        public IntPtr lpReserved2;
        public IntPtr hStdInput;
        public IntPtr hStdOutput;
        public IntPtr hStdError;
    }

    [StructLayout(LayoutKind.Sequential)]
    internal struct PROCESS_INFORMATION
    {
        public IntPtr hProcess;
        public IntPtr hThread;
        public int dwProcessId;
        public int dwThreadId;
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct WTS_SESSION_INFO
    {
        public Int32 SessionID;

        [MarshalAs(UnmanagedType.LPStr)]
        public String pWinStationName;

        public WTS_CONNECTSTATE_CLASS State;
    }

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern uint WTSGetActiveConsoleSessionId();

    [DllImport("wtsapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern bool WTSQueryUserToken(int sessionId, out IntPtr tokenHandle);

    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public extern static bool DuplicateTokenEx(IntPtr existingToken, uint desiredAccess, IntPtr tokenAttributes, SECURITY_IMPERSONATION_LEVEL impersonationLevel, TOKEN_TYPE tokenType, out IntPtr newToken);

    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern bool CreateProcessAsUser(IntPtr token, string applicationName, string commandLine, ref SECURITY_ATTRIBUTES processAttributes, ref SECURITY_ATTRIBUTES threadAttributes, bool inheritHandles, uint creationFlags, IntPtr environment, string currentDirectory, ref STARTUPINFO startupInfo, out PROCESS_INFORMATION processInformation);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern bool CloseHandle(IntPtr handle);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern int GetLastError();

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern int WaitForSingleObject(IntPtr token, uint timeInterval);

    [DllImport("wtsapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern int WTSEnumerateSessions(System.IntPtr hServer, int Reserved, int Version, ref System.IntPtr ppSessionInfo, ref int pCount);

    [DllImport("userenv.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern bool CreateEnvironmentBlock(out IntPtr lpEnvironment, IntPtr hToken, bool bInherit);

    [DllImport("wtsapi32.dll", ExactSpelling = true, SetLastError = false)]
    public static extern void WTSFreeMemory(IntPtr memory);

    [DllImport("userenv.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool DestroyEnvironmentBlock(IntPtr lpEnvironment);

    #endregion

    /// <summary>
    /// Initializes a new instance of the <see cref="ProcessStarter"/> class.
    /// </summary>
    public ProcessStarter()
    {

    }

    /// <summary>
    /// Initializes a new instance of the <see cref="ProcessStarter"/> class.
    /// </summary>
    /// <param name="processName">Name of the process.</param>
    /// <param name="fullExeName">Full name of the exe.</param>
    public ProcessStarter(string processName, string fullExeName)
    {
        processName_ = processName;
        processPath_ = fullExeName;
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="ProcessStarter"/> class.
    /// </summary>
    /// <param name="processName">Name of the process.</param>
    /// <param name="fullExeName">Full name of the exe.</param>
    /// <param name="arguments">The arguments.</param>
    public ProcessStarter(string processName, string fullExeName, string arguments)
    {
        processName_ = processName;
        processPath_ = fullExeName;
        arguments_ = arguments;
    }

    /// <summary>
    /// Gets the current user token.
    /// </summary>
    /// <returns></returns>
    public static IntPtr GetCurrentUserToken()
    {
        IntPtr currentToken = IntPtr.Zero;
        IntPtr primaryToken = IntPtr.Zero;
        IntPtr WTS_CURRENT_SERVER_HANDLE = IntPtr.Zero;

        int dwSessionId = 0;
        IntPtr hUserToken = IntPtr.Zero;
        IntPtr hTokenDup = IntPtr.Zero;

        IntPtr pSessionInfo = IntPtr.Zero;
        int dwCount = 0;

        WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, ref pSessionInfo, ref dwCount);

        Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO));

        Int32 current = (int)pSessionInfo;
        for (int i = 0; i < dwCount; i++)
        {
            WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)current, typeof(WTS_SESSION_INFO));
            if (WTS_CONNECTSTATE_CLASS.WTSActive == si.State)
            {
                dwSessionId = si.SessionID;
                break;
            }

            current += dataSize;
        }

        WTSFreeMemory(pSessionInfo);

        bool bRet = WTSQueryUserToken(dwSessionId, out currentToken);
        if (bRet == false)
        {
            return IntPtr.Zero;
        }

        bRet = DuplicateTokenEx(currentToken, TOKEN_ASSIGN_PRIMARY | TOKEN_ALL_ACCESS, IntPtr.Zero, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenPrimary, out primaryToken);
        if (bRet == false)
        {
            return IntPtr.Zero;
        }

        return primaryToken;
    }

    /// <summary>
    /// Runs this instance.
    /// </summary>
    public void Run()
    {

        IntPtr primaryToken = GetCurrentUserToken();
        if (primaryToken == IntPtr.Zero)
        {
            return;
        }
        STARTUPINFO StartupInfo = new STARTUPINFO();
        processInfo_ = new PROCESS_INFORMATION();
        StartupInfo.cb = Marshal.SizeOf(StartupInfo);

        SECURITY_ATTRIBUTES Security1 = new SECURITY_ATTRIBUTES();
        SECURITY_ATTRIBUTES Security2 = new SECURITY_ATTRIBUTES();

        string command = "\"" + processPath_ + "\"";
        if ((arguments_ != null) && (arguments_.Length != 0))
        {
            command += " " + arguments_;
        }

        IntPtr lpEnvironment = IntPtr.Zero;
        bool resultEnv = CreateEnvironmentBlock(out lpEnvironment, primaryToken, false);
        if (resultEnv != true)
        {
            int nError = GetLastError();
        }

        CreateProcessAsUser(primaryToken, null, command, ref Security1, ref Security2, false, CREATE_NO_WINDOW | NORMAL_PRIORITY_CLASS | CREATE_UNICODE_ENVIRONMENT, lpEnvironment, null, ref StartupInfo, out processInfo_);

        DestroyEnvironmentBlock(lpEnvironment);
        CloseHandle(primaryToken);
    }

    /// <summary>
    /// Stops this instance.
    /// </summary>
    public void Stop()
    {
        Process[] processes = Process.GetProcesses();
        foreach (Process current in processes)
        {
            if (current.ProcessName == processName_)
            {
                current.Kill();
            }
        }
    }

    /// <summary>
    /// Waits for exit.
    /// </summary>
    /// <returns></returns>
    public int WaitForExit()
    {
        WaitForSingleObject(processInfo_.hProcess, INFINITE);
        int errorcode = GetLastError();
        return errorcode;
    }

    #region IDisposable Members

    /// <summary>
    /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
    /// </summary>
    public void Dispose()
    {
    }

    #endregion

    private string processPath_ = string.Empty;
    private string processName_ = string.Empty;
    private string arguments_ = string.Empty;
    private PROCESS_INFORMATION processInfo_;

    /// <summary>
    /// Gets or sets the process path.
    /// </summary>
    /// <value>The process path.</value>
    public string ProcessPath
    {
        get
        {
            return processPath_;
        }
        set
        {
            processPath_ = value;
        }
    }

    /// <summary>
    /// Gets or sets the name of the process.
    /// </summary>
    /// <value>The name of the process.</value>
    public string ProcessName
    {
        get
        {
            return processName_;
        }
        set
        {
            processName_ = value;
        }
    }

    /// <summary>
    /// Gets or sets the arguments.
    /// </summary>
    /// <value>The arguments.</value>
    public string Arguments
    {
        get
        {
            return arguments_;
        }
        set
        {
            arguments_ = value;
        }
    }
}
</code>```

Now, my function look like:

```<code>private void PrintFormPdfData(byte[] formPdfData)
{
    string tempFile;

    tempFile = Path.GetTempFileName();

    using (FileStream fs = new FileStream(tempFile, FileMode.Create))
    {
        fs.Write(formPdfData, 0, formPdfData.Length);
        fs.Flush();
    }
    string pdfArguments =string.Format("/t /o {0} \"Printer name\"", tempFile);

    string pdfPrinterLocation = @"C:\Program Files (x86)\Adobe\Reader 9.0\Reader\AcroRd32.exe";

    try
    {
        ProcessStarter processStarter = new ProcessStarter("AcroRd32", pdfPrinterLocation, pdfArguments);
        processStarter.Run();
        processStarter.WaitForExit();
        processStarter.Stop();
    }
    finally
    {
        File.Delete(tempFile);
    }
}
</code>```

Also, ServiceProcessInstaller must have `Account set to "LocalSystem". When I created service I set to "Local service" with this user it does not work. I did not try with "Network service" or "User".

Body:
I have windows service that must periodically print PDF document from server. My function is

private void PrintFormPdfData(byte[] formPdfData)
{
    string tempFile;

    tempFile = Path.GetTempFileName();

    using (FileStream fs = new FileStream(tempFile, FileMode.Create))
    {
        fs.Write(formPdfData, 0, formPdfData.Length);
        fs.Flush();
    }

    string pdfArguments = string.Format("/p /h\"{0}\"", tempFile);

    string pdfPrinterLocation = @"C:\Program Files (x86)\Adobe\Reader 9.0\Reader\AcroRd32.exe";

    ProcessStartInfo newProcess = new ProcessStartInfo(pdfPrinterLocation, pdfArguments);
    newProcess.CreateNoWindow = true;
    newProcess.RedirectStandardOutput = true;
    newProcess.UseShellExecute = false;
    newProcess.RedirectStandardError = true;

    Process pdfProcess = new Process();
    pdfProcess.StartInfo = newProcess;
    pdfProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    pdfProcess.Start();
    pdfProcess.WaitForExit();
}

When I implement this in Windows Application it works, but when I implement in Windows service it does not work.

Can you help me?

Body:
I solved problem with Session 0. I use this class:

public class ProcessStarter : IDisposable
{
    #region Import Section

    private static uint STANDARD_RIGHTS_REQUIRED = 0x000F0000;
    private static uint STANDARD_RIGHTS_READ = 0x00020000;
    private static uint TOKEN_ASSIGN_PRIMARY = 0x0001;
    private static uint TOKEN_DUPLICATE = 0x0002;
    private static uint TOKEN_IMPERSONATE = 0x0004;
    private static uint TOKEN_QUERY = 0x0008;
    private static uint TOKEN_QUERY_SOURCE = 0x0010;
    private static uint TOKEN_ADJUST_PRIVILEGES = 0x0020;
    private static uint TOKEN_ADJUST_GROUPS = 0x0040;
    private static uint TOKEN_ADJUST_DEFAULT = 0x0080;
    private static uint TOKEN_ADJUST_SESSIONID = 0x0100;
    private static uint TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY);
    private static uint TOKEN_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE | TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID);

    private const uint NORMAL_PRIORITY_CLASS = 0x0020;

    private const uint CREATE_UNICODE_ENVIRONMENT = 0x00000400;

    private const uint MAX_PATH = 260;

    private const uint CREATE_NO_WINDOW = 0x08000000;

    private const uint INFINITE = 0xFFFFFFFF;

    [StructLayout(LayoutKind.Sequential)]
    public struct SECURITY_ATTRIBUTES
    {
        public int nLength;
        public IntPtr lpSecurityDescriptor;
        public int bInheritHandle;
    }

    public enum SECURITY_IMPERSONATION_LEVEL
    {
        SecurityAnonymous,
        SecurityIdentification,
        SecurityImpersonation,
        SecurityDelegation
    }

    public enum TOKEN_TYPE
    {
        TokenPrimary = 1,
        TokenImpersonation
    }

    public enum WTS_CONNECTSTATE_CLASS
    {
        WTSActive,
        WTSConnected,
        WTSConnectQuery,
        WTSShadow,
        WTSDisconnected,
        WTSIdle,
        WTSListen,
        WTSReset,
        WTSDown,
        WTSInit
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    public struct STARTUPINFO
    {
        public Int32 cb;
        public string lpReserved;
        public string lpDesktop;
        public string lpTitle;
        public Int32 dwX;
        public Int32 dwY;
        public Int32 dwXSize;
        public Int32 dwYSize;
        public Int32 dwXCountChars;
        public Int32 dwYCountChars;
        public Int32 dwFillAttribute;
        public Int32 dwFlags;
        public Int16 wShowWindow;
        public Int16 cbReserved2;
        public IntPtr lpReserved2;
        public IntPtr hStdInput;
        public IntPtr hStdOutput;
        public IntPtr hStdError;
    }

    [StructLayout(LayoutKind.Sequential)]
    internal struct PROCESS_INFORMATION
    {
        public IntPtr hProcess;
        public IntPtr hThread;
        public int dwProcessId;
        public int dwThreadId;
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct WTS_SESSION_INFO
    {
        public Int32 SessionID;

        [MarshalAs(UnmanagedType.LPStr)]
        public String pWinStationName;

        public WTS_CONNECTSTATE_CLASS State;
    }

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern uint WTSGetActiveConsoleSessionId();

    [DllImport("wtsapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern bool WTSQueryUserToken(int sessionId, out IntPtr tokenHandle);

    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public extern static bool DuplicateTokenEx(IntPtr existingToken, uint desiredAccess, IntPtr tokenAttributes, SECURITY_IMPERSONATION_LEVEL impersonationLevel, TOKEN_TYPE tokenType, out IntPtr newToken);

    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern bool CreateProcessAsUser(IntPtr token, string applicationName, string commandLine, ref SECURITY_ATTRIBUTES processAttributes, ref SECURITY_ATTRIBUTES threadAttributes, bool inheritHandles, uint creationFlags, IntPtr environment, string currentDirectory, ref STARTUPINFO startupInfo, out PROCESS_INFORMATION processInformation);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern bool CloseHandle(IntPtr handle);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern int GetLastError();

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern int WaitForSingleObject(IntPtr token, uint timeInterval);

    [DllImport("wtsapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern int WTSEnumerateSessions(System.IntPtr hServer, int Reserved, int Version, ref System.IntPtr ppSessionInfo, ref int pCount);

    [DllImport("userenv.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern bool CreateEnvironmentBlock(out IntPtr lpEnvironment, IntPtr hToken, bool bInherit);

    [DllImport("wtsapi32.dll", ExactSpelling = true, SetLastError = false)]
    public static extern void WTSFreeMemory(IntPtr memory);

    [DllImport("userenv.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool DestroyEnvironmentBlock(IntPtr lpEnvironment);

    #endregion

    /// <summary>
    /// Initializes a new instance of the <see cref="ProcessStarter"/> class.
    /// </summary>
    public ProcessStarter()
    {

    }

    /// <summary>
    /// Initializes a new instance of the <see cref="ProcessStarter"/> class.
    /// </summary>
    /// <param name="processName">Name of the process.</param>
    /// <param name="fullExeName">Full name of the exe.</param>
    public ProcessStarter(string processName, string fullExeName)
    {
        processName_ = processName;
        processPath_ = fullExeName;
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="ProcessStarter"/> class.
    /// </summary>
    /// <param name="processName">Name of the process.</param>
    /// <param name="fullExeName">Full name of the exe.</param>
    /// <param name="arguments">The arguments.</param>
    public ProcessStarter(string processName, string fullExeName, string arguments)
    {
        processName_ = processName;
        processPath_ = fullExeName;
        arguments_ = arguments;
    }

    /// <summary>
    /// Gets the current user token.
    /// </summary>
    /// <returns></returns>
    public static IntPtr GetCurrentUserToken()
    {
        IntPtr currentToken = IntPtr.Zero;
        IntPtr primaryToken = IntPtr.Zero;
        IntPtr WTS_CURRENT_SERVER_HANDLE = IntPtr.Zero;

        int dwSessionId = 0;
        IntPtr hUserToken = IntPtr.Zero;
        IntPtr hTokenDup = IntPtr.Zero;

        IntPtr pSessionInfo = IntPtr.Zero;
        int dwCount = 0;

        WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, ref pSessionInfo, ref dwCount);

        Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO));

        Int32 current = (int)pSessionInfo;
        for (int i = 0; i < dwCount; i++)
        {
            WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)current, typeof(WTS_SESSION_INFO));
            if (WTS_CONNECTSTATE_CLASS.WTSActive == si.State)
            {
                dwSessionId = si.SessionID;
                break;
            }

            current += dataSize;
        }

        WTSFreeMemory(pSessionInfo);

        bool bRet = WTSQueryUserToken(dwSessionId, out currentToken);
        if (bRet == false)
        {
            return IntPtr.Zero;
        }

        bRet = DuplicateTokenEx(currentToken, TOKEN_ASSIGN_PRIMARY | TOKEN_ALL_ACCESS, IntPtr.Zero, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenPrimary, out primaryToken);
        if (bRet == false)
        {
            return IntPtr.Zero;
        }

        return primaryToken;
    }

    /// <summary>
    /// Runs this instance.
    /// </summary>
    public void Run()
    {

        IntPtr primaryToken = GetCurrentUserToken();
        if (primaryToken == IntPtr.Zero)
        {
            return;
        }
        STARTUPINFO StartupInfo = new STARTUPINFO();
        processInfo_ = new PROCESS_INFORMATION();
        StartupInfo.cb = Marshal.SizeOf(StartupInfo);

        SECURITY_ATTRIBUTES Security1 = new SECURITY_ATTRIBUTES();
        SECURITY_ATTRIBUTES Security2 = new SECURITY_ATTRIBUTES();

        string command = "\"" + processPath_ + "\"";
        if ((arguments_ != null) && (arguments_.Length != 0))
        {
            command += " " + arguments_;
        }

        IntPtr lpEnvironment = IntPtr.Zero;
        bool resultEnv = CreateEnvironmentBlock(out lpEnvironment, primaryToken, false);
        if (resultEnv != true)
        {
            int nError = GetLastError();
        }

        CreateProcessAsUser(primaryToken, null, command, ref Security1, ref Security2, false, CREATE_NO_WINDOW | NORMAL_PRIORITY_CLASS | CREATE_UNICODE_ENVIRONMENT, lpEnvironment, null, ref StartupInfo, out processInfo_);

        DestroyEnvironmentBlock(lpEnvironment);
        CloseHandle(primaryToken);
    }

    /// <summary>
    /// Stops this instance.
    /// </summary>
    public void Stop()
    {
        Process[] processes = Process.GetProcesses();
        foreach (Process current in processes)
        {
            if (current.ProcessName == processName_)
            {
                current.Kill();
            }
        }
    }

    /// <summary>
    /// Waits for exit.
    /// </summary>
    /// <returns></returns>
    public int WaitForExit()
    {
        WaitForSingleObject(processInfo_.hProcess, INFINITE);
        int errorcode = GetLastError();
        return errorcode;
    }

    #region IDisposable Members

    /// <summary>
    /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
    /// </summary>
    public void Dispose()
    {
    }

    #endregion

    private string processPath_ = string.Empty;
    private string processName_ = string.Empty;
    private string arguments_ = string.Empty;
    private PROCESS_INFORMATION processInfo_;

    /// <summary>
    /// Gets or sets the process path.
    /// </summary>
    /// <value>The process path.</value>
    public string ProcessPath
    {
        get
        {
            return processPath_;
        }
        set
        {
            processPath_ = value;
        }
    }

    /// <summary>
    /// Gets or sets the name of the process.
    /// </summary>
    /// <value>The name of the process.</value>
    public string ProcessName
    {
        get
        {
            return processName_;
        }
        set
        {
            processName_ = value;
        }
    }

    /// <summary>
    /// Gets or sets the arguments.
    /// </summary>
    /// <value>The arguments.</value>
    public string Arguments
    {
        get
        {
            return arguments_;
        }
        set
        {
            arguments_ = value;
        }
    }
}

Now, my function look like:

private void PrintFormPdfData(byte[] formPdfData)
{
    string tempFile;

    tempFile = Path.GetTempFileName();

    using (FileStream fs = new FileStream(tempFile, FileMode.Create))
    {
        fs.Write(formPdfData, 0, formPdfData.Length);
        fs.Flush();
    }
    string pdfArguments =string.Format("/t /o {0} \"Printer name\"", tempFile);

    string pdfPrinterLocation = @"C:\Program Files (x86)\Adobe\Reader 9.0\Reader\AcroRd32.exe";

    try
    {
        ProcessStarter processStarter = new ProcessStarter("AcroRd32", pdfPrinterLocation, pdfArguments);
        processStarter.Run();
        processStarter.WaitForExit();
        processStarter.Stop();
    }
    finally
    {
        File.Delete(tempFile);
    }
}

Also, ServiceProcessInstaller must have `Account set to "LocalSystem". When I created service I set to "Local service" with this user it does not work. I did not try with "Network service" or "User".


问:
Aframe Three.js Javascript caching images
I'm sharing a bunch of images between a React layer and an AFRAME VR layer.

I've preloaded the images into  in an assets entity (not using the aframe asset manager as these assets are loaded dynamically at run time)

i.e.

```<code>    const asset = getAsset(state, assetId, thumbnail)
    const image = new Image()
    image.id = assetId
    image.src= asset.url
    document.getElementById('assets').appendChild(image)
</code>```

When switching too VR, I'm trying to use the same assets to load the thumbnails

i.e.

```<code> const thumb = document.getElementById(assetId)
 this.el.setAttribute('src', thumb.src)
</code>```

However the browser is reloading the assets.

In this comment https://stackoverflow.com/a/44868733/2884250

Loading images as img in AFrame doesn't store them in THREE.Cache
  therefore the image was loaded twice. But if you load the image as
  a-asset-item it does.

So I've attempted to add the files to the THREE.Cache (I'm assuming as a src)

```<code> window.THREE.Cache.add(assetId, asset.url)
</code>```

How then in AFRAME do I get this image into the AFRAME A-IMAGE Entity as a src?

答:
Figured it out..

Add the image to the cache with the ID

```<code> image.onload = () =>  window.THREE.Cache.add(assetId, image)
</code>```

And use the ID as the SRC

```<code>this.el.setAttribute('src', '#'+assetId)
</code>```

Body:
I'm sharing a bunch of images between a React layer and an AFRAME VR layer.

I've preloaded the images into  in an assets entity (not using the aframe asset manager as these assets are loaded dynamically at run time)

i.e.

    const asset = getAsset(state, assetId, thumbnail)
    const image = new Image()
    image.id = assetId
    image.src= asset.url
    document.getElementById('assets').appendChild(image)

When switching too VR, I'm trying to use the same assets to load the thumbnails

i.e.

 const thumb = document.getElementById(assetId)
 this.el.setAttribute('src', thumb.src)

However the browser is reloading the assets.

In this comment https://stackoverflow.com/a/44868733/2884250

Loading images as img in AFrame doesn't store them in THREE.Cache
  therefore the image was loaded twice. But if you load the image as
  a-asset-item it does.

So I've attempted to add the files to the THREE.Cache (I'm assuming as a src)

 window.THREE.Cache.add(assetId, asset.url)

How then in AFRAME do I get this image into the AFRAME A-IMAGE Entity as a src?

Body:
Figured it out..

Add the image to the cache with the ID

 image.onload = () =>  window.THREE.Cache.add(assetId, image)

And use the ID as the SRC

this.el.setAttribute('src', '#'+assetId)


问:
How to read CSV file into 2d array of struct with each element having a determining character (C, G, M) to sort into the struct?
I am trying to create a 2d map of array using the csv input

```<code>   5,4
   ,,,C 200
   ,G Vibranium Shield:hands:990,,C 50
   M Healing Potion:85,,M Defence Enchanment:360,
   ,,,
   ,,G Lighsaber:hands:850,5,4
</code>```

The first row is the size of the array given.

The problem I am having right now is how to still count the empty list in the csv as a row and column in the array such as ",,,". Plus, how to read the determining character (C, G, M) in order to store the element in the struct. Example, G Vibranium Shield:hands:990, G will be the determining character stored in char type which then i use the switch case to store other element into the appropriate struct.

I tried to use fgets() strtok() but I can't read separately the determining element from other element in the CSV. As from other example it seem it need prior knowledge into which element will be in the line and predetermine the read line and not based on the determining character in the CSV. Thus I used fscanf to read:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct map
{
char types;
char geartypes[100];
int coins;
int values;
char items[100];
}map;

struct map **m;

int main()
{
    FILE* mapz;
    int i,j,h;
    int width,height;
    char a;
    mapz=fopen("map.csv","r");

    if(mapz!=NULL)
    {
        fscanf(mapz,"%d,%d",&height,&width);
        map **m=(map **)malloc(height * sizeof(map *));
        for(i=0;i<height;i++)
        {
            m[i]=(map*)malloc(width * sizeof(map));
        }
        for(h=0;h<height;h++)
        {
            for(j=0;j<width;j++)
            {
                fscanf(mapz,"%c",&a);
                switch(a)
                {
                case('C'):
                    m[h][j].types=a;
                    fscanf(mapz,"%d",&m[h][j].coins);
                    break;
                case('G'):
                    m[h][j].types=a;
                    fscanf(mapz,"%[^,:]s",m[h][j].items);
                    fscanf(mapz,"%[^,:]s",m[h][j].geartypes);
                    fscanf(mapz,"%d",&m[h][j].values);
                    break;
                case('M'):
                    m[h][j].types=a;
                    fscanf(mapz,"%[^,:]s",m[h][j].items);
                    fscanf(mapz,"%d",&m[h][j].values);
                    break;
                }

            }
        }
        for(h=0;h<height;h++)
        {
            for(j=0;j<width;j++)
            {
                switch(m[h][j].types)
                {
                case('C'):
                    printf("%c",m[h][j].types);
                    printf("%d\n",m[h][j].coins);
                    break;
                case('G'):
                    printf("%c",m[h][j].types);
                    printf("%s%s%d\n",m[h][j].items,m[h][j].geartypes,m[h][j].values);
                    break;
                case('M'):
                    printf("%c",m[h][j].types);
                    printf("%s%d\n",m[h][j].items,m[h][j].values);
                    break;
                }
            }
        }
    }
    else
    {
        printf("No such file in directory");
    }
    fclose(mapz);
    return 0;
</code>```

I tried to use fscanf but it seem to also read the "," which messed up the for count. When i ran the code it come out blank.

答:
While I have no qualms with David C. Rankin's answer, here's a different approach that uses regular expressions:

```<code>#include <assert.h>
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <sys/types.h>
#include <regex.h>

char line[4096];

int main( int argc, char *argv[] ) {
  if( !argv[1] )
    errx(EXIT_FAILURE, "missing input");

  FILE *input = fopen(argv[1], "r");
  if( !input  )
    err(EXIT_FAILURE, "could not open %s", argv[1]);

  if( NULL == fgets(line, sizeof(line), input) )
    err(EXIT_FAILURE, "could not read %s", argv[1]);

  int nr, nf, nfield;
  if( 2 != sscanf(line, "%d,%d", &nr, &nfield) )
    err(EXIT_FAILURE, "failed to parse first line");
  printf( "reading %d lines of %d fields each\n", nr, nfield );

  int erc;
  regex_t reg;
  const char fmt[] = "([^,\n]*)[,\n]";
  char *regex = calloc( nfield, 1 + strlen(fmt) );
  for( int i=0; i < nfield; i++ ) {
    strcat(regex, fmt);
  }

  int cflags = REG_EXTENDED;
  char errbuf[128];
  size_t len = sizeof(errbuf);
  const char *truncated = "";

  if( (erc = regcomp(&reg, regex, cflags)) != 0 ) {
    if( (len = regerror(erc, &reg, errbuf, len)) > sizeof(errbuf) )
      truncated = "(truncated)";
    errx(EXIT_FAILURE, "%s %s", errbuf, truncated);
  }

  for( int i=0; i < nr && NULL != fgets(line, sizeof(line), input); i++ ) {
    regmatch_t matches[1 + nfield];
    const int eflags = 0;

    printf("%s", line);

    if( (erc = regexec(&reg, line, 1 + nfield, matches, eflags)) != 0 ) {
      if( (len = regerror(erc, &reg, errbuf, len)) > sizeof(errbuf) )
        truncated = "(truncated)";
      errx(EXIT_FAILURE, "regex error: %s %s", errbuf, truncated);
    }

    for( nf=1; nf < nfield + 1 && matches[nf].rm_so != -1; nf++ ) {
      assert(matches[nf].rm_so <= matches[nf].rm_eo);
      printf( "%4d: '%.*s'\n",
          nf,
          (int)(matches[nf].rm_eo - matches[nf].rm_so),
          line + matches[nf].rm_so );
    }
  }

  return EXIT_SUCCESS;
}
</code>```

It's only a little longer (mostly to handle errors).  What I like is that once regexec(3) is called, the fields are all set up in the matches array.

Body:
I am trying to create a 2d map of array using the csv input

   5,4
   ,,,C 200
   ,G Vibranium Shield:hands:990,,C 50
   M Healing Potion:85,,M Defence Enchanment:360,
   ,,,
   ,,G Lighsaber:hands:850,5,4

The first row is the size of the array given.

The problem I am having right now is how to still count the empty list in the csv as a row and column in the array such as ",,,". Plus, how to read the determining character (C, G, M) in order to store the element in the struct. Example, G Vibranium Shield:hands:990, G will be the determining character stored in char type which then i use the switch case to store other element into the appropriate struct.

I tried to use fgets() strtok() but I can't read separately the determining element from other element in the CSV. As from other example it seem it need prior knowledge into which element will be in the line and predetermine the read line and not based on the determining character in the CSV. Thus I used fscanf to read:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct map
{
char types;
char geartypes[100];
int coins;
int values;
char items[100];
}map;

struct map **m;

int main()
{
    FILE* mapz;
    int i,j,h;
    int width,height;
    char a;
    mapz=fopen("map.csv","r");

    if(mapz!=NULL)
    {
        fscanf(mapz,"%d,%d",&height,&width);
        map **m=(map **)malloc(height * sizeof(map *));
        for(i=0;i<height;i++)
        {
            m[i]=(map*)malloc(width * sizeof(map));
        }
        for(h=0;h<height;h++)
        {
            for(j=0;j<width;j++)
            {
                fscanf(mapz,"%c",&a);
                switch(a)
                {
                case('C'):
                    m[h][j].types=a;
                    fscanf(mapz,"%d",&m[h][j].coins);
                    break;
                case('G'):
                    m[h][j].types=a;
                    fscanf(mapz,"%[^,:]s",m[h][j].items);
                    fscanf(mapz,"%[^,:]s",m[h][j].geartypes);
                    fscanf(mapz,"%d",&m[h][j].values);
                    break;
                case('M'):
                    m[h][j].types=a;
                    fscanf(mapz,"%[^,:]s",m[h][j].items);
                    fscanf(mapz,"%d",&m[h][j].values);
                    break;
                }

            }
        }
        for(h=0;h<height;h++)
        {
            for(j=0;j<width;j++)
            {
                switch(m[h][j].types)
                {
                case('C'):
                    printf("%c",m[h][j].types);
                    printf("%d\n",m[h][j].coins);
                    break;
                case('G'):
                    printf("%c",m[h][j].types);
                    printf("%s%s%d\n",m[h][j].items,m[h][j].geartypes,m[h][j].values);
                    break;
                case('M'):
                    printf("%c",m[h][j].types);
                    printf("%s%d\n",m[h][j].items,m[h][j].values);
                    break;
                }
            }
        }
    }
    else
    {
        printf("No such file in directory");
    }
    fclose(mapz);
    return 0;

I tried to use fscanf but it seem to also read the "," which messed up the for count. When i ran the code it come out blank.

Body:
While I have no qualms with David C. Rankin's answer, here's a different approach that uses regular expressions:

#include <assert.h>
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <sys/types.h>
#include <regex.h>

char line[4096];

int main( int argc, char *argv[] ) {
  if( !argv[1] )
    errx(EXIT_FAILURE, "missing input");

  FILE *input = fopen(argv[1], "r");
  if( !input  )
    err(EXIT_FAILURE, "could not open %s", argv[1]);

  if( NULL == fgets(line, sizeof(line), input) )
    err(EXIT_FAILURE, "could not read %s", argv[1]);

  int nr, nf, nfield;
  if( 2 != sscanf(line, "%d,%d", &nr, &nfield) )
    err(EXIT_FAILURE, "failed to parse first line");
  printf( "reading %d lines of %d fields each\n", nr, nfield );

  int erc;
  regex_t reg;
  const char fmt[] = "([^,\n]*)[,\n]";
  char *regex = calloc( nfield, 1 + strlen(fmt) );
  for( int i=0; i < nfield; i++ ) {
    strcat(regex, fmt);
  }

  int cflags = REG_EXTENDED;
  char errbuf[128];
  size_t len = sizeof(errbuf);
  const char *truncated = "";

  if( (erc = regcomp(&reg, regex, cflags)) != 0 ) {
    if( (len = regerror(erc, &reg, errbuf, len)) > sizeof(errbuf) )
      truncated = "(truncated)";
    errx(EXIT_FAILURE, "%s %s", errbuf, truncated);
  }

  for( int i=0; i < nr && NULL != fgets(line, sizeof(line), input); i++ ) {
    regmatch_t matches[1 + nfield];
    const int eflags = 0;

    printf("%s", line);

    if( (erc = regexec(&reg, line, 1 + nfield, matches, eflags)) != 0 ) {
      if( (len = regerror(erc, &reg, errbuf, len)) > sizeof(errbuf) )
        truncated = "(truncated)";
      errx(EXIT_FAILURE, "regex error: %s %s", errbuf, truncated);
    }

    for( nf=1; nf < nfield + 1 && matches[nf].rm_so != -1; nf++ ) {
      assert(matches[nf].rm_so <= matches[nf].rm_eo);
      printf( "%4d: '%.*s'\n",
          nf,
          (int)(matches[nf].rm_eo - matches[nf].rm_so),
          line + matches[nf].rm_so );
    }
  }

  return EXIT_SUCCESS;
}

It's only a little longer (mostly to handle errors).  What I like is that once regexec(3) is called, the fields are all set up in the matches array.


问:
Revoked permission android.permission.CALL_PHONE
I'm trying to programmatically call to a number with following code:

```<code> String number = ("tel:" + numTxt.getText());
 Intent intent = new Intent(Intent.ACTION_CALL);
 intent.setData(Uri.parse(number));
 startActivity(intent);
</code>```

I've set the permission in the Manifest:

```<code><uses-permission android:name="android.permission.CALL_PHONE"/>
</code>```

I'm working with real device for testing and debugging, it is Nexus 5 with Android M, my compileSdkVersion is 23. I'm getting the following Security Exception:

```<code>error: Permission Denial: starting Intent { act=android.intent.action.CALL dat=tel:xxxxxxxxxx cmp=com.android.server.telecom/.components.UserCallActivity } from ProcessRecord{cbbd7c1 5228:com.dialerTest.DialerApp/u0a96} (pid=5228, uid=10096) with revoked permission android.permission.CALL_PHONE
</code>```

I've searched the web and this community for similar Q/A and couldn't find the answer. Any help will be appreciated.

答:
in fragment class

Step 1:
import static android.Manifest.permission.CALL_PHONE;

step 2:Where your onclick button:

```<code>            Intent callIntent = new Intent(Intent.ACTION_CALL);
            callIntent.setData(Uri.parse("tel:" +driver_no ));

            if (ContextCompat.checkSelfPermission(getActivity(), CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
                startActivity(callIntent);
            } else {
                requestPermissions(new String[]{CALL_PHONE}, 1);
            }
</code>```

[Or] you are using in activity class means change the getActivity to getApplicationContext()

Body:
I'm trying to programmatically call to a number with following code:

 String number = ("tel:" + numTxt.getText());
 Intent intent = new Intent(Intent.ACTION_CALL);
 intent.setData(Uri.parse(number));
 startActivity(intent);

I've set the permission in the Manifest:

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

I'm working with real device for testing and debugging, it is Nexus 5 with Android M, my compileSdkVersion is 23. I'm getting the following Security Exception:

error: Permission Denial: starting Intent { act=android.intent.action.CALL dat=tel:xxxxxxxxxx cmp=com.android.server.telecom/.components.UserCallActivity } from ProcessRecord{cbbd7c1 5228:com.dialerTest.DialerApp/u0a96} (pid=5228, uid=10096) with revoked permission android.permission.CALL_PHONE

I've searched the web and this community for similar Q/A and couldn't find the answer. Any help will be appreciated.

Body:
in fragment class

Step 1:
import static android.Manifest.permission.CALL_PHONE;

step 2:Where your onclick button:

            Intent callIntent = new Intent(Intent.ACTION_CALL);
            callIntent.setData(Uri.parse("tel:" +driver_no ));

            if (ContextCompat.checkSelfPermission(getActivity(), CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
                startActivity(callIntent);
            } else {
                requestPermissions(new String[]{CALL_PHONE}, 1);
            }

[Or] you are using in activity class means change the getActivity to getApplicationContext()


问:
Connecting to Exchange Online with PowerShell and Modern Authentication (without any dependencies)
I want to connect to Exchange Online using PowerShell and modern authentication without depending on any modules or dll's.

There's a module available for modern authentication to Exchange Online that depends on the CreateEXOPSSession.ps1 and Microsoft.Exchange.Management.ExoPowerShellModule.dll, I have decompiled the latter and found that it generates an access token as such:

```<code>TokenInformation accessToken = TokenProviderFactory.Instance.CreateTokenProvider(new TokenProviderContext(authType, "a0c73c16-a7e3-4564-9a95-2bdf47383716", this.AzureADAuthorizationEndpointUri, acquireTokenEndpoint, this.UserPrincipalName, this.Credential, clientAppRedirectUri, (Action<string>) (s => this.WriteWarning(s)))).GetAccessToken();
</code>```

I want to request the access token is the same way in PowerShell but I can't seem to get the right authentication context and method of retrieving the access token.

Any ideas?

答:
You have to have an MSOL connection and create a remote session to EXO to use EXO cmdlets. There is no workaround for this.

The dependencies are there for a reason. The backend plumbing of MSOL / Azure / O365 expects what it expects, and skirting it will just lead you down a very frustrating/hair-pulling activity.

That token is an Azure AD as MA/ADAL requires that you have an Azure AD Premium license.
MA requires use of the ADAL API/DLL. This is like asking to programmatically connect to and use Exchange on-prem EAS/EWS services without using the API/DLL, that's not a thing either.

So, no matter how you look at this, there will be dependencies, as noted below. So, if you are serious about this effort, you need to really dig into what MA really is and how it's plumbing really works. Also, MFA must be already enabled for you and users, either in O365 and or the ADAL MFA settings in Azure.

Modern Authentication – What is it?
Modern Authentication brings Active Directory Authentication Library (ADAL)-based sign-in to Office client apps across platforms.

Microsoft identity platform authentication libraries

There is also an ADAL module on the MS PowerShellGallery.com.

Microsoft.ADAL.PowerShell 1.12
ADAL module for PowerShell
https://www.powershellgallery.com/packages/Microsoft.ADAL.PowerShell/1.12

Functions
Get-ADALAccessToken Clear-ADALAccessTokenCache

Examples are here:

```<code>Microsoft.ADAL.Powershell ```
####Example 1 This example acquire accesstoken by using RedirectUri from contoso.onmicrosoft.com Azure Active Directory for PowerBI
service. It will only prompt you to sign in for the first time, or
when cache is expired.
```
</blockquote>

```Get-ADALAccessToken -AuthorityName contoso.onmicrosoft.com `
-ClientId 8f710b23-d3ea-4dd3-8a0e-c5958a6bc16d `
-ResourceId https://analysis.windows.net/powerbi/api `
-RedirectUri "http://yourredirecturi.local"
```

See also:
Azure-AD-Authentication-with-PowerShell-and-ADAL

This is a set of really simple PowerShell scripts which allow you to get access tokens with Azure Active Directory using ADAL.

and this...
ADAL and PowerShell

Body:
I want to connect to Exchange Online using PowerShell and modern authentication without depending on any modules or dll's.

There's a module available for modern authentication to Exchange Online that depends on the CreateEXOPSSession.ps1 and Microsoft.Exchange.Management.ExoPowerShellModule.dll, I have decompiled the latter and found that it generates an access token as such:

TokenInformation accessToken = TokenProviderFactory.Instance.CreateTokenProvider(new TokenProviderContext(authType, "a0c73c16-a7e3-4564-9a95-2bdf47383716", this.AzureADAuthorizationEndpointUri, acquireTokenEndpoint, this.UserPrincipalName, this.Credential, clientAppRedirectUri, (Action<string>) (s => this.WriteWarning(s)))).GetAccessToken();

I want to request the access token is the same way in PowerShell but I can't seem to get the right authentication context and method of retrieving the access token.

Any ideas?

Body:
You have to have an MSOL connection and create a remote session to EXO to use EXO cmdlets. There is no workaround for this.

The dependencies are there for a reason. The backend plumbing of MSOL / Azure / O365 expects what it expects, and skirting it will just lead you down a very frustrating/hair-pulling activity.

That token is an Azure AD as MA/ADAL requires that you have an Azure AD Premium license.
MA requires use of the ADAL API/DLL. This is like asking to programmatically connect to and use Exchange on-prem EAS/EWS services without using the API/DLL, that's not a thing either.

So, no matter how you look at this, there will be dependencies, as noted below. So, if you are serious about this effort, you need to really dig into what MA really is and how it's plumbing really works. Also, MFA must be already enabled for you and users, either in O365 and or the ADAL MFA settings in Azure.

Modern Authentication – What is it?
Modern Authentication brings Active Directory Authentication Library (ADAL)-based sign-in to Office client apps across platforms.

Microsoft identity platform authentication libraries

There is also an ADAL module on the MS PowerShellGallery.com.

Microsoft.ADAL.PowerShell 1.12
ADAL module for PowerShell
https://www.powershellgallery.com/packages/Microsoft.ADAL.PowerShell/1.12

Functions
Get-ADALAccessToken Clear-ADALAccessTokenCache

Examples are here:

Microsoft.ADAL.Powershell ```
####Example 1 This example acquire accesstoken by using RedirectUri from contoso.onmicrosoft.com Azure Active Directory for PowerBI
service. It will only prompt you to sign in for the first time, or
when cache is expired.

Get-ADALAccessToken -AuthorityName contoso.onmicrosoft.com `
-ClientId 8f710b23-d3ea-4dd3-8a0e-c5958a6bc16d `
-ResourceId https://analysis.windows.net/powerbi/api `
-RedirectUri "http://yourredirecturi.local"

See also:
Azure-AD-Authentication-with-PowerShell-and-ADAL

This is a set of really simple PowerShell scripts which allow you to get access tokens with Azure Active Directory using ADAL.

and this...
ADAL and PowerShell