问:
Trying to merge two shaders (double sided and cross section) but getting syntax error
I am trying to "merge" the code of two shaders:

The first one is a double sided shader for Hololens from the Microsoft Holotoolkit:

```<code>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

Shader "MixedRealityToolkit/Obsolete/Fast Configurable 2 Sided"
{
    Properties
    {
        _Mode("Rendering Mode", Float) = 0.0

        [Toggle] _UseVertexColor("Vertex Color Enabled?", Float) = 0
        [Toggle] _UseMainColor("Main Color Enabled?", Float) = 0
        _Color("Main Color", Color) = (1,1,1,1)
        [Toggle] _UseMainTex("Main Texture Enabled?", Float) = 0
        [NoScaleOffset]_MainTex("Main Texture", 2D) = "red" {}

        [Toggle] _UseOcclusionMap("Occlusion/Detail Texture Enabled?", Float) = 0
        [NoScaleOffset]_OcclusionMap("Occlusion/Detail Texture", 2D) = "blue" {}

        [Toggle] _UseAmbient("Ambient Lighting Enabled?", Float) = 1
        [Toggle] _UseDiffuse("Diffuse Lighting Enabled?", Float) = 1

        [Toggle] _SpecularHighlights("Specular Lighting Enabled?", Float) = 0
        [Toggle] _Shade4("Use additional lighting data? (Expensive!)", Float) = 0

        [Toggle] _ForcePerPixel("Light per-pixel (always on if a map is set)", Float) = 0

        _SpecColor("Specular Color", Color) = (0.5, 0.5, 0.5, 1)
        [PowerSlider(5.0)]_Specular("Specular (Specular Power)", Range(1.0, 100.0)) = 10.0
        [Toggle] _UseSpecularMap("Use Specular Map? (per-pixel)", Float) = 0
        [NoScaleOffset]_SpecularMap("Specular Map", 2D) = "white" {}

        _Gloss("Gloss (Specular Scale)", Range(0.1, 10.0)) = 1.0
        [Toggle] _UseGlossMap("Use Gloss Map? (per-pixel)", Float) = 0
        [NoScaleOffset]_GlossMap("Gloss Map", 2D) = "white" {}

        [Toggle] _UseBumpMap("Normal Map Enabled? (per-pixel)", Float) = 0
        [NoScaleOffset][Normal] _BumpMap("Normal Map", 2D) = "bump" {}

        [Toggle] _UseReflections("Reflections Enabled?", Float) = 0
        [NoScaleOffset]_CubeMap("CubeMap", Cube) = "" {}
        _ReflectionScale("Reflection Scale", Range(0.01, 3.0)) = 2.0
        [Toggle]_CalibrationSpaceReflections("Reflect in calibration space?", Float) = 0

        [Toggle] _UseRimLighting("Rim Lighting Enabled?", Float) = 0
        [PowerSlider(.6)]_RimPower("Power", Range(0.1, 1.0)) = 0.7
        _RimColor("Color", Color) = (1,1,1,1)

        [Toggle] _UseEmissionColor("Emission Color Enabled?", Float) = 0
        _EmissionColor("Emission Color", Color) = (1,1,1,1)
        [Toggle] _UseEmissionMap("Emission Map Enabled?", Float) = 0
        [NoScaleOffset] _EmissionMap("Emission Map", 2D) = "blue" {}

        _TextureScaleOffset("Texture Scale (XY) and Offset (ZW)", Vector) = (1, 1, 0, 0)

        [Enum(UnityEngine.Rendering.BlendMode)] _SrcBlend("SrcBlend", Float) = 1 //"One"
        [Enum(UnityEngine.Rendering.BlendMode)] _DstBlend("DestBlend", Float) = 0 //"Zero"
        [Enum(UnityEngine.Rendering.BlendOp)] _BlendOp("BlendOp", Float) = 0 //"Add"

        [Toggle] _AlphaTest("Alpha test enabled?", Float) = 0
        _Cutoff("Alpha Cutoff", Range(-0.1, 1.0)) = -0.1

        [Enum(UnityEngine.Rendering.CompareFunction)] _ZTest("ZTest", Float) = 4 //"LessEqual"
        [Enum(Off,0,On,1)] _ZWrite("ZWrite", Float) = 1 //"On"
        [Enum(UnityEngine.Rendering.ColorWriteMask)] _ColorWriteMask("ColorWriteMask", Float) = 15 //"All"
    }

    SubShader
    {
        Tags { "RenderType"="Opaque" "PerformanceChecks"="False" }
        LOD 100
        Blend[_SrcBlend][_DstBlend]
        BlendOp[_BlendOp]
        ZTest[_ZTest]
        ZWrite[_ZWrite]

        Pass
        {
            Name "FRONT"
            Tags { "LightMode" = "ForwardBase" }
            Cull Back
            ColorMask[_ColorWriteMask]

            CGPROGRAM
                #pragma vertex vert
                #pragma fragment frag

                //compiles all variants needed by ForwardBase (forward rendering base) pass type. The variants deal with different lightmap types and main directional light having shadows on or off.
                #pragma multi_compile_fwdbase

                //expands to several variants to handle different fog types
                #pragma multi_compile_fog

                //We only target the HoloLens (and the Unity editor), so take advantage of shader model 5.
                #pragma target 5.0
                #pragma only_renderers d3d11

                //shader features are only compiled if a material uses them
                #pragma shader_feature _USEVERTEXCOLOR_ON
                #pragma shader_feature _USEMAINCOLOR_ON
                #pragma shader_feature _USEMAINTEX_ON
                #pragma shader_feature _USESOCCLUSIONMAP_ON
                #pragma shader_feature _USEBUMPMAP_ON
                #pragma shader_feature _USEAMBIENT_ON
                #pragma shader_feature _USEDIFFUSE_ON
                #pragma shader_feature _USESPECULAR_ON
                #pragma shader_feature _USEGLOSSMAP_ON
                #pragma shader_feature _SHADE4_ON
                #pragma shader_feature _USEREFLECTIONS_ON
                #pragma shader_feature _USERIMLIGHTING_ON
                #pragma shader_feature _USEEMISSIONCOLOR_ON
                #pragma shader_feature _USEEMISSIONTEX_ON
                #pragma shader_feature _ALPHATEST_ON

                //scale and offset will apply to all
                #pragma shader_feature _MainTex_SCALE_ON
                #pragma shader_feature _MainTex_OFFSET_ON

                //may be set from script so generate both paths
                #pragma multi_compile __ _NEAR_PLANE_FADE_ON

                #include "FastConfigurable.cginc"
            ENDCG
        }

        Pass
        {
            Name "BACK"
            Tags{ "LightMode" = "ForwardBase" }
            Cull Front
            ColorMask[_ColorWriteMask]

            CGPROGRAM
                #pragma vertex vert
                #pragma fragment frag

                //compiles all variants needed by ForwardBase (forward rendering base) pass type. The variants deal with different lightmap types and main directional light having shadows on or off.
                #pragma multi_compile_fwdbase

                //expands to several variants to handle different fog types
                #pragma multi_compile_fog

                //We only target the HoloLens (and the Unity editor), so take advantage of shader model 5.
                #pragma target 5.0
                #pragma only_renderers d3d11

                //shader features are only compiled if a material uses them
                #pragma shader_feature _USEMAINCOLOR_ON
                #pragma shader_feature _USEMAINTEX_ON
                #pragma shader_feature _USESOCCLUSIONMAP_ON
                #pragma shader_feature _USEBUMPMAP_ON
                #pragma shader_feature _USEAMBIENT_ON
                #pragma shader_feature _USEDIFFUSE_ON
                #pragma shader_feature _USESPECULAR_ON
                #pragma shader_feature _USEGLOSSMAP_ON
                #pragma shader_feature _SHADE4_ON
                #pragma shader_feature _USEEMISSIONCOLOR_ON
                #pragma shader_feature _USEEMISSIONTEX_ON

                //scale and offset will apply to all
                #pragma shader_feature _MainTex_SCALE_ON
                #pragma shader_feature _MainTex_OFFSET_ON

                //may be set from script so generate both paths
                #pragma multi_compile __ _NEAR_PLANE_FADE_ON

                #define FLIP_NORMALS 1
                #include "FastConfigurable.cginc"
            ENDCG
        }
    }

    CustomEditor "HoloToolkit.Unity.FastConfigurable2SidedGUI"
    Fallback "VertexLit" //for shadows
}
</code>```

The second one is a cross section shader from the Unity asset store:

```<code>Shader "CrossSection/OnePlaneBSP" {
    Properties{
        _Color("Color", Color) = (1,1,1,1)
        _CrossColor("Cross Section Color", Color) = (1,1,1,1)
        _MainTex("Albedo (RGB)", 2D) = "white" {}
        _Glossiness("Smoothness", Range(0,1)) = 0.5
        _Metallic("Metallic", Range(0,1)) = 0.0
        _PlaneNormal("PlaneNormal",Vector) = (0,1,0,0)
        _PlanePosition("PlanePosition",Vector) = (0,0,0,1)
        _StencilMask("Stencil Mask", Range(0, 255)) = 255
    }
    SubShader {
        Tags { "RenderType"="Opaque" }
        //LOD 200
        Stencil
        {
            Ref [_StencilMask]
            CompBack Always
            PassBack Replace

            CompFront Always
            PassFront Zero
        }
        Cull Back
            CGPROGRAM
            // Physically based Standard lighting model, and enable shadows on all light types
#pragma surface surf Standard fullforwardshadows

            // Use shader model 3.0 target, to get nicer looking lighting
#pragma target 3.0

            sampler2D _MainTex;

        struct Input {
            float2 uv_MainTex;

            float3 worldPos;
        };

        half _Glossiness;
        half _Metallic;
        fixed4 _Color;
        fixed4 _CrossColor;
        fixed3 _PlaneNormal;
        fixed3 _PlanePosition;
        bool checkVisability(fixed3 worldPos)
        {
            float dotProd1 = dot(worldPos - _PlanePosition, _PlaneNormal);
            return dotProd1 > 0  ;
        }
        void surf(Input IN, inout SurfaceOutputStandard o) {
            if (checkVisability(IN.worldPos))discard;
            fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color;
            o.Albedo = c.rgb;
            // Metallic and smoothness come from slider variables
            o.Metallic = _Metallic;
            o.Smoothness = _Glossiness;
            o.Alpha = c.a;
        }
        ENDCG

            Cull Front
            CGPROGRAM
#pragma surface surf NoLighting  noambient

        struct Input {
            half2 uv_MainTex;
            float3 worldPos;

        };
        sampler2D _MainTex;
        fixed4 _Color;
        fixed4 _CrossColor;
        fixed3 _PlaneNormal;
        fixed3 _PlanePosition;
        bool checkVisability(fixed3 worldPos)
        {
            float dotProd1 = dot(worldPos - _PlanePosition, _PlaneNormal);
            return dotProd1 >0 ;
        }
        fixed4 LightingNoLighting(SurfaceOutput s, fixed3 lightDir, fixed atten)
        {
            fixed4 c;
            c.rgb = s.Albedo;
            c.a = s.Alpha;
            return c;
        }

        void surf(Input IN, inout SurfaceOutput o)
        {
            if (checkVisability(IN.worldPos))discard;
            o.Albedo = _CrossColor;

        }
            ENDCG

    }
    //FallBack "Diffuse"
}
</code>```

I tried to start from the double sided shader and add pragma surf surface from the second one at the end of the first PASS like this:

```<code>...
//End of the first PASS from the first shader

        #include "FastConfigurable.cginc"

#pragma surface surf NoLighting  noambient

        struct Input {
            half2 uv_MainTex;
            float3 worldPos;

        };
        fixed4 _CrossColor;
        fixed3 _PlaneNormal;
        fixed3 _PlanePosition;
        bool checkVisability(fixed3 worldPos)
        {
            float dotProd1 = dot(worldPos - _PlanePosition, _PlaneNormal);
            return dotProd1 > 0;
        }
        fixed4 LightingNoLighting(SurfaceOutput s, fixed3 lightDir, fixed atten)
        {
            fixed4 c;
            c.rgb = s.Albedo;
            c.a = s.Alpha;
            return c;
        }

        void surf(Input IN, inout SurfaceOutput o)
        {
            if (checkVisability(IN.worldPos))discard;
            o.Albedo = _CrossColor;

        }
            ENDCG
        }

        Pass
        {
            Name "BACK"
            Tags{ "LightMode" = "ForwardBase" }
            Cull Front
            ColorMask[_ColorWriteMask]

            CGPROGRAM
//Next of the second PASS of the first shader
...
</code>```

But I am getting the following errors:

Shader Compiler Socket Exception: Terminating shader compiler process

Shader compiler: Preprocess DoubleSidedStandardCrossCut.shader:
  Internal error communicating with the shader compiler process.  Please
  report a bug including this shader and the editor log.

Shader error in 'DoubleSidedStandardCrossCut': Parse error: syntax
  error, unexpected $end, expecting TOK_SHADER at line 1

If you have any tip or suggestion, I would really appreciate, thank you!

答:
As often, this boils down to what you want to achieve, and understanding which part of which shader does what you want in your final outcome.

This is not very clear, and I can only make assumptions. It seems you have a given mesh; you wish that it can be (1) carved out based on a Plane, given its position and normal; and want (2) front-facing (F) and back-facing (B) surfaces to have different rendering properties.

Writing multi-pass shaders is often just a shorthand for something you can do with just setup, albeit maybe with a little bit more overhead: Each pass is essentially another draw call, it could just as well be another object.

Options:

Write a multi-pass shader

Have 2 objects nested in a common transform, or have either object F or B nested into the other one.

Provided your mesh doesn't have sub-meshes, assign 2 materials into the MeshRenderer component. This list is usually assigning different materials to each sub-mesh, but if none is present it will just draw the Mesh again.

In either case 2 and 3, you need 2 materials. They could both use the same shader, or for simplicity you could first author 2 shaders with baked-in properties:

Material B(ack) has a lower render queue (maybe Geometry-1) since it always needs to be covered up by F(ront). (see https://docs.unity3d.com/Manual/SL-SubShaderTags.html)

Material B uses the Cull Front flag, and material F uses the Cull Back flag (the default one)

Both of them uses checkVisibility(IN.worldPos) to discard pixels that are carved out.

On a side note: this needs to be fast since you seem to do VR, so I'd advocate to use the clip() hlsl instruction and have checkVisibility to return a float, to get rid of the conditional branching entirely.

Body:
I am trying to "merge" the code of two shaders:

The first one is a double sided shader for Hololens from the Microsoft Holotoolkit:

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

Shader "MixedRealityToolkit/Obsolete/Fast Configurable 2 Sided"
{
    Properties
    {
        _Mode("Rendering Mode", Float) = 0.0

        [Toggle] _UseVertexColor("Vertex Color Enabled?", Float) = 0
        [Toggle] _UseMainColor("Main Color Enabled?", Float) = 0
        _Color("Main Color", Color) = (1,1,1,1)
        [Toggle] _UseMainTex("Main Texture Enabled?", Float) = 0
        [NoScaleOffset]_MainTex("Main Texture", 2D) = "red" {}

        [Toggle] _UseOcclusionMap("Occlusion/Detail Texture Enabled?", Float) = 0
        [NoScaleOffset]_OcclusionMap("Occlusion/Detail Texture", 2D) = "blue" {}

        [Toggle] _UseAmbient("Ambient Lighting Enabled?", Float) = 1
        [Toggle] _UseDiffuse("Diffuse Lighting Enabled?", Float) = 1

        [Toggle] _SpecularHighlights("Specular Lighting Enabled?", Float) = 0
        [Toggle] _Shade4("Use additional lighting data? (Expensive!)", Float) = 0

        [Toggle] _ForcePerPixel("Light per-pixel (always on if a map is set)", Float) = 0

        _SpecColor("Specular Color", Color) = (0.5, 0.5, 0.5, 1)
        [PowerSlider(5.0)]_Specular("Specular (Specular Power)", Range(1.0, 100.0)) = 10.0
        [Toggle] _UseSpecularMap("Use Specular Map? (per-pixel)", Float) = 0
        [NoScaleOffset]_SpecularMap("Specular Map", 2D) = "white" {}

        _Gloss("Gloss (Specular Scale)", Range(0.1, 10.0)) = 1.0
        [Toggle] _UseGlossMap("Use Gloss Map? (per-pixel)", Float) = 0
        [NoScaleOffset]_GlossMap("Gloss Map", 2D) = "white" {}

        [Toggle] _UseBumpMap("Normal Map Enabled? (per-pixel)", Float) = 0
        [NoScaleOffset][Normal] _BumpMap("Normal Map", 2D) = "bump" {}

        [Toggle] _UseReflections("Reflections Enabled?", Float) = 0
        [NoScaleOffset]_CubeMap("CubeMap", Cube) = "" {}
        _ReflectionScale("Reflection Scale", Range(0.01, 3.0)) = 2.0
        [Toggle]_CalibrationSpaceReflections("Reflect in calibration space?", Float) = 0

        [Toggle] _UseRimLighting("Rim Lighting Enabled?", Float) = 0
        [PowerSlider(.6)]_RimPower("Power", Range(0.1, 1.0)) = 0.7
        _RimColor("Color", Color) = (1,1,1,1)

        [Toggle] _UseEmissionColor("Emission Color Enabled?", Float) = 0
        _EmissionColor("Emission Color", Color) = (1,1,1,1)
        [Toggle] _UseEmissionMap("Emission Map Enabled?", Float) = 0
        [NoScaleOffset] _EmissionMap("Emission Map", 2D) = "blue" {}

        _TextureScaleOffset("Texture Scale (XY) and Offset (ZW)", Vector) = (1, 1, 0, 0)

        [Enum(UnityEngine.Rendering.BlendMode)] _SrcBlend("SrcBlend", Float) = 1 //"One"
        [Enum(UnityEngine.Rendering.BlendMode)] _DstBlend("DestBlend", Float) = 0 //"Zero"
        [Enum(UnityEngine.Rendering.BlendOp)] _BlendOp("BlendOp", Float) = 0 //"Add"

        [Toggle] _AlphaTest("Alpha test enabled?", Float) = 0
        _Cutoff("Alpha Cutoff", Range(-0.1, 1.0)) = -0.1

        [Enum(UnityEngine.Rendering.CompareFunction)] _ZTest("ZTest", Float) = 4 //"LessEqual"
        [Enum(Off,0,On,1)] _ZWrite("ZWrite", Float) = 1 //"On"
        [Enum(UnityEngine.Rendering.ColorWriteMask)] _ColorWriteMask("ColorWriteMask", Float) = 15 //"All"
    }

    SubShader
    {
        Tags { "RenderType"="Opaque" "PerformanceChecks"="False" }
        LOD 100
        Blend[_SrcBlend][_DstBlend]
        BlendOp[_BlendOp]
        ZTest[_ZTest]
        ZWrite[_ZWrite]

        Pass
        {
            Name "FRONT"
            Tags { "LightMode" = "ForwardBase" }
            Cull Back
            ColorMask[_ColorWriteMask]

            CGPROGRAM
                #pragma vertex vert
                #pragma fragment frag

                //compiles all variants needed by ForwardBase (forward rendering base) pass type. The variants deal with different lightmap types and main directional light having shadows on or off.
                #pragma multi_compile_fwdbase

                //expands to several variants to handle different fog types
                #pragma multi_compile_fog

                //We only target the HoloLens (and the Unity editor), so take advantage of shader model 5.
                #pragma target 5.0
                #pragma only_renderers d3d11

                //shader features are only compiled if a material uses them
                #pragma shader_feature _USEVERTEXCOLOR_ON
                #pragma shader_feature _USEMAINCOLOR_ON
                #pragma shader_feature _USEMAINTEX_ON
                #pragma shader_feature _USESOCCLUSIONMAP_ON
                #pragma shader_feature _USEBUMPMAP_ON
                #pragma shader_feature _USEAMBIENT_ON
                #pragma shader_feature _USEDIFFUSE_ON
                #pragma shader_feature _USESPECULAR_ON
                #pragma shader_feature _USEGLOSSMAP_ON
                #pragma shader_feature _SHADE4_ON
                #pragma shader_feature _USEREFLECTIONS_ON
                #pragma shader_feature _USERIMLIGHTING_ON
                #pragma shader_feature _USEEMISSIONCOLOR_ON
                #pragma shader_feature _USEEMISSIONTEX_ON
                #pragma shader_feature _ALPHATEST_ON

                //scale and offset will apply to all
                #pragma shader_feature _MainTex_SCALE_ON
                #pragma shader_feature _MainTex_OFFSET_ON

                //may be set from script so generate both paths
                #pragma multi_compile __ _NEAR_PLANE_FADE_ON

                #include "FastConfigurable.cginc"
            ENDCG
        }

        Pass
        {
            Name "BACK"
            Tags{ "LightMode" = "ForwardBase" }
            Cull Front
            ColorMask[_ColorWriteMask]

            CGPROGRAM
                #pragma vertex vert
                #pragma fragment frag

                //compiles all variants needed by ForwardBase (forward rendering base) pass type. The variants deal with different lightmap types and main directional light having shadows on or off.
                #pragma multi_compile_fwdbase

                //expands to several variants to handle different fog types
                #pragma multi_compile_fog

                //We only target the HoloLens (and the Unity editor), so take advantage of shader model 5.
                #pragma target 5.0
                #pragma only_renderers d3d11

                //shader features are only compiled if a material uses them
                #pragma shader_feature _USEMAINCOLOR_ON
                #pragma shader_feature _USEMAINTEX_ON
                #pragma shader_feature _USESOCCLUSIONMAP_ON
                #pragma shader_feature _USEBUMPMAP_ON
                #pragma shader_feature _USEAMBIENT_ON
                #pragma shader_feature _USEDIFFUSE_ON
                #pragma shader_feature _USESPECULAR_ON
                #pragma shader_feature _USEGLOSSMAP_ON
                #pragma shader_feature _SHADE4_ON
                #pragma shader_feature _USEEMISSIONCOLOR_ON
                #pragma shader_feature _USEEMISSIONTEX_ON

                //scale and offset will apply to all
                #pragma shader_feature _MainTex_SCALE_ON
                #pragma shader_feature _MainTex_OFFSET_ON

                //may be set from script so generate both paths
                #pragma multi_compile __ _NEAR_PLANE_FADE_ON

                #define FLIP_NORMALS 1
                #include "FastConfigurable.cginc"
            ENDCG
        }
    }

    CustomEditor "HoloToolkit.Unity.FastConfigurable2SidedGUI"
    Fallback "VertexLit" //for shadows
}

The second one is a cross section shader from the Unity asset store:

Shader "CrossSection/OnePlaneBSP" {
    Properties{
        _Color("Color", Color) = (1,1,1,1)
        _CrossColor("Cross Section Color", Color) = (1,1,1,1)
        _MainTex("Albedo (RGB)", 2D) = "white" {}
        _Glossiness("Smoothness", Range(0,1)) = 0.5
        _Metallic("Metallic", Range(0,1)) = 0.0
        _PlaneNormal("PlaneNormal",Vector) = (0,1,0,0)
        _PlanePosition("PlanePosition",Vector) = (0,0,0,1)
        _StencilMask("Stencil Mask", Range(0, 255)) = 255
    }
    SubShader {
        Tags { "RenderType"="Opaque" }
        //LOD 200
        Stencil
        {
            Ref [_StencilMask]
            CompBack Always
            PassBack Replace

            CompFront Always
            PassFront Zero
        }
        Cull Back
            CGPROGRAM
            // Physically based Standard lighting model, and enable shadows on all light types
#pragma surface surf Standard fullforwardshadows

            // Use shader model 3.0 target, to get nicer looking lighting
#pragma target 3.0

            sampler2D _MainTex;

        struct Input {
            float2 uv_MainTex;

            float3 worldPos;
        };

        half _Glossiness;
        half _Metallic;
        fixed4 _Color;
        fixed4 _CrossColor;
        fixed3 _PlaneNormal;
        fixed3 _PlanePosition;
        bool checkVisability(fixed3 worldPos)
        {
            float dotProd1 = dot(worldPos - _PlanePosition, _PlaneNormal);
            return dotProd1 > 0  ;
        }
        void surf(Input IN, inout SurfaceOutputStandard o) {
            if (checkVisability(IN.worldPos))discard;
            fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color;
            o.Albedo = c.rgb;
            // Metallic and smoothness come from slider variables
            o.Metallic = _Metallic;
            o.Smoothness = _Glossiness;
            o.Alpha = c.a;
        }
        ENDCG

            Cull Front
            CGPROGRAM
#pragma surface surf NoLighting  noambient

        struct Input {
            half2 uv_MainTex;
            float3 worldPos;

        };
        sampler2D _MainTex;
        fixed4 _Color;
        fixed4 _CrossColor;
        fixed3 _PlaneNormal;
        fixed3 _PlanePosition;
        bool checkVisability(fixed3 worldPos)
        {
            float dotProd1 = dot(worldPos - _PlanePosition, _PlaneNormal);
            return dotProd1 >0 ;
        }
        fixed4 LightingNoLighting(SurfaceOutput s, fixed3 lightDir, fixed atten)
        {
            fixed4 c;
            c.rgb = s.Albedo;
            c.a = s.Alpha;
            return c;
        }

        void surf(Input IN, inout SurfaceOutput o)
        {
            if (checkVisability(IN.worldPos))discard;
            o.Albedo = _CrossColor;

        }
            ENDCG

    }
    //FallBack "Diffuse"
}

I tried to start from the double sided shader and add pragma surf surface from the second one at the end of the first PASS like this:

...
//End of the first PASS from the first shader

        #include "FastConfigurable.cginc"

#pragma surface surf NoLighting  noambient

        struct Input {
            half2 uv_MainTex;
            float3 worldPos;

        };
        fixed4 _CrossColor;
        fixed3 _PlaneNormal;
        fixed3 _PlanePosition;
        bool checkVisability(fixed3 worldPos)
        {
            float dotProd1 = dot(worldPos - _PlanePosition, _PlaneNormal);
            return dotProd1 > 0;
        }
        fixed4 LightingNoLighting(SurfaceOutput s, fixed3 lightDir, fixed atten)
        {
            fixed4 c;
            c.rgb = s.Albedo;
            c.a = s.Alpha;
            return c;
        }

        void surf(Input IN, inout SurfaceOutput o)
        {
            if (checkVisability(IN.worldPos))discard;
            o.Albedo = _CrossColor;

        }
            ENDCG
        }

        Pass
        {
            Name "BACK"
            Tags{ "LightMode" = "ForwardBase" }
            Cull Front
            ColorMask[_ColorWriteMask]

            CGPROGRAM
//Next of the second PASS of the first shader
...

But I am getting the following errors:

Shader Compiler Socket Exception: Terminating shader compiler process

Shader compiler: Preprocess DoubleSidedStandardCrossCut.shader:
  Internal error communicating with the shader compiler process.  Please
  report a bug including this shader and the editor log.

Shader error in 'DoubleSidedStandardCrossCut': Parse error: syntax
  error, unexpected $end, expecting TOK_SHADER at line 1

If you have any tip or suggestion, I would really appreciate, thank you!


来源: stackexchange

问:
PHP mysqli query foreach
this little script will not update the database after update from mysql to MySQLi.

```<code>include $dirlib . 'dbo.php';
if(!empty($_GET['list_vid'])) {
foreach ($_GET['list_vid'] as $position => $item) {
        $query  = mysqli_query($sql[] = "UPDATE $dbmov SET sort = '$position' WHERE id = $item");
        $result = mysqli_query($GLOBALS["___mysqli_ston"], $query);
</code>```

err('sorting videos'));

答:
Run a prepared statement instead, that you can execute multiple times over. Its simpler, and safer.

Your current issue is that you were executing an array the first time around, and an object the second time around - doesn't quite work like that.

$query = "UPDATE $dbmov SET sort = ? WHERE id = ?";
$stmt = $GLOBALS["___mysqli_ston"]->prepare($query);
$stmt->bind_param("ss", $position, $item);
foreach ($_GET['list_vid'] as $position => $item) {
    $stmt->execute();
}
$stmt->close();
```

ContentLicense: CC BY-SA 4.0

Title: PHP mysqli query foreach

Body:
this little script will not update the database after update from mysql to MySQLi.

include $dirlib . 'dbo.php';
if(!empty($_GET['list_vid'])) {
foreach ($_GET['list_vid'] as $position => $item) {
        $query  = mysqli_query($sql[] = "UPDATE $dbmov SET sort = '$position' WHERE id = $item");
        $result = mysqli_query($GLOBALS["___mysqli_ston"], $query);

err('sorting videos'));


问:
Simple CRUD Generator for C#
I am looking for a simple CRUD (or DAL) Generator for C#. I don't want anything heavyweight since I only have a couple of tables in a SQL Server 2008 database.

Any suggestions? I know .netTiers, but it is way too much for what I need.

Thanks!

UPDATE: I tried LINQ to SQL and it doesn't work well for my needs.

答:
try http://pureobjects.com/
it is not need any other work </p>

ContentLicense: CC BY-SA 2.5

Title: Simple CRUD Generator for C#

ContentLicense: CC BY-SA 3.0


问:
How to delete the first row
I have some trouble with Laravel SQL builder. I want to delete the first row. I am using the below code:

```<code>DB::table('ahah')->first()->delete().
</code>```

In the controller, I've already imported DB class using the statement use Illuminate\Support\Facades\DB. Can you tell me what's the problem and how to fix it?

答:
If are working in Laravel then it's better to use Eloquent ORM by creating Model.

```<code>namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{

    // Code Stuff
}
</code>```

fetch the first records and delete

```<code>$user = \App\Models\User::orderBy('id')->first()->delete();
</code>```

Title: How to delete the first row

Body:
I have some trouble with Laravel SQL builder. I want to delete the first row. I am using the below code:

DB::table('ahah')->first()->delete().

In the controller, I've already imported DB class using the statement use Illuminate\Support\Facades\DB. Can you tell me what's the problem and how to fix it?

Body:
If are working in Laravel then it's better to use Eloquent ORM by creating Model.

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{

    // Code Stuff
}

fetch the first records and delete

$user = \App\Models\User::orderBy('id')->first()->delete();


问:
ASP.Core ODataControllers not recognizing "get by key" operation
I'm investigating how to use OData in ASP.Core.

I've created a BooksController, subclassed from ODataController, within which I've defined two Actions:  Get(), and Get(int id).

/odata/books resolves to the first Action, but /odata/books(1) does not find the second Action.

Once the Models are defined, it is able to find the following Controller:

[ODataRoutePrefix("Books")]
public class BooksController : ODataController
{
    private BookStoreContext _db;

    public BooksController(BookStoreContext context)
    {
        _db = context;
    }

    [ODataRoute]
    [EnableQuery]
    public IActionResult Get()
    {
        return Ok(_db.Books);
    }

    [EnableQuery]
    [ODataRoute("({key})")]
    public IActionResult Get([FromODataUri] int key)
    {
        return Ok(_db.Books.FirstOrDefault(c => c.Id == key.ToGuid()));
    }
}
```

<p>The site has the default Convention rules for all routes (see below).
But I think this is not in play, as the <code>BooksController</code> is decorated with <code>[ODataRoutePrefix("Books")]</code> and the actions with <code>[ODataRoute]</code> (and <code>[EnableQuery]</code>) -- which I think, being Attribute based routing, take precedence (is that a correct assumption?).</p>

<p>My dto models are are registered using Reflection...), but the key part is where Startup invokes <code>UseMvc(...)</code>, and defines the routes, which ends up calling here:</p>

<pre class="lang-cs prettyprint-override"><code>private void CreateODataRoutes(IRouteBuilder routeBuilder)
{
    // register the convention routes for MVC first...
            routeBuilder.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
    ...

    // then do the OData stuff...

    routeBuilder.Count().Expand().Filter()
        .MaxTop(100).OrderBy().Select();

    // Use method further down the page
    // to create a Build Model by reflection, using
    // all OData Model definitions (ie, classes that implement
    // IAllModulesOdataModelBuilderConfiguration)
    var oDataConventionModelBuilder = BuildODataModelUsingReflectionAcrossAllAssemblies();

    // Use the modelBuilder as the basis of defining routes:
    RegisterRoutesToODataController(routeBuilder, oDataConventionModelBuilder);
}
</code>```

Where BuildODataModelUsingReflectionAcrossAllAssemblies uses reflection to find individual model definitions, each one pretty simple, only defining their id (relying on convention for the rest).

Note that I'm not defining Actions as that used to be by convention (see further down).

    public class BookODataModelBuilderConfigurationBase<T> : IAllModulesOdataModelBuilderConfiguration
        where T : class, IHasGuidId, new()
    {

        public virtual void Apply(ODataModelBuilder builder ...)
        {
            var _controllerName = this.GetControllerNameByConvention(typeof(Book));
            var entity = builder.EntitySet<T>(this._controllerName).EntityType;
            entity.HasKey(x => x.Id);
        //Note...no Actions defined, as planning to rely on default conventions (routing by Verb to method starting with Get...)
        }
    }

```

<p>When the model is created, it is registered as follows;</p>

<pre class="lang-cs prettyprint-override"><code>        private void RegisterRoutesToODataController(IRouteBuilder routeBuilder,
            ODataConventionModelBuilder oDataConventionModelBuilder)
        {
            string routePrefix = $"{App.Modules.Core.Shared.Constants.ModuleSpecific.Module.AssemblyNamePrefix}.";

            // Build the Edm model used to parse commands:
            var edmModel = oDataConventionModelBuilder.GetEdmModel();

            // Register the Odata paths
            routeBuilder.MapODataServiceRoute(
                routeName: $"{routePrefix}odataDefault",
                routePrefix: "odata",
                edmModel,
                pathHandler:new DefaultODataPathHandler(),
                // By convention? So that Get verb goes to Get action, etc.
                routingConventions: ODataRoutingConventions.CreateDefault()
            );
        }

</code>```

When the path is /odata/book(1) it returns HTTP ERROR 404, the page does not exist.

Thank you!

Other things I've tried include:

commented out configuration of SwaggerAPI

Removed [FromODataUri] on the key param (is it necessary?)

Added/removed [ODataRoute("({key})")]

Registered the Controller as BooksController in plural/singular

Changed the name of the Action to GetBook and back again to Get

Added/removed ODataRoutePrefix

registering the OData routes before registering the default convention routes (think that should be the case all the time, right?).

...all of which is starting to look more like desperation than coding :-( ...

Still looking. Thanks for any guidance.

答:
OMG. (sheepishly) solved.
It wasn't the Framework, Nuget, the Controller base class, routeprefix, routes, or anything glorious, it was ...me.
The only place I was not looking was the Model itself, which defined the Id as a Guid. The Action was using an int, converting it to a Guid.
ASP.Core could not find it because it was building routes based on the Model (not the Controller), so ignored the Action as it made no sense to its convention based route building as an int != Guid. duh.

If you were wondering why the heck I used an int...it was because when I had seeded the Db I wanted a Guid Key, but for testing purposes I wanted some records to have specific Ids that I could refer back to, and I was lazy, and didn't want to type in a full Guid.

That was a DUMB idea, in retrospect...:-(

But thank you for looking into it! Appreciate the time spent.

Body:
I'm investigating how to use OData in ASP.Core.

I've created a BooksController, subclassed from ODataController, within which I've defined two Actions:  Get(), and Get(int id).

/odata/books resolves to the first Action, but /odata/books(1) does not find the second Action.

Once the Models are defined, it is able to find the following Controller:

[ODataRoutePrefix("Books")]
public class BooksController : ODataController
{
    private BookStoreContext _db;

    public BooksController(BookStoreContext context)
    {
        _db = context;
    }

    [ODataRoute]
    [EnableQuery]
    public IActionResult Get()
    {
        return Ok(_db.Books);
    }

    [EnableQuery]
    [ODataRoute("({key})")]
    public IActionResult Get([FromODataUri] int key)
    {
        return Ok(_db.Books.FirstOrDefault(c => c.Id == key.ToGuid()));
    }
}

The site has the default Convention rules for all routes (see below).
But I think this is not in play, as the BooksController is decorated with [ODataRoutePrefix("Books")] and the actions with [ODataRoute] (and [EnableQuery]) -- which I think, being Attribute based routing, take precedence (is that a correct assumption?).

My dto models are are registered using Reflection...), but the key part is where Startup invokes UseMvc(...), and defines the routes, which ends up calling here:

private void CreateODataRoutes(IRouteBuilder routeBuilder)
{
    // register the convention routes for MVC first...
            routeBuilder.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
    ...

    // then do the OData stuff...

    routeBuilder.Count().Expand().Filter()
        .MaxTop(100).OrderBy().Select();

    // Use method further down the page
    // to create a Build Model by reflection, using
    // all OData Model definitions (ie, classes that implement
    // IAllModulesOdataModelBuilderConfiguration)
    var oDataConventionModelBuilder = BuildODataModelUsingReflectionAcrossAllAssemblies();

    // Use the modelBuilder as the basis of defining routes:
    RegisterRoutesToODataController(routeBuilder, oDataConventionModelBuilder);
}

Where BuildODataModelUsingReflectionAcrossAllAssemblies uses reflection to find individual model definitions, each one pretty simple, only defining their id (relying on convention for the rest).

Note that I'm not defining Actions as that used to be by convention (see further down).

    public class BookODataModelBuilderConfigurationBase<T> : IAllModulesOdataModelBuilderConfiguration
        where T : class, IHasGuidId, new()
    {

        public virtual void Apply(ODataModelBuilder builder ...)
        {
            var _controllerName = this.GetControllerNameByConvention(typeof(Book));
            var entity = builder.EntitySet<T>(this._controllerName).EntityType;
            entity.HasKey(x => x.Id);
        //Note...no Actions defined, as planning to rely on default conventions (routing by Verb to method starting with Get...)
        }
    }

When the model is created, it is registered as follows;

        private void RegisterRoutesToODataController(IRouteBuilder routeBuilder,
            ODataConventionModelBuilder oDataConventionModelBuilder)
        {
            string routePrefix = $"{App.Modules.Core.Shared.Constants.ModuleSpecific.Module.AssemblyNamePrefix}.";

            // Build the Edm model used to parse commands:
            var edmModel = oDataConventionModelBuilder.GetEdmModel();

            // Register the Odata paths
            routeBuilder.MapODataServiceRoute(
                routeName: $"{routePrefix}odataDefault",
                routePrefix: "odata",
                edmModel,
                pathHandler:new DefaultODataPathHandler(),
                // By convention? So that Get verb goes to Get action, etc.
                routingConventions: ODataRoutingConventions.CreateDefault()
            );
        }

When the path is /odata/book(1) it returns HTTP ERROR 404, the page does not exist.

Thank you!

Other things I've tried include:

commented out configuration of SwaggerAPI

Removed [FromODataUri] on the key param (is it necessary?)

Added/removed [ODataRoute("({key})")]

Registered the Controller as BooksController in plural/singular

Changed the name of the Action to GetBook and back again to Get

Added/removed ODataRoutePrefix

registering the OData routes before registering the default convention routes (think that should be the case all the time, right?).

...all of which is starting to look more like desperation than coding :-( ...

Still looking. Thanks for any guidance.


问:
How to retain a row value of other columns in Groupby?
I have a dataframe:

```<code>df = pd.DataFrame()
df['bird'] = ['shikra','shikra','eagle','eagle','eagle','crow','sparrow','sparrow']
df['bird2'] = [1,1,2,2,2,3,4,4]
df['n'] = ['a','b','c','d','e','f','g','h']
df['range'] = [1400,1600,np.nan,2800,3300,np.nan,800,600]

    bird    bird2   n   range
0   shikra  1   a   1400.0
1   shikra  1   b   1600.0
2   eagle   2   c   NaN
3   eagle   2   d   2800.0
4   eagle   2   e   3300.0
5   crow    3   f   NaN
6   sparrow 4   g   800.0
7   sparrow 4   h   600.0
</code>```

I want to find top 2 birds with max range from about data.

I used groupby operation as below:

```<code>df.groupby(['bird','bird2']).agg({'range':'max', 'n':'first'}).reset_index().sort_values('range', ascending=False).head(2)
</code>```

which gives output as:

```<code>    bird    bird2   range   n
1   eagle   2      3300.0   c
2   shikra  1      1600.0   a
</code>```

Only problem with above output is column n. As I have selected first in agg it's giving 1st value for corresponding groupby value but actually what I want is value of n which is related to maximum range.

How can I select the value from n column where range is max

Expected Output:

```<code>    bird    bird2   range   n
1   eagle   2      3300.0   e
2   shikra  1      1600.0   b
</code>```

答:
Use DataFrame.sort_values first, then remove duplicates by both columns by DataFrame.drop_duplicates and select top values by DataFrame.head or DataFrame.iloc:

```<code>df = df.sort_values('range', ascending=False).drop_duplicates(['bird','bird2']).head(2)

#df = df.sort_values('range', ascending=False).drop_duplicates(['bird','bird2']).iloc[:2]
print (df)
     bird  bird2  n   range
4   eagle      2  e  3300.0
1  shikra      1  b  1600.0
</code>```

Body:
I have a dataframe:

df = pd.DataFrame()
df['bird'] = ['shikra','shikra','eagle','eagle','eagle','crow','sparrow','sparrow']
df['bird2'] = [1,1,2,2,2,3,4,4]
df['n'] = ['a','b','c','d','e','f','g','h']
df['range'] = [1400,1600,np.nan,2800,3300,np.nan,800,600]

    bird    bird2   n   range
0   shikra  1   a   1400.0
1   shikra  1   b   1600.0
2   eagle   2   c   NaN
3   eagle   2   d   2800.0
4   eagle   2   e   3300.0
5   crow    3   f   NaN
6   sparrow 4   g   800.0
7   sparrow 4   h   600.0

I want to find top 2 birds with max range from about data.

I used groupby operation as below:

df.groupby(['bird','bird2']).agg({'range':'max', 'n':'first'}).reset_index().sort_values('range', ascending=False).head(2)

which gives output as:

    bird    bird2   range   n
1   eagle   2      3300.0   c
2   shikra  1      1600.0   a

Only problem with above output is column n. As I have selected first in agg it's giving 1st value for corresponding groupby value but actually what I want is value of n which is related to maximum range.

How can I select the value from n column where range is max

Expected Output:

    bird    bird2   range   n
1   eagle   2      3300.0   e
2   shikra  1      1600.0   b

Body:
Use DataFrame.sort_values first, then remove duplicates by both columns by DataFrame.drop_duplicates and select top values by DataFrame.head or DataFrame.iloc:

df = df.sort_values('range', ascending=False).drop_duplicates(['bird','bird2']).head(2)

#df = df.sort_values('range', ascending=False).drop_duplicates(['bird','bird2']).iloc[:2]
print (df)
     bird  bird2  n   range
4   eagle      2  e  3300.0
1  shikra      1  b  1600.0


问:
Angular error installing service worker to an existing app
I need to install a service worker in my Angular 6 application.
I run the following command:
ng add @angular/pwa --project fire but after some times no service worker is added and this is the result:

@angular/pwa@0.10.6 updated 1 package and audited 36760 packages in
  11.742s found 0 vulnerabilities

Installed packages for tooling via npm. Maximum call stack size
  exceeded

or

Installed packages for tooling via npm. Expected a synchronous
  delegate but got an asynchronous one.

This is my current configuration:

```<code>Angular CLI: 6.2.4
Node: 10.9.0
OS: win32 x64
Angular: 6.0.5
... core

Package                             Version
-------------------------------------------------------------
@angular-devkit/architect           0.8.4
@angular-devkit/build-angular       0.8.3
@angular-devkit/build-optimizer     0.8.3
@angular-devkit/build-webpack       0.8.3
@angular-devkit/core                0.8.4
@angular-devkit/schematics          0.8.4
@angular/animations                 6.0.6
@angular/cdk                        6.4.7
@angular/cli                        6.2.4
@angular/common                     6.0.6
@angular/compiler                   6.0.6
@angular/compiler-cli               6.0.6
@angular/forms                      6.0.6
@angular/http                       6.0.6
@angular/material                   6.4.7
@angular/material-moment-adapter    6.3.0
@angular/platform-browser           6.0.6
@angular/platform-browser-dynamic   6.0.6
@angular/platform-server            6.0.6
@angular/pwa                        0.10.6
@angular/router                     6.0.6
@ngtools/webpack                    6.2.3
@schematics/angular                 0.8.4
@schematics/update                  0.8.4
rxjs                                6.2.1
typescript                          2.7.2
webpack                             4.20.2
</code>```

答:
below command will work only when the project and package version will be the same.

ng add @angular/pwa --project YOUR_PROJECT_NAME

your Angular version is 6.0.5. first, upgrade it to Angular 7 and then use the above command and it will work perfectly.
Also, if you don't want to update. you have to run above

ng add @angular/pwa@VERSION6 --project YOUR_PROJECT_NAME

Body:
I need to install a service worker in my Angular 6 application.
I run the following command:
ng add @angular/pwa --project fire but after some times no service worker is added and this is the result:

@angular/pwa@0.10.6 updated 1 package and audited 36760 packages in
  11.742s found 0 vulnerabilities

Installed packages for tooling via npm. Maximum call stack size
  exceeded

or

Installed packages for tooling via npm. Expected a synchronous
  delegate but got an asynchronous one.

This is my current configuration:

Angular CLI: 6.2.4
Node: 10.9.0
OS: win32 x64
Angular: 6.0.5
... core

Package                             Version
-------------------------------------------------------------
@angular-devkit/architect           0.8.4
@angular-devkit/build-angular       0.8.3
@angular-devkit/build-optimizer     0.8.3
@angular-devkit/build-webpack       0.8.3
@angular-devkit/core                0.8.4
@angular-devkit/schematics          0.8.4
@angular/animations                 6.0.6
@angular/cdk                        6.4.7
@angular/cli                        6.2.4
@angular/common                     6.0.6
@angular/compiler                   6.0.6
@angular/compiler-cli               6.0.6
@angular/forms                      6.0.6
@angular/http                       6.0.6
@angular/material                   6.4.7
@angular/material-moment-adapter    6.3.0
@angular/platform-browser           6.0.6
@angular/platform-browser-dynamic   6.0.6
@angular/platform-server            6.0.6
@angular/pwa                        0.10.6
@angular/router                     6.0.6
@ngtools/webpack                    6.2.3
@schematics/angular                 0.8.4
@schematics/update                  0.8.4
rxjs                                6.2.1
typescript                          2.7.2
webpack                             4.20.2


问:
C# PDFsharp: TIFF images drawn without transparency
When rendering a TIFF image like this (C# and PDFsharp)

```<code>XGraphics gfx = XGraphics.FromPdfPage(page);
XImage myImg = XImage.FromStream(myImgStream);
gfx.DrawImage( myImg, x, y, s, w );
</code>```

the image is drawn without transparency.
I tried loading the image from file too (XImage.FromFile(myPath)).
If I do the same with a PNG image transparency is drawn correctly.
Am I missing something?

EDIT:

Link to sample image: https://ibin.co/4iBXM9W5hW1l

PDFsharp build is WPF. I haven't tried GDI.

答: My image did not store the transparency information - which I just recognized...</p>

Body:
When rendering a TIFF image like this (C# and PDFsharp)

XGraphics gfx = XGraphics.FromPdfPage(page);
XImage myImg = XImage.FromStream(myImgStream);
gfx.DrawImage( myImg, x, y, s, w );

the image is drawn without transparency.
I tried loading the image from file too (XImage.FromFile(myPath)).
If I do the same with a PNG image transparency is drawn correctly.
Am I missing something?

EDIT:

Link to sample image: https://ibin.co/4iBXM9W5hW1l

PDFsharp build is WPF. I haven't tried GDI.


问:
How can I get data from the acf.maps field?
I tried to make a simple fetch from the Wordpress API. In this case from ACF Fields.

With the code:

I get a response. But if I try
to add
${post.acf.address}

there are no data. But why, anyone who can help me?

Here is the code:

```<code>function getPosts() {
  fetch(
    "https://localhost/wp-json/wp/v2/tourplan?per_page=100"
  )
    .then(res => res.json())
    .then(data => {
      let output = '<h2 class="mb-4">Posts</h2>';
      data.forEach(function(post) {
        output += `
                  <div class="card card-body mb-3">
                    <h2>${post.acf.location}</h3>
                    <h3>${post.acf.programmname}</h3>
                    <p>${post.acf.datum}</p>
                    <p>${post.acf.beginn}</p>
                  </div>
                `;
        console.log(data);
      });
      document.getElementById("output").innerHTML = output;
    });
}
</code>```

This is the json response if you call the fetch url in a browser.

```<code>[
    {
        "id": 5692,
        "date": "2019-05-08T14:41:15",
        "date_gmt": "2019-05-08T12:41:15",
        "guid": {
            "rendered": "https://localhost/?post_type=tourplan&p=5692"
        },
        "modified": "2019-05-08T14:41:15",
        "modified_gmt": "2019-05-08T12:41:15",
        "slug": "münchen",
        "status": "publish",
        "type": "tourplan",
        "link": "https://localhost/Tourplan/münchen/",
        "title": {
            "rendered": "München"
        },
        "content": {
            "rendered": "",
            "protected": false
        },
        "template": "",
        "authorName": "wtced",
        "acf": {
            "plz": "81825",
            "location": "Wirtshaus",
            "programmname": "\"Programmname\"",
            "datum": "20190913",
            "einlass": "18:00",
            "beginn": "20:00",
            "ticketlink": "https://localhost/hxanh/",
            "ausverkauft": false,
            "vvk": "Veranstalter: Testverein e.V.",
            "zusatzfeld": "",
            "maps": {
                "address": "Feldstraße 35, 81825 München, Deutschland",
                "lat": "48.386076050384",
                "lng": "11.348405060504"
            }
    }
]
</code>```

答: Thank you all, the code was okay. The reason for doesn't work were too many results.</p>

Body:
I tried to make a simple fetch from the Wordpress API. In this case from ACF Fields.

With the code:

I get a response. But if I try
to add
${post.acf.address}

there are no data. But why, anyone who can help me?

Here is the code:

function getPosts() {
  fetch(
    "https://localhost/wp-json/wp/v2/tourplan?per_page=100"
  )
    .then(res => res.json())
    .then(data => {
      let output = '
Posts
';
      data.forEach(function(post) {
        output += `

${post.acf.location}

${post.acf.programmname}

${post.acf.datum}

${post.acf.beginn}

                `;
        console.log(data);
      });
      document.getElementById("output").innerHTML = output;
    });
}

This is the json response if you call the fetch url in a browser.

[
    {
        "id": 5692,
        "date": "2019-05-08T14:41:15",
        "date_gmt": "2019-05-08T12:41:15",
        "guid": {
            "rendered": "https://localhost/?post_type=tourplan&p=5692"
        },
        "modified": "2019-05-08T14:41:15",
        "modified_gmt": "2019-05-08T12:41:15",
        "slug": "münchen",
        "status": "publish",
        "type": "tourplan",
        "link": "https://localhost/Tourplan/münchen/",
        "title": {
            "rendered": "München"
        },
        "content": {
            "rendered": "",
            "protected": false
        },
        "template": "",
        "authorName": "wtced",
        "acf": {
            "plz": "81825",
            "location": "Wirtshaus",
            "programmname": "\"Programmname\"",
            "datum": "20190913",
            "einlass": "18:00",
            "beginn": "20:00",
            "ticketlink": "https://localhost/hxanh/",
            "ausverkauft": false,
            "vvk": "Veranstalter: Testverein e.V.",
            "zusatzfeld": "",
            "maps": {
                "address": "Feldstraße 35, 81825 München, Deutschland",
                "lat": "48.386076050384",
                "lng": "11.348405060504"
            }
    }
]


问:
ViewComponent does not recognize AspNetCore.Identity "User"
I'm trying to create a ViewComponent for a series of checkboxes based on this article here:

https://learn.microsoft.com/en-us/aspnet/core/mvc/views/view-components?view=aspnetcore-2.2

And this SO answer here:
https://stackoverflow.com/a/42853705/2300177

Seems like a perfect case scenario for what I'm trying to do. However, I've created my ViewComponent to include Identity UserManager to get the userId:

```<code>using BlogPlayground.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace BlogPlayground.ViewComponents
{
    public class LatestArticlesViewComponent : ViewComponent
    {
        private readonly ApplicationDbContext _context;
        private readonly UserManager<IdentityUser> _userManager;

        public LatestArticlesViewComponent(ApplicationDbContext context, UserManager<IdentityUser> userManager)
        {
            _context = context;
            _userManager = userManager;
        }

        public async Task<IViewComponentResult> InvokeAsync()
        {
            string userId = _userManager.GetUserId(User);

            var lastArticles = await _context.Article
                                            .OrderByDescending(a => a.CreatedDate)
                                            .Take(howMany)
                                            .ToListAsync();
            return View(lastArticles);
        }
    }
}
</code>```

The problem is that when I call this line:

```<code>string userId = _userManager.GetUserId(User);
</code>```

I'm getting an error for Userthat reads:

cannot convert from 'System.Security.Principal.IPrincipal' to
  'System.Security.Claims.ClaimsPrincipal'

This exact code works in all my controllers and I have no idea where the User even comes from. Seems like magic, but I'm guessing somewhere inherent inside Identity? Or did I just miss something included in my controllers? (I searched "User" in my controllers and can't link that to anything.)

I'm using the Pomelo MySQL nuget package if that makes a difference? I wouldn't think so.

Anyone know what I'm missing and how to eliminate this error?

Update: Seems it will work with this (at least it gets rid of the error):

```<code>string userId = _userManager.GetUserId(Request.HttpContext.User);
</code>```

Is that the same thing? Is there a using statement I'm missing? Visual studio (2017) usually clues me in to what I'm missing.

答:
Please make sure you configured services.AddDefaultIdentity and enabled app.UseAuthentication Identity in your Startup.

This is needed to make it available to the app through dependency injection, so you can get it loaded in your LatestArticlesViewComponent.

See the details here: Introduction to Identity on ASP.NET Core

Body:
I'm trying to create a ViewComponent for a series of checkboxes based on this article here:

https://learn.microsoft.com/en-us/aspnet/core/mvc/views/view-components?view=aspnetcore-2.2

And this SO answer here:
https://stackoverflow.com/a/42853705/2300177

Seems like a perfect case scenario for what I'm trying to do. However, I've created my ViewComponent to include Identity UserManager to get the userId:

using BlogPlayground.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace BlogPlayground.ViewComponents
{
    public class LatestArticlesViewComponent : ViewComponent
    {
        private readonly ApplicationDbContext _context;
        private readonly UserManager<IdentityUser> _userManager;

        public LatestArticlesViewComponent(ApplicationDbContext context, UserManager<IdentityUser> userManager)
        {
            _context = context;
            _userManager = userManager;
        }

        public async Task<IViewComponentResult> InvokeAsync()
        {
            string userId = _userManager.GetUserId(User);

            var lastArticles = await _context.Article
                                            .OrderByDescending(a => a.CreatedDate)
                                            .Take(howMany)
                                            .ToListAsync();
            return View(lastArticles);
        }
    }
}

The problem is that when I call this line:

string userId = _userManager.GetUserId(User);

I'm getting an error for Userthat reads:

cannot convert from 'System.Security.Principal.IPrincipal' to
  'System.Security.Claims.ClaimsPrincipal'

This exact code works in all my controllers and I have no idea where the User even comes from. Seems like magic, but I'm guessing somewhere inherent inside Identity? Or did I just miss something included in my controllers? (I searched "User" in my controllers and can't link that to anything.)

I'm using the Pomelo MySQL nuget package if that makes a difference? I wouldn't think so.

Anyone know what I'm missing and how to eliminate this error?

Update: Seems it will work with this (at least it gets rid of the error):

string userId = _userManager.GetUserId(Request.HttpContext.User);

Is that the same thing? Is there a using statement I'm missing? Visual studio (2017) usually clues me in to what I'm missing.


问:
stop automatical convert to htmlentities?
I have a div id="ultimativegodemperorofalldivs"
It contains some Text like "such a cool & sexy div"

when I extract the InnerHTML with JS it converts the & to &
I really don't want this. I don't need it for URL's so it really should be a very simple &.
How to archive this?

Thx in Advance,
iceteea

答:
Like its name says, innerHTML retrieves the element’s inner HTML.  Without HTML entities, it wouldn’t be valid HTML.  If you want to retrieve the element’s text content, you’ll have to use the element’s textContent or innerText properties.

(innerText is only supported in IE; but textContent is not supported by older versions of IE).


问:
Unity - How can i make a function fire only when player clicked on it 3 times?
I have a hint button on my game, but it fires up everytime you click on it. I need for it to fire only once every 3 clicks

i've tried adding a loadCount = 0 and an if statement

```<code>if (loadCount % 3 == 0) { }
</code>```

but it dosen't seem to work

image for reference : https://ibb.co/L9LnNDw

Here is the script:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[ExecuteInEditMode]
public class HintScript : MonoBehaviour
{

    LineRenderer line;

    // Use this for initialization
    void Start ()
    {

    }

    // Update is called once per frame
    void Update ()
    {
        line = GetComponent<LineRenderer>();
        line.positionCount = transform.childCount;
        for (int i = 0; i<transform.childCount; i++)
        {
            line.SetPosition(i, transform.GetChild(i).position);
        }
    }

    // This is called from onClick of the Button
    public void Hint()
    {
        FindObjectOfType<AdMobManager>().Hint = true;
        FindObjectOfType<AdMobManager>().showInterstitial();
    }
}
</code>```

答:
You can have a counter to keep track of how many times the player has clicked. Then fire when that counter is at 3.</p>

```<code>int amountOfClicks = 0;
void clickme(){
   amountOfClicks++;
   if(amountOfClicks == 3){
      amountOfClicks = 0;
      YourFunction();
   }
}

void YourFunction(){
   // do something...

}
</code>```

Body:
I have a hint button on my game, but it fires up everytime you click on it. I need for it to fire only once every 3 clicks

i've tried adding a loadCount = 0 and an if statement

if (loadCount % 3 == 0) { }

but it dosen't seem to work

image for reference : https://ibb.co/L9LnNDw

Here is the script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[ExecuteInEditMode]
public class HintScript : MonoBehaviour
{

    LineRenderer line;

    // Use this for initialization
    void Start ()
    {

    }

    // Update is called once per frame
    void Update ()
    {
        line = GetComponent<LineRenderer>();
        line.positionCount = transform.childCount;
        for (int i = 0; i<transform.childCount; i++)
        {
            line.SetPosition(i, transform.GetChild(i).position);
        }
    }

    // This is called from onClick of the Button
    public void Hint()
    {
        FindObjectOfType<AdMobManager>().Hint = true;
        FindObjectOfType<AdMobManager>().showInterstitial();
    }
}

Body:
You can have a counter to keep track of how many times the player has clicked. Then fire when that counter is at 3.

int amountOfClicks = 0;
void clickme(){
   amountOfClicks++;
   if(amountOfClicks == 3){
      amountOfClicks = 0;
      YourFunction();
   }
}

void YourFunction(){
   // do something...

}


问:
DOMException: Failed to execute 'querySelector' on 'Document':
I am working on a project which I started building on bootstrap 4.3.1.

I'm crazy about this one Javascript and html coding.

```<code><a class="dropdown-item" href="{{ route('user.panel') }}">
    User panel
</a>
</code>```

I get this error in console.

SyntaxError: 'http://localhost:8000/user/panel' is not a valid selector

bootstrap.min.js:6 Uncaught DOMException: Failed to execute 'querySelector' on 'Document': 'http://localhost:8000/user/panel' is not a valid selector.
      at Object.getSelectorFromElement (http://localhost:8000/themes/js/bootstrap.min.js:6:1466)
      at http://localhost:8000/themes/js/bootstrap.min.js:6:46766
      at Array.map ()
      at n.t.refresh (http://localhost:8000/themes/js/bootstrap.min.js:6:46740)
      at new n (http://localhost:8000/themes/js/bootstrap.min.js:6:46381)

I figured out that it occur due to the dropdown because of this error the dropdown does not work. I also checked, that if I am using href="javascript:void(0);", href="#!" the error occur but if i use anchor tag without href or href="#" then it is working fine.

Note: I need the solution with href="javascript:void(0); as href="# in the address link does not look pretty and page scrolls up to the top .

```<code><ul class="navbar-nav">
    @guest
    <li class="navbar-item dropdown">
        <a href="#" class="nav-link" data-toggle="dropdown">Register/Login<i class="fas fa-sort-down"></i></a>
        <div class="dropdown-menu text-right m-2 position-absolute" style="width:300px;left:-111px;">
            <a href="{{ route('login') }}" class="btn btn-primary d-block m-3">Login</a>
            <span class="m-3">Are you new user?<a href="{{ route('register') }}" class="link-sign">Login</a></span>
        </div>
    </li>
    @else
        <li class="nav-item dropdown">
            <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
                {{ Auth::user()->first_name }} {{ Auth::user()->last_name }} <span class="caret"></span>
            </a>

            <div class="dropdown-menu dropdown-menu-left" aria-labelledby="navbarDropdown">
                <a class="dropdown-item" href="{{ route('user.panel') }}">
                    User Panel
                </a>
                <a class="dropdown-item" href="#" id="logout-button">
                    {{ __('Logout') }}
                </a>
                <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                    @csrf
                </form>
            </div>
        </li>
    @endguest
</ul>
</code>```

The error comes in the following line.

```<code>$('body').scrollspy({
    target: '#mainNav',
    offset: 50
});
</code>```

script.js

```<code>(function($) {
    "use strict"; // Start of use strict

    // Smooth scrolling using jQuery easing
    $('a.js-scroll-trigger[href*="#"]:not([href="#"])').click(function() {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
            if (target.length) {
                $('html, body').animate({
                    scrollTop: (target.offset().top - 54)
                }, 1000, "easeInOutExpo");
                return false;
            }
        }
    });

    // Closes responsive menu when a scroll trigger link is clicked
    $('.js-scroll-trigger').click(function() {
        $('.navbar-collapse').collapse('hide');
    });

    // Activate scrollspy to add active class to navbar items on scroll
    $('body').scrollspy({
        target: '#mainNav',
        offset: 50
    });

})(jQuery); // End of use strict

AOS.init({
    easing: 'ease-in-out-sine'
});

$('#logout-button').on('click', function(e) {
    e.preventDefault();
    $('#logout-form').submit();
});

$('#select').change(function() {
    var $selected = $(this).find(':selected');
    $('#description').html($selected.data('description'));
}).trigger('change');
$("#select").change(function() {
    var color = $(this).val();
    if (color == "laptop_repair") {
        $(".box").not(".laptop_repair").hide();
        $(".laptop_repair").show();
    } else if (color == "install_windows") {
        $(".box").not(".install_windows").hide();
        $(".install_windows").show();
    } else if (color == "backup") {
        $(".box").not(".backup").hide();
        $(".backup").show();
    } else if (color == "antivirus") {
        $(".box").not(".antivirus").hide();
        $(".antivirus").show();
    } else if (color == "magenta") {
        $(".box").not(".magenta").hide();
        $(".magenta").show();
    } else {
        $(".box").hide();
    }
});
getSelectorFromElement: function getSelectorFromElement(element) {
    var selector = element.getAttribute('data-target');

    if (!selector || selector === '#') {
        var hrefAttr = element.getAttribute('href');
        selector = hrefAttr && hrefAttr !== '#' ? hrefAttr.trim() : '';
    }

    return selector && document.querySelector(selector) ? selector : null;
}
</code>```

答:
The error comes from Bootstrap's scrollspy component, that clearly states:

Anchors () are required and must point to an element with that id.

or

Navbar links must have resolvable id targets. For example, a home must correspond to something in the DOM like

.

You have couple of solutions:

Change the scrollspy tartget from #mainNav to something more narrow which does not include .navbar-nav

In case you wanna track/spy the links inside the .navbar-nav, than you need either to hack scrollspy source, or to use some other component

Keep everything as is, but use valid local links in anchors.

Body:
I am working on a project which I started building on bootstrap 4.3.1.

I'm crazy about this one Javascript and html coding.

    User panel

I get this error in console.

SyntaxError: 'http://localhost:8000/user/panel' is not a valid selector

bootstrap.min.js:6 Uncaught DOMException: Failed to execute 'querySelector' on 'Document': 'http://localhost:8000/user/panel' is not a valid selector.
      at Object.getSelectorFromElement (http://localhost:8000/themes/js/bootstrap.min.js:6:1466)
      at http://localhost:8000/themes/js/bootstrap.min.js:6:46766
      at Array.map ()
      at n.t.refresh (http://localhost:8000/themes/js/bootstrap.min.js:6:46740)
      at new n (http://localhost:8000/themes/js/bootstrap.min.js:6:46381)

I figured out that it occur due to the dropdown because of this error the dropdown does not work. I also checked, that if I am using href="javascript:void(0);", href="#!" the error occur but if i use anchor tag without href or href="#" then it is working fine.

Note: I need the solution with href="javascript:void(0); as href="# in the address link does not look pretty and page scrolls up to the top .

    @guest

        Register/Login

            Login
            Are you new user?Login

    @else

                {{ Auth::user()->first_name }} {{ Auth::user()->last_name }}

                    User Panel

                    {{ __('Logout') }}

                <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                    @csrf
                </form>

    @endguest

The error comes in the following line.

$('body').scrollspy({
    target: '#mainNav',
    offset: 50
});

script.js

(function($) {
    "use strict"; // Start of use strict

    // Smooth scrolling using jQuery easing
    $('a.js-scroll-trigger[href*="#"]:not([href="#"])').click(function() {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
            if (target.length) {
                $('html, body').animate({
                    scrollTop: (target.offset().top - 54)
                }, 1000, "easeInOutExpo");
                return false;
            }
        }
    });

    // Closes responsive menu when a scroll trigger link is clicked
    $('.js-scroll-trigger').click(function() {
        $('.navbar-collapse').collapse('hide');
    });

    // Activate scrollspy to add active class to navbar items on scroll
    $('body').scrollspy({
        target: '#mainNav',
        offset: 50
    });

})(jQuery); // End of use strict

AOS.init({
    easing: 'ease-in-out-sine'
});

$('#logout-button').on('click', function(e) {
    e.preventDefault();
    $('#logout-form').submit();
});

$('#select').change(function() {
    var $selected = $(this).find(':selected');
    $('#description').html($selected.data('description'));
}).trigger('change');
$("#select").change(function() {
    var color = $(this).val();
    if (color == "laptop_repair") {
        $(".box").not(".laptop_repair").hide();
        $(".laptop_repair").show();
    } else if (color == "install_windows") {
        $(".box").not(".install_windows").hide();
        $(".install_windows").show();
    } else if (color == "backup") {
        $(".box").not(".backup").hide();
        $(".backup").show();
    } else if (color == "antivirus") {
        $(".box").not(".antivirus").hide();
        $(".antivirus").show();
    } else if (color == "magenta") {
        $(".box").not(".magenta").hide();
        $(".magenta").show();
    } else {
        $(".box").hide();
    }
});
getSelectorFromElement: function getSelectorFromElement(element) {
    var selector = element.getAttribute('data-target');

    if (!selector || selector === '#') {
        var hrefAttr = element.getAttribute('href');
        selector = hrefAttr && hrefAttr !== '#' ? hrefAttr.trim() : '';
    }

    return selector && document.querySelector(selector) ? selector : null;
}

Body:
The error comes from Bootstrap's scrollspy component, that clearly states:

Anchors () are required and must point to an element with that id.

or

Navbar links must have resolvable id targets. For example, a <a
  href="#home">home</a> must correspond to something in the DOM like
  <div id="home">.

You have couple of solutions:

Change the scrollspy tartget from #mainNav to something more narrow which does not include .navbar-nav

In case you wanna track/spy the links inside the .navbar-nav, than you need either to hack scrollspy source, or to use some other component

Keep everything as is, but use valid local links in anchors.


问:
Function not doing anything after clicking on button (aspx page)
I have problem with buttons, I typed alert("") to be sure if it enters to function or not,I discovered that it enters into function after I click on button and the alert works fine but, anything else inside function does not work neither ajax nor any simple jquery code. I will add the code to be more clarified.

for example these buttons below

```<code><button type="button" id="submitX" class="btn btn-primary">Submit</button>
<button type="submit" id="cancelX" class="btn btn-default">Cancel</button>
</code>```

This javascript code

```<code>    $(document).ready(function () {
    $(document).on("click", "#cancelX", function (event) {
          alert('cancel function');
            window.location.href = "www.test.com";
         });
    $(document).on("click", "#submitX", function (event) {
           alert('submit function');

var Details  = $('#Detail').summernote('code');
var params = [];
params.push({ name: "CreatedBy", value: $('#Email').val() });
params.push({ name: "Detail", value: Details});
var apiURL = "<%= ResolveUrl("~/api/Submit/") %>";
$.ajax({
url: apiURL,
data: params,
type: "POST",
success: function (data, textStatus, jqXHR) {
window.location.href = "www.test.com";
},
error: function (err) {
swal({
text: "An error occured.",
icon: "error"
});
}
})

  });
    });
</code>```

why are both buttons or functions not working properly ? did I do anything wrong here ?

答:
Try to remove document.ready() function on click event of cancel and submit button.Use below syntax:

```<code> $("#id_name").click(function (event) {
      ..//Code
 });
</code>```

And also remove type submit on which is given in submit button.Just make it simple button.

Body:
I have problem with buttons, I typed alert("") to be sure if it enters to function or not,I discovered that it enters into function after I click on button and the alert works fine but, anything else inside function does not work neither ajax nor any simple jquery code. I will add the code to be more clarified.

for example these buttons below

<button type="button" id="submitX" class="btn btn-primary">Submit</button>
<button type="submit" id="cancelX" class="btn btn-default">Cancel</button>

This javascript code

    $(document).ready(function () {
    $(document).on("click", "#cancelX", function (event) {
          alert('cancel function');
            window.location.href = "www.test.com";
         });
    $(document).on("click", "#submitX", function (event) {
           alert('submit function');

var Details  = $('#Detail').summernote('code');
var params = [];
params.push({ name: "CreatedBy", value: $('#Email').val() });
params.push({ name: "Detail", value: Details});
var apiURL = "<%= ResolveUrl("~/api/Submit/") %>";
$.ajax({
url: apiURL,
data: params,
type: "POST",
success: function (data, textStatus, jqXHR) {
window.location.href = "www.test.com";
},
error: function (err) {
swal({
text: "An error occured.",
icon: "error"
});
}
})

  });
    });

why are both buttons or functions not working properly ? did I do anything wrong here ?

Body:
Try to remove document.ready() function on click event of cancel and submit button.Use below syntax:

 $("#id_name").click(function (event) {
      ..//Code
 });

And also remove type submit on which is given in submit button.Just make it simple button.


问:
Add fragment in RecyclerView.ViewHolder
I have a RecyclerView.ViewHolder which will add different fragment into its FrameLayout based on the instance of the object passed. The problem comes where it is almost impossible to add fragment into the ViewHolder. Take note that I already passed the FragmentManager from the parent. Initially I try with this code

```<code>public void setSomething(boolean A) {
    if (A) {
         mFragmentManager.beginTransaction()
            .replace(mBinding.typeContainerLayout.getId(), new FragmentA())
            .commit();
    } else {
        mFragmentManager.beginTransaction()
            .replace(mBinding.typeContainerLayout.getId(), new FragmentB())
            .commit();
    }
}
</code>```

The problem with this code is that all the ViewHolder share the same id, thus only a single ViewHolder can add the fragment. In my RecyclerView, only the first cell added the fragment. To tackle this problem, I create another FrameLayout and add it into typeContainerLayout. Now my code become like this.

```<code>public void setSomething(boolean A) {
    FrameLayout frameLayout = new FrameLayout(mContext);
    frameLayout.setId(View.generateViewId());
    mBinding.typeContainerLayout.removeAllViews();
    mBinding.typeContainerLayout.addView(frameLayout)

    if (A) {
         mFragmentManager.beginTransaction()
            .replace(frameLayout.getId(), new FragmentA())
            .commit();
    } else {
        mFragmentManager.beginTransaction()
            .replace(frameLayout.getId(), new FragmentB())
            .commit();
    }
}
</code>```

Now each ViewHolder has added the fragment correctly and has their own fragment. However the problem comes when I added like 5 ViewHolder and trying to scroll down the RecyclerView, a runtime error occurred which state

```<code>java.lang.IllegalArgumentException: No view found for id 0x4 (unknown) for fragment FragmentA{7c55a69 #0 id=0x4 FragmentA}
                      at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1292)
                      at android.support.v4.app.FragmentManagerImpl.moveFragmentsToInvisible(FragmentManager.java:2323)
                      at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2136)
                      at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2092)
                      at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1998)
                      at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:709)
                      at android.os.Handler.handleCallback(Handler.java:739)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:148)
                      at android.app.ActivityThread.main(ActivityThread.java:5417)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

My guess is that either the id conflicted at some point, or the view got destroyed due to the ViewHolder pattern. So my question is that.

1) Is there any workaround to it?

2) Is there any better practice than adding fragment. The reason I add fragment is so that the logic for the sub item of the ViewHolder can all be located in a single fragment. Of course I can just put both the views for the fragments into the ViewHolder xml. And just setVisible() depending on the condition. But that will just make my ViewHolder contain too many logic.

In case someone is confused why I need fragment. This is what I am trying to achieve.
The image

答:
You should know exactly that recyclerview created your holder and drew a view for him, so you need to attach a fragment in onViewAttachedToWindowmethod of your adapter. In your "attaching fragment" method you should check if fragment manager already contains those fragments to prevent of creating multiple instances.

Adapter:

```<code> override fun onViewAttachedToWindow(holder: RecyclerView.ViewHolder) {
    if(holder is FragmentsHolder){
        attachFragmentToContainer(holder.flContainer)
    }
    super.onViewAttachedToWindow(holder)
}
</code>```

Method realization:

```<code> fun attachFragmentToContainer(containerId: Int) {
    val fragment = if (fragmentManager?.fragments?.firstOrNull { it is YourFragment } == null)
        YourFragment.instance()
    else
        null

    if (fragment != null) {
        fragmentManager?.beginTransaction()
            ?.add(containerId, fragment)
            ?.commitNowAllowingStateLoss()
    }
}
</code>```

This tested on big amount of users - no crashes, good perfomance.

Title: Add fragment in RecyclerView.ViewHolder

Body:
I have a RecyclerView.ViewHolder which will add different fragment into its FrameLayout based on the instance of the object passed. The problem comes where it is almost impossible to add fragment into the ViewHolder. Take note that I already passed the FragmentManager from the parent. Initially I try with this code

public void setSomething(boolean A) {
    if (A) {
         mFragmentManager.beginTransaction()
            .replace(mBinding.typeContainerLayout.getId(), new FragmentA())
            .commit();
    } else {
        mFragmentManager.beginTransaction()
            .replace(mBinding.typeContainerLayout.getId(), new FragmentB())
            .commit();
    }
}

The problem with this code is that all the ViewHolder share the same id, thus only a single ViewHolder can add the fragment. In my RecyclerView, only the first cell added the fragment. To tackle this problem, I create another FrameLayout and add it into typeContainerLayout. Now my code become like this.

public void setSomething(boolean A) {
    FrameLayout frameLayout = new FrameLayout(mContext);
    frameLayout.setId(View.generateViewId());
    mBinding.typeContainerLayout.removeAllViews();
    mBinding.typeContainerLayout.addView(frameLayout)

    if (A) {
         mFragmentManager.beginTransaction()
            .replace(frameLayout.getId(), new FragmentA())
            .commit();
    } else {
        mFragmentManager.beginTransaction()
            .replace(frameLayout.getId(), new FragmentB())
            .commit();
    }
}

Now each ViewHolder has added the fragment correctly and has their own fragment. However the problem comes when I added like 5 ViewHolder and trying to scroll down the RecyclerView, a runtime error occurred which state

java.lang.IllegalArgumentException: No view found for id 0x4 (unknown) for fragment FragmentA{7c55a69 #0 id=0x4 FragmentA}
                      at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1292)
                      at android.support.v4.app.FragmentManagerImpl.moveFragmentsToInvisible(FragmentManager.java:2323)
                      at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2136)
                      at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2092)
                      at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1998)
                      at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:709)
                      at android.os.Handler.handleCallback(Handler.java:739)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:148)
                      at android.app.ActivityThread.main(ActivityThread.java:5417)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

My guess is that either the id conflicted at some point, or the view got destroyed due to the ViewHolder pattern. So my question is that.

1) Is there any workaround to it?

2) Is there any better practice than adding fragment. The reason I add fragment is so that the logic for the sub item of the ViewHolder can all be located in a single fragment. Of course I can just put both the views for the fragments into the ViewHolder xml. And just setVisible() depending on the condition. But that will just make my ViewHolder contain too many logic.

In case someone is confused why I need fragment. This is what I am trying to achieve.
The image

Body:
You should know exactly that recyclerview created your holder and drew a view for him, so you need to attach a fragment in onViewAttachedToWindowmethod of your adapter. In your "attaching fragment" method you should check if fragment manager already contains those fragments to prevent of creating multiple instances.

Adapter:

 override fun onViewAttachedToWindow(holder: RecyclerView.ViewHolder) {
    if(holder is FragmentsHolder){
        attachFragmentToContainer(holder.flContainer)
    }
    super.onViewAttachedToWindow(holder)
}

Method realization:

 fun attachFragmentToContainer(containerId: Int) {
    val fragment = if (fragmentManager?.fragments?.firstOrNull { it is YourFragment } == null)
        YourFragment.instance()
    else
        null

    if (fragment != null) {
        fragmentManager?.beginTransaction()
            ?.add(containerId, fragment)
            ?.commitNowAllowingStateLoss()
    }
}

This tested on big amount of users - no crashes, good perfomance.


问:
Post to a Facebook user's stream at a later date?
What would be the common workflow to be able to post to a user's feed/stream a couple of hours/days after they've accepted your access permissions on your "canvas" app?

For instance, if someone were to register their interest to be notified when something has been released, how could we post on their wall the release notification when it occurs a few days later?

Specifically, how would authentication work? Does one need to log the keys gathered during the original authentication process?

答:
When you request permissions during authentication you must request the offline_access permission to post to the users wall when they're not signed in.  With this permission, the access token you use to perform api requests becomes permanent, and you can use it at any time.

Further reading:
Facebook offline access step-by-step


问:
Point Cloud Visualization
I am trying to load and visualize a point cloud data by "addPointCloud" instruction.

```<code>    //***********
pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGBA>);

if (pcl::io::loadPCDFile<pcl::PointXYZRGBA> ("f.pcd", *cloud) == -1)
  {
    PCL_ERROR ("Couldn't read the pcd file \n");
    return (-1);
  }
pcl::visualization::PCLVisualizer viewer ("Simple Cloud Viewer");
viewer.setBackgroundColor (0, 0, 0);
viewer.addPointCloud(cloud, "sample cloud");
    //***********
</code>```

But instead of seeing my point cloud in a black background, only see a white backbround whithout any point cloud. Can any one tell me kindly where is my problem?

答:
pcl::visualization::PCLVisualizer viewer window object has been created and you're currently looking at just the window... You would need to add .spin()

```<code>viewer.spin();
</code>```

Title: Point Cloud Visualization

Body:
I am trying to load and visualize a point cloud data by "addPointCloud" instruction.

    //***********
pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGBA>);

if (pcl::io::loadPCDFile<pcl::PointXYZRGBA> ("f.pcd", *cloud) == -1)
  {
    PCL_ERROR ("Couldn't read the pcd file \n");
    return (-1);
  }
pcl::visualization::PCLVisualizer viewer ("Simple Cloud Viewer");
viewer.setBackgroundColor (0, 0, 0);
viewer.addPointCloud(cloud, "sample cloud");
    //***********

But instead of seeing my point cloud in a black background, only see a white backbround whithout any point cloud. Can any one tell me kindly where is my problem?

Body:
pcl::visualization::PCLVisualizer viewer window object has been created and you're currently looking at just the window... You would need to add .spin()

viewer.spin();


问:
SQL add conditional query
In a table in my database I have 12 columns, month_1 .... month_12.

I want to add conditional to my SQL query, if @m = 1 will do

```<code>CREATE PROCEDURE XemDiem_Top5Month1
    @m INT
AS
BEGIN
    SELECT *
    FROM XemDiem
    WHERE (month_1 IN (SELECT TOP (5) month_1
                       FROM XemDiem
                       GROUP BY month_1
                       ORDER BY month_1DESC))
END
</code>```

if @m = 2 will do

```<code>CREATE PROCEDURE XemDiem_Top5Month1
    @m INT
AS
BEGIN
    SELECT *
    FROM XemDiem
    WHERE (month_2 IN (SELECT TOP (5) month_2
                       FROM XemDiem
                       GROUP BY month_2
                       ORDER BY month_2 DESC))
END
</code>```

and so on ....

I don't want to write too many queries, so please help

答:
Assign the select query to a string and concatenate your parameter. Finally execute the string. </p>

```<code>Create proc XemDiem_Top5Month1
@m int
AS
BEGIN
Delcare @query nvarchar(max)
set @query='SELECT *
FROM XemDiem
WHERE
(
  month_''+Convert(varchar(10),@m)+'' IN
  (
    SELECT TOP (5) month_''+Convert(varchar(10),@m)+''
    FROM XemDiem
    GROUP BY month_''+Convert(varchar(10),@m)+''
    ORDER BY month_''+Convert(varchar(10),@m)+'' DESC
  )
)'
execute(@query)
</code>```

Title: SQL add conditional query

Body:
In a table in my database I have 12 columns, month_1 .... month_12.

I want to add conditional to my SQL query, if @m = 1 will do

CREATE PROCEDURE XemDiem_Top5Month1
    @m INT
AS
BEGIN
    SELECT *
    FROM XemDiem
    WHERE (month_1 IN (SELECT TOP (5) month_1
                       FROM XemDiem
                       GROUP BY month_1
                       ORDER BY month_1DESC))
END

if @m = 2 will do

CREATE PROCEDURE XemDiem_Top5Month1
    @m INT
AS
BEGIN
    SELECT *
    FROM XemDiem
    WHERE (month_2 IN (SELECT TOP (5) month_2
                       FROM XemDiem
                       GROUP BY month_2
                       ORDER BY month_2 DESC))
END

and so on ....

I don't want to write too many queries, so please help

Body:
Assign the select query to a string and concatenate your parameter. Finally execute the string.

Create proc XemDiem_Top5Month1
@m int
AS
BEGIN
Delcare @query nvarchar(max)
set @query='SELECT *
FROM XemDiem
WHERE
(
  month_''+Convert(varchar(10),@m)+'' IN
  (
    SELECT TOP (5) month_''+Convert(varchar(10),@m)+''
    FROM XemDiem
    GROUP BY month_''+Convert(varchar(10),@m)+''
    ORDER BY month_''+Convert(varchar(10),@m)+'' DESC
  )
)'
execute(@query)


问:
How to open only camera and crop using theartofdev in android
how to open only camera and crop using theartofdev dependency .I am using theartofdev dependency 2.7.+ . </p>

答:
Try this</p>

```<code> //Declare in Manifest file
   <activity
        android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
        android:theme="@style/Base.Theme.AppCompat" />

// Declare global variable
  Uri mCropImageUri;

// write below line on the button click
CropImage.startPickImageActivity(this);

// then result will received inside onActivityResult() method
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    getImageCallback(requestCode,resultCode,data);
}

  public void getImageCallback(int requestCode, int resultCode, Intent data) {
    if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
        Uri imageUri = CropImage.getPickImageResultUri(this, data);
        // For API >= 23 we need to check specifically that we have permissions to read external storage.
        if (CropImage.isReadExternalStoragePermissionsRequired(this, imageUri)) {
            // request permissions and handle the result in onRequestPermissionsResult()
            mCropImageUri = imageUri;
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, CropImage.PICK_IMAGE_PERMISSIONS_REQUEST_CODE);
        } else {
            // no permissions required or already grunted, can start crop image activity
            startCropImageActivity(imageUri);
        }
    }
    else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {

        CropImage.ActivityResult result = CropImage.getActivityResult(data);
        if (resultCode == RESULT_OK) {
            Uri resultUri = result.getUri();
            profileImage.setImageURI(resultUri);

        }
    }
}

 private void startCropImageActivity(Uri imageUri) {
    CropImage.activity(imageUri).setGuidelines(CropImageView.Guidelines.ON).setCropShape(CropImageView.CropShape.OVAL).start(this);
}
</code>```

Body:
Try this

 //Declare in Manifest file
   <activity
        android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
        android:theme="@style/Base.Theme.AppCompat" />

// Declare global variable
  Uri mCropImageUri;

// write below line on the button click
CropImage.startPickImageActivity(this);

// then result will received inside onActivityResult() method
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    getImageCallback(requestCode,resultCode,data);
}

  public void getImageCallback(int requestCode, int resultCode, Intent data) {
    if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
        Uri imageUri = CropImage.getPickImageResultUri(this, data);
        // For API >= 23 we need to check specifically that we have permissions to read external storage.
        if (CropImage.isReadExternalStoragePermissionsRequired(this, imageUri)) {
            // request permissions and handle the result in onRequestPermissionsResult()
            mCropImageUri = imageUri;
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, CropImage.PICK_IMAGE_PERMISSIONS_REQUEST_CODE);
        } else {
            // no permissions required or already grunted, can start crop image activity
            startCropImageActivity(imageUri);
        }
    }
    else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {

        CropImage.ActivityResult result = CropImage.getActivityResult(data);
        if (resultCode == RESULT_OK) {
            Uri resultUri = result.getUri();
            profileImage.setImageURI(resultUri);

        }
    }
}

 private void startCropImageActivity(Uri imageUri) {
    CropImage.activity(imageUri).setGuidelines(CropImageView.Guidelines.ON).setCropShape(CropImageView.CropShape.OVAL).start(this);
}