问:
Bootstrap Material Design(4.1.1)'s bmd-label-floating not working well with autofocus attribute

1. On page load

The autofocus attribute doesn't trigger the Bootstrap-JavaScript to add the is-focused class to the corresponding (bmd-)form-group.

```<code><fieldset class="form-group bmd-form-group">
    <label for="usernameControl" class="bmd-label-floating">Username</label>
    <input type="text" class="form-control text-light" required="" id="usernameControl" name="username" autofocus="">
</fieldset>
</code>```

2. After some typing

When typing something in the field, the label goes up because is-filled gets added, but the focus is still not recognized.

```<code><fieldset class="form-group bmd-form-group is-filled">
    <label for="usernameControl" class="bmd-label-floating">Username</label>
    <input type="text" class="form-control text-light" required="" id="usernameControl" name="username" autofocus="">
</fieldset>
</code>```

3. After reselecting (desirable output)

Deselecting the text-input (with mouseclicks or the tab-key) and then selecting it again is the only way to get the is-focused class (and therefore making it look like it should).

```<code><fieldset class="form-group bmd-form-group is-filled is-focused">
    <label for="usernameControl" class="bmd-label-floating">Username</label>
    <input type="text" class="form-control text-light" required="" id="usernameControl" name="username" autofocus="">
</fieldset>
</code>```

Question

Is there any fix or workaround to this problem?

Bootstrap Material Design used: https://fezvrasta.github.io/bootstrap-material-design/ (Version 4.1.1)

Source/input html:

```<code><fieldset class="form-group">
    <label for="usernameControl" class="bmd-label-floating">Username</label>
    <input type="text" class="form-control text-light" required="" id="usernameControl" name="username" autofocus="">
</fieldset>
</code>```

答:
```<code><script> $('body').bootstrapMaterialDesign({}); </script>
</code>```

add this to your website if you're using https://fezvrasta.github.io/bootstrap-material-design This will fix forms etc.

Body:
1. On page load

The autofocus attribute doesn't trigger the Bootstrap-JavaScript to add the is-focused class to the corresponding (bmd-)form-group.

<fieldset class="form-group bmd-form-group">
    Username
    <input type="text" class="form-control text-light" required="" id="usernameControl" name="username" autofocus="">
</fieldset>

2. After some typing

When typing something in the field, the label goes up because is-filled gets added, but the focus is still not recognized.

<fieldset class="form-group bmd-form-group is-filled">
    Username
    <input type="text" class="form-control text-light" required="" id="usernameControl" name="username" autofocus="">
</fieldset>

3. After reselecting (desirable output)

Deselecting the text-input (with mouseclicks or the tab-key) and then selecting it again is the only way to get the is-focused class (and therefore making it look like it should).

<fieldset class="form-group bmd-form-group is-filled is-focused">
    Username
    <input type="text" class="form-control text-light" required="" id="usernameControl" name="username" autofocus="">
</fieldset>

Question

Is there any fix or workaround to this problem?

Bootstrap Material Design used: https://fezvrasta.github.io/bootstrap-material-design/ (Version 4.1.1)

Source/input html:

<fieldset class="form-group">
    Username
    <input type="text" class="form-control text-light" required="" id="usernameControl" name="username" autofocus="">
</fieldset>

Body:
<script> $('body').bootstrapMaterialDesign({}); </script>

add this to your website if you're using https://fezvrasta.github.io/bootstrap-material-design This will fix forms etc.


来源: stackexchange

问:
Tests not running in Test Explorer
I am currently working on a solution that has currently 32 Unittests. I have been working with the resharper test runner - which works fine. All tests are running, all tests are showing the right test outcome.

However, the tests are not running when using the Visual Studio test explorer.

The Test Explorer is showing all unit tests, but once clicking on "Run All", all tests are getting greyed out and show no result of the test run:

All test classes are public

All test classes are having the [TestClass] attribute declared

All test methods are using the [TestMethod] attribute

Both the productivity code and the test projects are targeting .NET 3.5.

I have already tried to clean build my solution, and / or delete all obj, bin, Debug and Release folders

I'd appreciate any hints which would explain this behaviour.

答: Clean-Rebuild solution worked for me.

ContentLicense: CC BY-SA 4.0

Title: Tests not running in Test Explorer

Body: Clean-Rebuild solution worked for me.


问:
Convert the tuples in a list to a dictionary and calculate the frequency
Three friends – Mike, John, and Tom – measured their jumps lengths in centimeters. We've stored their jump results in the template code. Create a dictionary named avg_results which will store the names as keys and their average jump lengths as values.

```<code>jumps = [('Mike', 283), ('Mike', 317), ('Mike', 302), ('John', 305), ('John', 311), ('John', 297), ('John', 308), ('Tom', 341), ('Tom', 256)]
</code>```

I only know how to calculate the sum of measure for each of them, but I don't know how to iterate and get the count of each of them.

```<code>for jump in jumps:
  name,length=jump
  dict_results[name]=dict_results.get(name,0)+length
</code>```

答:
Following is one possible solution using Dictionary based on this answer</p>

```<code>dct = {}

for i, j in jumps:
    group = dct.get(i, [])
    group.append(j)
    dct[i] = group

avg_results = {k:sum(v)/len(v) for k, v in dct.items()}
# {'Mike': 300.6666666666667, 'John': 305.25, 'Tom': 298.5}
</code>```

Body:
Three friends – Mike, John, and Tom – measured their jumps lengths in centimeters. We've stored their jump results in the template code. Create a dictionary named avg_results which will store the names as keys and their average jump lengths as values.

jumps = [('Mike', 283), ('Mike', 317), ('Mike', 302), ('John', 305), ('John', 311), ('John', 297), ('John', 308), ('Tom', 341), ('Tom', 256)]

I only know how to calculate the sum of measure for each of them, but I don't know how to iterate and get the count of each of them.

for jump in jumps:
  name,length=jump
  dict_results[name]=dict_results.get(name,0)+length

Body:
Following is one possible solution using Dictionary based on this answer

dct = {}

for i, j in jumps:
    group = dct.get(i, [])
    group.append(j)
    dct[i] = group

avg_results = {k:sum(v)/len(v) for k, v in dct.items()}
# {'Mike': 300.6666666666667, 'John': 305.25, 'Tom': 298.5}


问:
Xcode 10.1, 'Element' collides with 'XML.Accessor.Element'?
I need to add some minor changes to iOS app.

I inherited swift 3 code. which can not build on current Xcode 10.2.1

I almost managed to build it on Xcode 10.1 except for the following errors, in SwiftyXMLParser, Accessor.swift:

```<code>    public func makeIterator() -> AnyIterator<Accessor> {
        let generator: [Element]

        switch self {
        case .failure(_):
            generator = [Element]() // Error 2
        case .singleElement(let element):
            generator = [element] // Error 1.1
        case .sequence(let elements):
            generator = elements // Error 1.2
        }
        var index = 0
        return AnyIterator {
            let nextAccessor: Accessor?
            if index < generator.count {
                nextAccessor = Accessor(generator[index]) // Error 1.3
                index += 1
            } else {
                nextAccessor = nil
            }
            return nextAccessor
        }
    }
</code>```

Error 1.1: Cannot assign value of type '[XML.Element]' to type '[XML.Accessor.Element]' (aka 'Array')

  Error 1.2: Cannot assign value of type '[XML.Element]' to type '[XML.Accessor.Element]' (aka 'Array')

  Error 1.3: Cannot invoke initializer for type 'XML.Accessor' with an argument list of type '(XML.Accessor.Element)'

I changed the first line to

```<code>let generator: [XML.Element]
</code>```

as suggested in
https://github.com/yahoojapan/SwiftyXMLParser/issues/9
but I now get error 2:

Error 2: Cannot assign value of type '[XML.Accessor.Element]' (aka 'Array') to type '[XML.Element]'

How can I fix it, so I can build the project?

EDIT: when trying to archive the project, I get more errors as

```<code>Cannot convert value of type 'XML.Accessor.Element' (aka 'XML.Accessor') to expected argument type 'XML.Element'
</code>```

in the same SwiftyXMLParser, Accessor.swift file.

I solved these errors using XML.Element instead of just Element where needed.

答:
```<code>case .failure(_):
                generator = [] // instead of // generator = [Element]()
</code>```

<p>(It was worth to learn git, I just need to remember to use it features, as "look in the current source code", as @MartinR suggested</p>

Body:
I need to add some minor changes to iOS app.

I inherited swift 3 code. which can not build on current Xcode 10.2.1

I almost managed to build it on Xcode 10.1 except for the following errors, in SwiftyXMLParser, Accessor.swift:

    public func makeIterator() -> AnyIterator<Accessor> {
        let generator: [Element]

        switch self {
        case .failure(_):
            generator = [Element]() // Error 2
        case .singleElement(let element):
            generator = [element] // Error 1.1
        case .sequence(let elements):
            generator = elements // Error 1.2
        }
        var index = 0
        return AnyIterator {
            let nextAccessor: Accessor?
            if index < generator.count {
                nextAccessor = Accessor(generator[index]) // Error 1.3
                index += 1
            } else {
                nextAccessor = nil
            }
            return nextAccessor
        }
    }

Error 1.1: Cannot assign value of type '[XML.Element]' to type '[XML.Accessor.Element]' (aka 'Array')

  Error 1.2: Cannot assign value of type '[XML.Element]' to type '[XML.Accessor.Element]' (aka 'Array')

  Error 1.3: Cannot invoke initializer for type 'XML.Accessor' with an argument list of type '(XML.Accessor.Element)'

I changed the first line to

let generator: [XML.Element]

as suggested in
https://github.com/yahoojapan/SwiftyXMLParser/issues/9
but I now get error 2:

Error 2: Cannot assign value of type '[XML.Accessor.Element]' (aka 'Array') to type '[XML.Element]'

How can I fix it, so I can build the project?

EDIT: when trying to archive the project, I get more errors as

Cannot convert value of type 'XML.Accessor.Element' (aka 'XML.Accessor') to expected argument type 'XML.Element'

in the same SwiftyXMLParser, Accessor.swift file.

I solved these errors using XML.Element instead of just Element where needed.

Body:
case .failure(_):
                generator = [] // instead of // generator = [Element]()

(It was worth to learn git, I just need to remember to use it features, as "look in the current source code", as @MartinR suggested


问:
Stop angular cli asking for collecting analytics when I use ng build
Angluar CLI is asking the following question when I am trying to build and deploy my project using gitlab CI/CD:

> @angular/cli@8.0.0 postinstall /workspace/node_modules/@angular/cli
> node ./bin/postinstall/script.js

? Would you like to share anonymous usage data with the Angular Team at Google u
nder
Google’s Privacy Policy at https://policies.google.com/privacy? For more details
 and
how to change this setting, see http://angular.io/analytics. (y/N) ```

Of course I cannot input anything in the CI/CD pipeline. How can I can prevent angular cli from asking this question?

答:
I had the same problem: The new analytics feature of Angular CLI was blocking my CI: https://travis-ci.org/LVM-IT/lvo-logging-lib.
Solution: set the environent variable NG_CLI_ANALYTICS equal to ci

```<code>export NG_CLI_ANALYTICS=ci
</code>```

see: https://github.com/LVM-IT/lvo-logging-lib/blob/329d014aa34dea49522f036e8d0b3aa3f71e33e7/.travis.yml#L16

Link to ng-cli Analytics

Body:
Angluar CLI is asking the following question when I am trying to build and deploy my project using gitlab CI/CD:

> @angular/cli@8.0.0 postinstall /workspace/node_modules/@angular/cli
> node ./bin/postinstall/script.js

? Would you like to share anonymous usage data with the Angular Team at Google u
nder
Google’s Privacy Policy at https://policies.google.com/privacy? For more details
 and
how to change this setting, see http://angular.io/analytics. (y/N)

Of course I cannot input anything in the CI/CD pipeline. How can I can prevent angular cli from asking this question?

Body:
I had the same problem: The new analytics feature of Angular CLI was blocking my CI: https://travis-ci.org/LVM-IT/lvo-logging-lib.
Solution: set the environent variable NG_CLI_ANALYTICS equal to ci

export NG_CLI_ANALYTICS=ci

see: https://github.com/LVM-IT/lvo-logging-lib/blob/329d014aa34dea49522f036e8d0b3aa3f71e33e7/.travis.yml#L16

Link to ng-cli Analytics


问:
How to use AWSRequestSigningApacheInterceptor with AWS SDK2
I am trying to use REST calls to Neptune SPARQL on existing Java code which already uses Apache HTTP clients.   I'd like to not mix and match AWS SDK1 and SDK2 (which I use for the S3 portion of loading owl to Neptune).

I see these solutions:

AWSRequestSigningApacheInterceptor that works with SDK1, but can't find the equivalent in SDK2.

aws-request-signing-apache-interceptor on github for building an adaptor class so it can be used in SDK 2 with mix-and-match SDK 1 & 2

javaquery/Examples where Vicky Thakor has gone even more generic and just implemented the V4 signing for any Java REST implementation

But none of these is what I expected: an AWS or Apache implmentation of an Apache Interceptor for AWS SDK 2.

Is there such a thing? or is one of the above solutions the best available at the moment?

答: So, I settled on the second option with an important caveat: it does not handle AWS_SESSION_TOKEN.   This is a simple fix.  I've posted it along with the original answer at  http://github.com/awslabs/aws-request-signing-apache-interceptor/</p>


问:
What does the main thread do when run on ui thread is called from a normal thread (non ui)?
I have noticed that the main looper is called during animations, skipping over some animations if the ui thread is doing something labor intensive. One way of solving this problem is to run a thread or runnable or callable and then they join on the ui thread (automatically for callable, and manually by invoking the run on ui thread).

But does that mean that the ui thread may be interrupted during something important by the other threads?
Ie if the other thread returns some data but the ui is in the middle of doing something with the old data.

Short answer:
The main thread will finish what it is doing and will not be interupted, the other thread will post a runnable with the new data on the main thread and continue doing other stuff (if there are any), eventually the main thread will run the runnable containing the new data from the other thread.

答:
Try this:-</p>

```<code>runOnUiThread (new Thread(new Runnable() {
        public void run() {
            while(i++ < 1000){
                btn.setText("#"+i);
                try {
                    Thread.sleep(300);
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
         }
    }));
</code>```

Body:
Try this:-

runOnUiThread (new Thread(new Runnable() {
        public void run() {
            while(i++ < 1000){
                btn.setText("#"+i);
                try {
                    Thread.sleep(300);
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
         }
    }));


问:
In .NET, how do I Create a Junction in NTFS, as opposed to a Symlink?
I'm trying to create an NTFS Junction.  From the cmd line I can do this using the junction.exe tool from sysinternals.  The output of a DIR cmd for a junction looks like this:

```<code> Volume in drive C has no label.
 Volume Serial Number is C8BC-2EBD

 Directory of c:\users\cheeso\Documents

03/22/2009  09:45 PM    <JUNCTION>     My Music [\??\c:\users\cheeso\Music]
05/11/2007  05:42 PM    <DIR>          My Received Files
03/22/2009  09:46 PM    <JUNCTION>     my videos [\??\c:\users\cheeso\Videos]
</code>```

I read somewhere that Junctions are a subset of Symbolic Links.

So I tried using CreateSymbolicLink to create a Junction.  When I do this, I actually get a Symlink, not a junction.

```<code>09/09/2009  11:50 AM    <SYMLINKD>     newLink [.\]
</code>```

There is also CreateHardLink.  The doc there says junctions (aka "Reparse Points") are a subset of hardlinks. but I can't seem to get this call to work. It completes but there is no hardlink or junction created.

I'm using .NET/C# and the imports look like this:

```<code>    [Interop.DllImport("kernel32.dll", EntryPoint="CreateSymbolicLinkW", CharSet=Interop.CharSet.Unicode)]
    public static extern int CreateSymbolicLink(string lpSymlinkFileName, string lpTargetFileName, int dwFlags);

    [Interop.DllImport("kernel32.dll", EntryPoint="CreateHardLinkW", CharSet=Interop.CharSet.Unicode)]
    public static extern bool CreateHardLink(string lpFileName,
                                             string lpExistingFileName,
                                             IntPtr mustBeNull);
</code>```

What am I doing wrong?

How can I create a Junction from within C#?

答:
The code is from http://www.codeproject.com/KB/files/JunctionPointsNet.aspx as a shortcut for those who can not reach this link or a backup in case the original page is down.

Do not vote up this answser, since I'm not author of this code.

Thanks to the original author jeff.brown@codeproject.

```<code>using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32.SafeHandles;

namespace Monitor.Core.Utilities
{
    /// <summary>
    /// Provides access to NTFS junction points in .Net.
    /// </summary>
    public static class JunctionPoint
    {
        /// <summary>
        /// The file or directory is not a reparse point.
        /// </summary>
        private const int ERROR_NOT_A_REPARSE_POINT = 4390;

        /// <summary>
        /// The reparse point attribute cannot be set because it conflicts with an existing attribute.
        /// </summary>
        private const int ERROR_REPARSE_ATTRIBUTE_CONFLICT = 4391;

        /// <summary>
        /// The data present in the reparse point buffer is invalid.
        /// </summary>
        private const int ERROR_INVALID_REPARSE_DATA = 4392;

        /// <summary>
        /// The tag present in the reparse point buffer is invalid.
        /// </summary>
        private const int ERROR_REPARSE_TAG_INVALID = 4393;

        /// <summary>
        /// There is a mismatch between the tag specified in the request and the tag present in the reparse point.
        /// </summary>
        private const int ERROR_REPARSE_TAG_MISMATCH = 4394;

        /// <summary>
        /// Command to set the reparse point data block.
        /// </summary>
        private const int FSCTL_SET_REPARSE_POINT = 0x000900A4;

        /// <summary>
        /// Command to get the reparse point data block.
        /// </summary>
        private const int FSCTL_GET_REPARSE_POINT = 0x000900A8;

        /// <summary>
        /// Command to delete the reparse point data base.
        /// </summary>
        private const int FSCTL_DELETE_REPARSE_POINT = 0x000900AC;

        /// <summary>
        /// Reparse point tag used to identify mount points and junction points.
        /// </summary>
        private const uint IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003;

        /// <summary>
        /// This prefix indicates to NTFS that the path is to be treated as a non-interpreted
        /// path in the virtual file system.
        /// </summary>
        private const string NonInterpretedPathPrefix = @"\??\";

        [Flags]
        private enum EFileAccess : uint
        {
            GenericRead = 0x80000000,
            GenericWrite = 0x40000000,
            GenericExecute = 0x20000000,
            GenericAll = 0x10000000,
        }

        [Flags]
        private enum EFileShare : uint
        {
            None = 0x00000000,
            Read = 0x00000001,
            Write = 0x00000002,
            Delete = 0x00000004,
        }

        private enum ECreationDisposition : uint
        {
            New = 1,
            CreateAlways = 2,
            OpenExisting = 3,
            OpenAlways = 4,
            TruncateExisting = 5,
        }

        [Flags]
        private enum EFileAttributes : uint
        {
            Readonly = 0x00000001,
            Hidden = 0x00000002,
            System = 0x00000004,
            Directory = 0x00000010,
            Archive = 0x00000020,
            Device = 0x00000040,
            Normal = 0x00000080,
            Temporary = 0x00000100,
            SparseFile = 0x00000200,
            ReparsePoint = 0x00000400,
            Compressed = 0x00000800,
            Offline = 0x00001000,
            NotContentIndexed = 0x00002000,
            Encrypted = 0x00004000,
            Write_Through = 0x80000000,
            Overlapped = 0x40000000,
            NoBuffering = 0x20000000,
            RandomAccess = 0x10000000,
            SequentialScan = 0x08000000,
            DeleteOnClose = 0x04000000,
            BackupSemantics = 0x02000000,
            PosixSemantics = 0x01000000,
            OpenReparsePoint = 0x00200000,
            OpenNoRecall = 0x00100000,
            FirstPipeInstance = 0x00080000
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct REPARSE_DATA_BUFFER
        {
            /// <summary>
            /// Reparse point tag. Must be a Microsoft reparse point tag.
            /// </summary>
            public uint ReparseTag;

            /// <summary>
            /// Size, in bytes, of the data after the Reserved member. This can be calculated by:
            /// (4 * sizeof(ushort)) + SubstituteNameLength + PrintNameLength +
            /// (namesAreNullTerminated ? 2 * sizeof(char) : 0);
            /// </summary>
            public ushort ReparseDataLength;

            /// <summary>
            /// Reserved; do not use.
            /// </summary>
            public ushort Reserved;

            /// <summary>
            /// Offset, in bytes, of the substitute name string in the PathBuffer array.
            /// </summary>
            public ushort SubstituteNameOffset;

            /// <summary>
            /// Length, in bytes, of the substitute name string. If this string is null-terminated,
            /// SubstituteNameLength does not include space for the null character.
            /// </summary>
            public ushort SubstituteNameLength;

            /// <summary>
            /// Offset, in bytes, of the print name string in the PathBuffer array.
            /// </summary>
            public ushort PrintNameOffset;

            /// <summary>
            /// Length, in bytes, of the print name string. If this string is null-terminated,
            /// PrintNameLength does not include space for the null character.
            /// </summary>
            public ushort PrintNameLength;

            /// <summary>
            /// A buffer containing the unicode-encoded path string. The path string contains
            /// the substitute name string and print name string.
            /// </summary>
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x3FF0)]
            public byte[] PathBuffer;
        }

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern bool DeviceIoControl(IntPtr hDevice, uint dwIoControlCode,
            IntPtr InBuffer, int nInBufferSize,
            IntPtr OutBuffer, int nOutBufferSize,
            out int pBytesReturned, IntPtr lpOverlapped);

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern IntPtr CreateFile(
            string lpFileName,
            EFileAccess dwDesiredAccess,
            EFileShare dwShareMode,
            IntPtr lpSecurityAttributes,
            ECreationDisposition dwCreationDisposition,
            EFileAttributes dwFlagsAndAttributes,
            IntPtr hTemplateFile);

        /// <summary>
        /// Creates a junction point from the specified directory to the specified target directory.
        /// </summary>
        /// <remarks>
        /// Only works on NTFS.
        /// </remarks>
        /// <param name="junctionPoint">The junction point path</param>
        /// <param name="targetDir">The target directory</param>
        /// <param name="overwrite">If true overwrites an existing reparse point or empty directory</param>
        /// <exception cref="IOException">Thrown when the junction point could not be created or when
        /// an existing directory was found and <paramref name="overwrite" /> if false</exception>
        public static void Create(string junctionPoint, string targetDir, bool overwrite)
        {
            targetDir = Path.GetFullPath(targetDir);

            if (!Directory.Exists(targetDir))
                throw new IOException("Target path does not exist or is not a directory.");

            if (Directory.Exists(junctionPoint))
            {
                if (!overwrite)
                    throw new IOException("Directory already exists and overwrite parameter is false.");
            }
            else
            {
                Directory.CreateDirectory(junctionPoint);
            }

            using (SafeFileHandle handle = OpenReparsePoint(junctionPoint, EFileAccess.GenericWrite))
            {
                byte[] targetDirBytes = Encoding.Unicode.GetBytes(NonInterpretedPathPrefix + Path.GetFullPath(targetDir));

                REPARSE_DATA_BUFFER reparseDataBuffer = new REPARSE_DATA_BUFFER();

                reparseDataBuffer.ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
                reparseDataBuffer.ReparseDataLength = (ushort)(targetDirBytes.Length + 12);
                reparseDataBuffer.SubstituteNameOffset = 0;
                reparseDataBuffer.SubstituteNameLength = (ushort)targetDirBytes.Length;
                reparseDataBuffer.PrintNameOffset = (ushort)(targetDirBytes.Length + 2);
                reparseDataBuffer.PrintNameLength = 0;
                reparseDataBuffer.PathBuffer = new byte[0x3ff0];
                Array.Copy(targetDirBytes, reparseDataBuffer.PathBuffer, targetDirBytes.Length);

                int inBufferSize = Marshal.SizeOf(reparseDataBuffer);
                IntPtr inBuffer = Marshal.AllocHGlobal(inBufferSize);

                try
                {
                    Marshal.StructureToPtr(reparseDataBuffer, inBuffer, false);

                    int bytesReturned;
                    bool result = DeviceIoControl(handle.DangerousGetHandle(), FSCTL_SET_REPARSE_POINT,
                        inBuffer, targetDirBytes.Length + 20, IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero);

                    if (!result)
                        ThrowLastWin32Error("Unable to create junction point.");
                }
                finally
                {
                    Marshal.FreeHGlobal(inBuffer);
                }
            }
        }

        /// <summary>
        /// Deletes a junction point at the specified source directory along with the directory itself.
        /// Does nothing if the junction point does not exist.
        /// </summary>
        /// <remarks>
        /// Only works on NTFS.
        /// </remarks>
        /// <param name="junctionPoint">The junction point path</param>
        public static void Delete(string junctionPoint)
        {
            if (!Directory.Exists(junctionPoint))
            {
                if (File.Exists(junctionPoint))
                    throw new IOException("Path is not a junction point.");

                return;
            }

            using (SafeFileHandle handle = OpenReparsePoint(junctionPoint, EFileAccess.GenericWrite))
            {
                REPARSE_DATA_BUFFER reparseDataBuffer = new REPARSE_DATA_BUFFER();

                reparseDataBuffer.ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
                reparseDataBuffer.ReparseDataLength = 0;
                reparseDataBuffer.PathBuffer = new byte[0x3ff0];

                int inBufferSize = Marshal.SizeOf(reparseDataBuffer);
                IntPtr inBuffer = Marshal.AllocHGlobal(inBufferSize);
                try
                {
                    Marshal.StructureToPtr(reparseDataBuffer, inBuffer, false);

                    int bytesReturned;
                    bool result = DeviceIoControl(handle.DangerousGetHandle(), FSCTL_DELETE_REPARSE_POINT,
                        inBuffer, 8, IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero);

                    if (!result)
                        ThrowLastWin32Error("Unable to delete junction point.");
                }
                finally
                {
                    Marshal.FreeHGlobal(inBuffer);
                }

                try
                {
                    Directory.Delete(junctionPoint);
                }
                catch (IOException ex)
                {
                    throw new IOException("Unable to delete junction point.", ex);
                }
            }
        }

        /// <summary>
        /// Determines whether the specified path exists and refers to a junction point.
        /// </summary>
        /// <param name="path">The junction point path</param>
        /// <returns>True if the specified path represents a junction point</returns>
        /// <exception cref="IOException">Thrown if the specified path is invalid
        /// or some other error occurs</exception>
        public static bool Exists(string path)
        {
            if (! Directory.Exists(path))
                return false;

            using (SafeFileHandle handle = OpenReparsePoint(path, EFileAccess.GenericRead))
            {
                string target = InternalGetTarget(handle);
                return target != null;
            }
        }

        /// <summary>
        /// Gets the target of the specified junction point.
        /// </summary>
        /// <remarks>
        /// Only works on NTFS.
        /// </remarks>
        /// <param name="junctionPoint">The junction point path</param>
        /// <returns>The target of the junction point</returns>
        /// <exception cref="IOException">Thrown when the specified path does not
        /// exist, is invalid, is not a junction point, or some other error occurs</exception>
        public static string GetTarget(string junctionPoint)
        {
            using (SafeFileHandle handle = OpenReparsePoint(junctionPoint, EFileAccess.GenericRead))
            {
                string target = InternalGetTarget(handle);
                if (target == null)
                    throw new IOException("Path is not a junction point.");

                return target;
            }
        }

        private static string InternalGetTarget(SafeFileHandle handle)
        {
            int outBufferSize = Marshal.SizeOf(typeof(REPARSE_DATA_BUFFER));
            IntPtr outBuffer = Marshal.AllocHGlobal(outBufferSize);

            try
            {
                int bytesReturned;
                bool result = DeviceIoControl(handle.DangerousGetHandle(), FSCTL_GET_REPARSE_POINT,
                    IntPtr.Zero, 0, outBuffer, outBufferSize, out bytesReturned, IntPtr.Zero);

                if (!result)
                {
                    int error = Marshal.GetLastWin32Error();
                    if (error == ERROR_NOT_A_REPARSE_POINT)
                        return null;

                    ThrowLastWin32Error("Unable to get information about junction point.");
                }

                REPARSE_DATA_BUFFER reparseDataBuffer = (REPARSE_DATA_BUFFER)
                    Marshal.PtrToStructure(outBuffer, typeof(REPARSE_DATA_BUFFER));

                if (reparseDataBuffer.ReparseTag != IO_REPARSE_TAG_MOUNT_POINT)
                    return null;

                string targetDir = Encoding.Unicode.GetString(reparseDataBuffer.PathBuffer,
                    reparseDataBuffer.SubstituteNameOffset, reparseDataBuffer.SubstituteNameLength);

                if (targetDir.StartsWith(NonInterpretedPathPrefix))
                    targetDir = targetDir.Substring(NonInterpretedPathPrefix.Length);

                return targetDir;
            }
            finally
            {
                Marshal.FreeHGlobal(outBuffer);
            }
        }

        private static SafeFileHandle OpenReparsePoint(string reparsePoint, EFileAccess accessMode)
        {
            SafeFileHandle reparsePointHandle = new SafeFileHandle(CreateFile(reparsePoint, accessMode,
                EFileShare.Read | EFileShare.Write | EFileShare.Delete,
                IntPtr.Zero, ECreationDisposition.OpenExisting,
                EFileAttributes.BackupSemantics | EFileAttributes.OpenReparsePoint, IntPtr.Zero), true);

            if (Marshal.GetLastWin32Error() != 0)
                ThrowLastWin32Error("Unable to open reparse point.");

            return reparsePointHandle;
        }

        private static void ThrowLastWin32Error(string message)
        {
            throw new IOException(message, Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()));
        }
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to create an NTFS Junction.  From the cmd line I can do this using the junction.exe tool from sysinternals.  The output of a DIR cmd for a junction looks like this:

 Volume in drive C has no label.
 Volume Serial Number is C8BC-2EBD

 Directory of c:\users\cheeso\Documents

03/22/2009  09:45 PM    <JUNCTION>     My Music [\??\c:\users\cheeso\Music]
05/11/2007  05:42 PM    <DIR>          My Received Files
03/22/2009  09:46 PM    <JUNCTION>     my videos [\??\c:\users\cheeso\Videos]

I read somewhere that Junctions are a subset of Symbolic Links.

So I tried using CreateSymbolicLink to create a Junction.  When I do this, I actually get a Symlink, not a junction.

09/09/2009  11:50 AM    <SYMLINKD>     newLink [.\]

There is also CreateHardLink.  The doc there says junctions (aka "Reparse Points") are a subset of hardlinks. but I can't seem to get this call to work. It completes but there is no hardlink or junction created.

I'm using .NET/C# and the imports look like this:

    [Interop.DllImport("kernel32.dll", EntryPoint="CreateSymbolicLinkW", CharSet=Interop.CharSet.Unicode)]
    public static extern int CreateSymbolicLink(string lpSymlinkFileName, string lpTargetFileName, int dwFlags);

    [Interop.DllImport("kernel32.dll", EntryPoint="CreateHardLinkW", CharSet=Interop.CharSet.Unicode)]
    public static extern bool CreateHardLink(string lpFileName,
                                             string lpExistingFileName,
                                             IntPtr mustBeNull);

What am I doing wrong?

How can I create a Junction from within C#?

Body:
The code is from http://www.codeproject.com/KB/files/JunctionPointsNet.aspx as a shortcut for those who can not reach this link or a backup in case the original page is down.

Do not vote up this answser, since I'm not author of this code.

Thanks to the original author jeff.brown@codeproject.

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32.SafeHandles;

namespace Monitor.Core.Utilities
{
    /// <summary>
    /// Provides access to NTFS junction points in .Net.
    /// </summary>
    public static class JunctionPoint
    {
        /// <summary>
        /// The file or directory is not a reparse point.
        /// </summary>
        private const int ERROR_NOT_A_REPARSE_POINT = 4390;

        /// <summary>
        /// The reparse point attribute cannot be set because it conflicts with an existing attribute.
        /// </summary>
        private const int ERROR_REPARSE_ATTRIBUTE_CONFLICT = 4391;

        /// <summary>
        /// The data present in the reparse point buffer is invalid.
        /// </summary>
        private const int ERROR_INVALID_REPARSE_DATA = 4392;

        /// <summary>
        /// The tag present in the reparse point buffer is invalid.
        /// </summary>
        private const int ERROR_REPARSE_TAG_INVALID = 4393;

        /// <summary>
        /// There is a mismatch between the tag specified in the request and the tag present in the reparse point.
        /// </summary>
        private const int ERROR_REPARSE_TAG_MISMATCH = 4394;

        /// <summary>
        /// Command to set the reparse point data block.
        /// </summary>
        private const int FSCTL_SET_REPARSE_POINT = 0x000900A4;

        /// <summary>
        /// Command to get the reparse point data block.
        /// </summary>
        private const int FSCTL_GET_REPARSE_POINT = 0x000900A8;

        /// <summary>
        /// Command to delete the reparse point data base.
        /// </summary>
        private const int FSCTL_DELETE_REPARSE_POINT = 0x000900AC;

        /// <summary>
        /// Reparse point tag used to identify mount points and junction points.
        /// </summary>
        private const uint IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003;

        /// <summary>
        /// This prefix indicates to NTFS that the path is to be treated as a non-interpreted
        /// path in the virtual file system.
        /// </summary>
        private const string NonInterpretedPathPrefix = @"\??\";

        [Flags]
        private enum EFileAccess : uint
        {
            GenericRead = 0x80000000,
            GenericWrite = 0x40000000,
            GenericExecute = 0x20000000,
            GenericAll = 0x10000000,
        }

        [Flags]
        private enum EFileShare : uint
        {
            None = 0x00000000,
            Read = 0x00000001,
            Write = 0x00000002,
            Delete = 0x00000004,
        }

        private enum ECreationDisposition : uint
        {
            New = 1,
            CreateAlways = 2,
            OpenExisting = 3,
            OpenAlways = 4,
            TruncateExisting = 5,
        }

        [Flags]
        private enum EFileAttributes : uint
        {
            Readonly = 0x00000001,
            Hidden = 0x00000002,
            System = 0x00000004,
            Directory = 0x00000010,
            Archive = 0x00000020,
            Device = 0x00000040,
            Normal = 0x00000080,
            Temporary = 0x00000100,
            SparseFile = 0x00000200,
            ReparsePoint = 0x00000400,
            Compressed = 0x00000800,
            Offline = 0x00001000,
            NotContentIndexed = 0x00002000,
            Encrypted = 0x00004000,
            Write_Through = 0x80000000,
            Overlapped = 0x40000000,
            NoBuffering = 0x20000000,
            RandomAccess = 0x10000000,
            SequentialScan = 0x08000000,
            DeleteOnClose = 0x04000000,
            BackupSemantics = 0x02000000,
            PosixSemantics = 0x01000000,
            OpenReparsePoint = 0x00200000,
            OpenNoRecall = 0x00100000,
            FirstPipeInstance = 0x00080000
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct REPARSE_DATA_BUFFER
        {
            /// <summary>
            /// Reparse point tag. Must be a Microsoft reparse point tag.
            /// </summary>
            public uint ReparseTag;

            /// <summary>
            /// Size, in bytes, of the data after the Reserved member. This can be calculated by:
            /// (4 * sizeof(ushort)) + SubstituteNameLength + PrintNameLength +
            /// (namesAreNullTerminated ? 2 * sizeof(char) : 0);
            /// </summary>
            public ushort ReparseDataLength;

            /// <summary>
            /// Reserved; do not use.
            /// </summary>
            public ushort Reserved;

            /// <summary>
            /// Offset, in bytes, of the substitute name string in the PathBuffer array.
            /// </summary>
            public ushort SubstituteNameOffset;

            /// <summary>
            /// Length, in bytes, of the substitute name string. If this string is null-terminated,
            /// SubstituteNameLength does not include space for the null character.
            /// </summary>
            public ushort SubstituteNameLength;

            /// <summary>
            /// Offset, in bytes, of the print name string in the PathBuffer array.
            /// </summary>
            public ushort PrintNameOffset;

            /// <summary>
            /// Length, in bytes, of the print name string. If this string is null-terminated,
            /// PrintNameLength does not include space for the null character.
            /// </summary>
            public ushort PrintNameLength;

            /// <summary>
            /// A buffer containing the unicode-encoded path string. The path string contains
            /// the substitute name string and print name string.
            /// </summary>
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x3FF0)]
            public byte[] PathBuffer;
        }

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern bool DeviceIoControl(IntPtr hDevice, uint dwIoControlCode,
            IntPtr InBuffer, int nInBufferSize,
            IntPtr OutBuffer, int nOutBufferSize,
            out int pBytesReturned, IntPtr lpOverlapped);

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern IntPtr CreateFile(
            string lpFileName,
            EFileAccess dwDesiredAccess,
            EFileShare dwShareMode,
            IntPtr lpSecurityAttributes,
            ECreationDisposition dwCreationDisposition,
            EFileAttributes dwFlagsAndAttributes,
            IntPtr hTemplateFile);

        /// <summary>
        /// Creates a junction point from the specified directory to the specified target directory.
        /// </summary>
        /// <remarks>
        /// Only works on NTFS.
        /// </remarks>
        /// <param name="junctionPoint">The junction point path</param>
        /// <param name="targetDir">The target directory</param>
        /// <param name="overwrite">If true overwrites an existing reparse point or empty directory</param>
        /// <exception cref="IOException">Thrown when the junction point could not be created or when
        /// an existing directory was found and <paramref name="overwrite" /> if false</exception>
        public static void Create(string junctionPoint, string targetDir, bool overwrite)
        {
            targetDir = Path.GetFullPath(targetDir);

            if (!Directory.Exists(targetDir))
                throw new IOException("Target path does not exist or is not a directory.");

            if (Directory.Exists(junctionPoint))
            {
                if (!overwrite)
                    throw new IOException("Directory already exists and overwrite parameter is false.");
            }
            else
            {
                Directory.CreateDirectory(junctionPoint);
            }

            using (SafeFileHandle handle = OpenReparsePoint(junctionPoint, EFileAccess.GenericWrite))
            {
                byte[] targetDirBytes = Encoding.Unicode.GetBytes(NonInterpretedPathPrefix + Path.GetFullPath(targetDir));

                REPARSE_DATA_BUFFER reparseDataBuffer = new REPARSE_DATA_BUFFER();

                reparseDataBuffer.ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
                reparseDataBuffer.ReparseDataLength = (ushort)(targetDirBytes.Length + 12);
                reparseDataBuffer.SubstituteNameOffset = 0;
                reparseDataBuffer.SubstituteNameLength = (ushort)targetDirBytes.Length;
                reparseDataBuffer.PrintNameOffset = (ushort)(targetDirBytes.Length + 2);
                reparseDataBuffer.PrintNameLength = 0;
                reparseDataBuffer.PathBuffer = new byte[0x3ff0];
                Array.Copy(targetDirBytes, reparseDataBuffer.PathBuffer, targetDirBytes.Length);

                int inBufferSize = Marshal.SizeOf(reparseDataBuffer);
                IntPtr inBuffer = Marshal.AllocHGlobal(inBufferSize);

                try
                {
                    Marshal.StructureToPtr(reparseDataBuffer, inBuffer, false);

                    int bytesReturned;
                    bool result = DeviceIoControl(handle.DangerousGetHandle(), FSCTL_SET_REPARSE_POINT,
                        inBuffer, targetDirBytes.Length + 20, IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero);

                    if (!result)
                        ThrowLastWin32Error("Unable to create junction point.");
                }
                finally
                {
                    Marshal.FreeHGlobal(inBuffer);
                }
            }
        }

        /// <summary>
        /// Deletes a junction point at the specified source directory along with the directory itself.
        /// Does nothing if the junction point does not exist.
        /// </summary>
        /// <remarks>
        /// Only works on NTFS.
        /// </remarks>
        /// <param name="junctionPoint">The junction point path</param>
        public static void Delete(string junctionPoint)
        {
            if (!Directory.Exists(junctionPoint))
            {
                if (File.Exists(junctionPoint))
                    throw new IOException("Path is not a junction point.");

                return;
            }

            using (SafeFileHandle handle = OpenReparsePoint(junctionPoint, EFileAccess.GenericWrite))
            {
                REPARSE_DATA_BUFFER reparseDataBuffer = new REPARSE_DATA_BUFFER();

                reparseDataBuffer.ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
                reparseDataBuffer.ReparseDataLength = 0;
                reparseDataBuffer.PathBuffer = new byte[0x3ff0];

                int inBufferSize = Marshal.SizeOf(reparseDataBuffer);
                IntPtr inBuffer = Marshal.AllocHGlobal(inBufferSize);
                try
                {
                    Marshal.StructureToPtr(reparseDataBuffer, inBuffer, false);

                    int bytesReturned;
                    bool result = DeviceIoControl(handle.DangerousGetHandle(), FSCTL_DELETE_REPARSE_POINT,
                        inBuffer, 8, IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero);

                    if (!result)
                        ThrowLastWin32Error("Unable to delete junction point.");
                }
                finally
                {
                    Marshal.FreeHGlobal(inBuffer);
                }

                try
                {
                    Directory.Delete(junctionPoint);
                }
                catch (IOException ex)
                {
                    throw new IOException("Unable to delete junction point.", ex);
                }
            }
        }

        /// <summary>
        /// Determines whether the specified path exists and refers to a junction point.
        /// </summary>
        /// <param name="path">The junction point path</param>
        /// <returns>True if the specified path represents a junction point</returns>
        /// <exception cref="IOException">Thrown if the specified path is invalid
        /// or some other error occurs</exception>
        public static bool Exists(string path)
        {
            if (! Directory.Exists(path))
                return false;

            using (SafeFileHandle handle = OpenReparsePoint(path, EFileAccess.GenericRead))
            {
                string target = InternalGetTarget(handle);
                return target != null;
            }
        }

        /// <summary>
        /// Gets the target of the specified junction point.
        /// </summary>
        /// <remarks>
        /// Only works on NTFS.
        /// </remarks>
        /// <param name="junctionPoint">The junction point path</param>
        /// <returns>The target of the junction point</returns>
        /// <exception cref="IOException">Thrown when the specified path does not
        /// exist, is invalid, is not a junction point, or some other error occurs</exception>
        public static string GetTarget(string junctionPoint)
        {
            using (SafeFileHandle handle = OpenReparsePoint(junctionPoint, EFileAccess.GenericRead))
            {
                string target = InternalGetTarget(handle);
                if (target == null)
                    throw new IOException("Path is not a junction point.");

                return target;
            }
        }

        private static string InternalGetTarget(SafeFileHandle handle)
        {
            int outBufferSize = Marshal.SizeOf(typeof(REPARSE_DATA_BUFFER));
            IntPtr outBuffer = Marshal.AllocHGlobal(outBufferSize);

            try
            {
                int bytesReturned;
                bool result = DeviceIoControl(handle.DangerousGetHandle(), FSCTL_GET_REPARSE_POINT,
                    IntPtr.Zero, 0, outBuffer, outBufferSize, out bytesReturned, IntPtr.Zero);

                if (!result)
                {
                    int error = Marshal.GetLastWin32Error();
                    if (error == ERROR_NOT_A_REPARSE_POINT)
                        return null;

                    ThrowLastWin32Error("Unable to get information about junction point.");
                }

                REPARSE_DATA_BUFFER reparseDataBuffer = (REPARSE_DATA_BUFFER)
                    Marshal.PtrToStructure(outBuffer, typeof(REPARSE_DATA_BUFFER));

                if (reparseDataBuffer.ReparseTag != IO_REPARSE_TAG_MOUNT_POINT)
                    return null;

                string targetDir = Encoding.Unicode.GetString(reparseDataBuffer.PathBuffer,
                    reparseDataBuffer.SubstituteNameOffset, reparseDataBuffer.SubstituteNameLength);

                if (targetDir.StartsWith(NonInterpretedPathPrefix))
                    targetDir = targetDir.Substring(NonInterpretedPathPrefix.Length);

                return targetDir;
            }
            finally
            {
                Marshal.FreeHGlobal(outBuffer);
            }
        }

        private static SafeFileHandle OpenReparsePoint(string reparsePoint, EFileAccess accessMode)
        {
            SafeFileHandle reparsePointHandle = new SafeFileHandle(CreateFile(reparsePoint, accessMode,
                EFileShare.Read | EFileShare.Write | EFileShare.Delete,
                IntPtr.Zero, ECreationDisposition.OpenExisting,
                EFileAttributes.BackupSemantics | EFileAttributes.OpenReparsePoint, IntPtr.Zero), true);

            if (Marshal.GetLastWin32Error() != 0)
                ThrowLastWin32Error("Unable to open reparse point.");

            return reparsePointHandle;
        }

        private static void ThrowLastWin32Error(string message)
        {
            throw new IOException(message, Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()));
        }
    }
}


问:
How do I convert a data frame where some rows are duplicates except for one column
I have data on taxpayers which have multiple branches which produces multiple rows which are almost duplicates except for one relevant column (enterprise activity). I want to change this so that each taxpayer has only one row, which involves creating columns 'enterprise_activity_1', 'enterprise_activity_2' and so on.

I realise this is similar to reshaping but I can't think of a way to use tidyr::spread to achieve this.

For simplicity, say we just have a dataframe like:

df <- tibble::tibble(
  TAXPAYER_ID = c(100, 151, 250, 250, 267, 296, 296, 304),
  ENTERPRISE_ACTIVITY = rep(c("AGRICULTURE", "MANUFACTURING"), 4)
)
```

<p>What I would like to achieve is this:</p>

```TAXPAYER_ID ENTERPRISE_ACTIVITY_1   ENTERPRISE_ACTIVITY_2
100         AGRICULTURE             NA
151         MANUFACTURING           NA
250         AGRICULTURE             MANUFACTURING
267         AGRICULTURE             NA
296         MANUFACTURING           AGRICULTURE
304         MANUFACTURING           NA

```

My actual data has varying numbers of branches per taxpayer so the number of columns should be the maximum number of branches that one taxpayer has.

答:
Basically you need to group by the taxpayer ID, create a column to handle duplicated identifiers and spread, i.e.</p>

```<code>library(tidyverse)

df %>%
  group_by(TAXPAYER_ID) %>%
  mutate(ENTERPRISE_ACT = row_number()) %>%
  spread(key = ENTERPRISE_ACT, ENTERPRISE_ACTIVITY, sep = '_')

# A tibble: 6 x 3
# Groups:   TAXPAYER_ID [6]
#  TAXPAYER_ID ENTERPRISE_ACT_1 ENTERPRISE_ACT_2
#        <dbl> <chr>            <chr>
#1         100 AGRICULTURE      <NA>
#2         151 MANUFACTURING    <NA>
#3         250 AGRICULTURE      MANUFACTURING
#4         267 AGRICULTURE      <NA>
#5         296 MANUFACTURING    AGRICULTURE
#6         304 MANUFACTURING    <NA>
</code>```

Body:
I have data on taxpayers which have multiple branches which produces multiple rows which are almost duplicates except for one relevant column (enterprise activity). I want to change this so that each taxpayer has only one row, which involves creating columns 'enterprise_activity_1', 'enterprise_activity_2' and so on.

I realise this is similar to reshaping but I can't think of a way to use tidyr::spread to achieve this.

For simplicity, say we just have a dataframe like:

df <- tibble::tibble(
  TAXPAYER_ID = c(100, 151, 250, 250, 267, 296, 296, 304),
  ENTERPRISE_ACTIVITY = rep(c("AGRICULTURE", "MANUFACTURING"), 4)
)

What I would like to achieve is this:

TAXPAYER_ID ENTERPRISE_ACTIVITY_1   ENTERPRISE_ACTIVITY_2
100         AGRICULTURE             NA
151         MANUFACTURING           NA
250         AGRICULTURE             MANUFACTURING
267         AGRICULTURE             NA
296         MANUFACTURING           AGRICULTURE
304         MANUFACTURING           NA

My actual data has varying numbers of branches per taxpayer so the number of columns should be the maximum number of branches that one taxpayer has.

Body:
Basically you need to group by the taxpayer ID, create a column to handle duplicated identifiers and spread, i.e.

library(tidyverse)

df %>%
  group_by(TAXPAYER_ID) %>%
  mutate(ENTERPRISE_ACT = row_number()) %>%
  spread(key = ENTERPRISE_ACT, ENTERPRISE_ACTIVITY, sep = '_')

# A tibble: 6 x 3
# Groups:   TAXPAYER_ID [6]
#  TAXPAYER_ID ENTERPRISE_ACT_1 ENTERPRISE_ACT_2
#        <dbl> <chr>            <chr>
#1         100 AGRICULTURE      <NA>
#2         151 MANUFACTURING    <NA>
#3         250 AGRICULTURE      MANUFACTURING
#4         267 AGRICULTURE      <NA>
#5         296 MANUFACTURING    AGRICULTURE
#6         304 MANUFACTURING    <NA>


问:
Call External JavaScript Function
I have an ActionScript program that I want to access some external JavaScript functions. By external, I mean that the ActionScript/swf aren't going to be loaded via the HTML/JavaScript. Everything I see recommends ExternalInterface, but that seems to imply that your JS loads your swf. Is there a way to call a JavaScript function by URL?

答:
I'm not sure what do you mean by calling a JavaScript function by URL, what you probably need is a JSON based web interface / service.

How / where do you plan to run the Flash content if not embedded in the HTML? You'll need one place or an other to actually run that JS code, be it on client side in the browser or server side (in which case you need the webservice).

ContentLicense: CC BY-SA 3.0

Title: Call External JavaScript Function


问:
Values in one column based on condition in another column
I have a dataframe:

```<code>Data = {'group':  ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'],
        'value1': [2, 0, 0, 5, 5, 5, 6, 31, 7, 5, 0, 99],
        'value2': [25, 12 ,15, 11, 36, 3, 65, 6, 89, 8, 74, 5]
        }

current_result = pd.DataFrame(Data, columns = ['group','value1', 'value2'])
</code>```

I want to set value2 to zero if corresponding value1 is equal to zero while keeping all other values the same. So my desired result would be:

```<code>Data = {'group':  ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'],
        'value1': [2, 0, 0, 5, 5, 5, 6, 31, 7, 5, 0, 99],
        'value2': [25, 0 ,0, 11, 36, 3, 65, 6, 89, 8, 0, 5]
        }

current_result = pd.DataFrame(Data, columns = ['group','value1', 'value2'])
</code>```

How could I do this?

答:
Use df.loc[]

```<code>current_result.loc[current_result.value1.eq(0),'value2']=current_result.value1
print(current_result)
</code>```

```<code>   group  value1  value2
0      a       2      25
1      b       0       0
2      c       0       0
3      d       5      11
4      e       5      36
5      f       5       3
6      g       6      65
7      h      31       6
8      i       7      89
9      j       5       8
10     k       0       0
11     l      99       5
</code>```

Body:
I have a dataframe:

Data = {'group':  ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'],
        'value1': [2, 0, 0, 5, 5, 5, 6, 31, 7, 5, 0, 99],
        'value2': [25, 12 ,15, 11, 36, 3, 65, 6, 89, 8, 74, 5]
        }

current_result = pd.DataFrame(Data, columns = ['group','value1', 'value2'])

I want to set value2 to zero if corresponding value1 is equal to zero while keeping all other values the same. So my desired result would be:

Data = {'group':  ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'],
        'value1': [2, 0, 0, 5, 5, 5, 6, 31, 7, 5, 0, 99],
        'value2': [25, 0 ,0, 11, 36, 3, 65, 6, 89, 8, 0, 5]
        }

current_result = pd.DataFrame(Data, columns = ['group','value1', 'value2'])

How could I do this?

Body:
Use df.loc[]

current_result.loc[current_result.value1.eq(0),'value2']=current_result.value1
print(current_result)

   group  value1  value2
0      a       2      25
1      b       0       0
2      c       0       0
3      d       5      11
4      e       5      36
5      f       5       3
6      g       6      65
7      h      31       6
8      i       7      89
9      j       5       8
10     k       0       0
11     l      99       5


问:
React not reordering array of components on render
I am trying to render a list of components in order with react, the component is updating this array of elements but is not re-ordering them.

Pseudo code;

```<code>class Form extends Component {
  //
  // .... other initialization code and logic
  //

  updatePositions() {
    //
    // re-order this.state.page.page_contents
    //
    this.setState({ page: this.state.page });
  }

  renderContents() {
    return this.state.page.page_content.map((c, i) => {
      return (<ContentItem
        key={ i }
        content={ c }
      />);
    });
  }

  render() {
    return (
      <div className="row">
        <div className="medium-12 columns">
          { this.renderContents() }
        </div>
      </div>
    );
  }
}
</code>```

If i log out the results of page.page_content the items are being reordered in the array, however the form render is not re-rendering the contents in its new order

答:
you could try to force update    </p>

```<code> renderContents() {
          this.forceUpdate();
          return this.state.page.page_content.map((c, i) => {
              return (<ContentItem
                key={ i }
                content={ c }
              />);
            });

          }
</code>```

Body:
I am trying to render a list of components in order with react, the component is updating this array of elements but is not re-ordering them.

Pseudo code;

class Form extends Component {
  //
  // .... other initialization code and logic
  //

  updatePositions() {
    //
    // re-order this.state.page.page_contents
    //
    this.setState({ page: this.state.page });
  }

  renderContents() {
    return this.state.page.page_content.map((c, i) => {
      return (<ContentItem
        key={ i }
        content={ c }
      />);
    });
  }

  render() {
    return (

          { this.renderContents() }

    );
  }
}

If i log out the results of page.page_content the items are being reordered in the array, however the form render is not re-rendering the contents in its new order

Body:
you could try to force update

 renderContents() {
          this.forceUpdate();
          return this.state.page.page_content.map((c, i) => {
              return (<ContentItem
                key={ i }
                content={ c }
              />);
            });

          }


问:
Interfaces vs Types in TypeScript
What is the difference between these statements (interface vs type) in TypeScript?

```<code>interface X {
    a: number
    b: string
}

type X = {
    a: number
    b: string
};
</code>```

答:
Examples with Types:

// create a tree structure for an object. You can't do the same with interface because of lack of intersection (&)

```<code>type Tree<T> = T & { parent: Tree<T> };
</code>```

// type to restrict a variable to assign only a few values. Interfaces don't have union (|)

```<code>type Choise = "A" | "B" | "C";
</code>```

// thanks to types, you can declare NonNullable type thanks to a conditional mechanism.

```<code>type NonNullable<T> = T extends null | undefined ? never : T;
</code>```

Examples with Interface:

// you can use interface for OOP and use 'implements' to define object/class skeleton

```<code>interface IUser {
    user: string;
    password: string;
    login: (user: string, password: string) => boolean;
}

class User implements IUser {
    user = "user1"
    password = "password1"

    login(user: string, password: string) {
        return (user == user && password == password)
    }
}
</code>```

// you can extend interfaces with other interfaces

```<code>    interface IMyObject {
        label: string,
    }

    interface IMyObjectWithSize extends IMyObject{
        size?: number
    }
</code>```

Title: Interfaces vs Types in TypeScript

Body:
What is the difference between these statements (interface vs type) in TypeScript?

interface X {
    a: number
    b: string
}

type X = {
    a: number
    b: string
};

Body:
Examples with Types:

// create a tree structure for an object. You can't do the same with interface because of lack of intersection (&)

type Tree<T> = T & { parent: Tree<T> };

// type to restrict a variable to assign only a few values. Interfaces don't have union (|)

type Choise = "A" | "B" | "C";

// thanks to types, you can declare NonNullable type thanks to a conditional mechanism.

type NonNullable<T> = T extends null | undefined ? never : T;

Examples with Interface:

// you can use interface for OOP and use 'implements' to define object/class skeleton

interface IUser {
    user: string;
    password: string;
    login: (user: string, password: string) => boolean;
}

class User implements IUser {
    user = "user1"
    password = "password1"

    login(user: string, password: string) {
        return (user == user && password == password)
    }
}

// you can extend interfaces with other interfaces

    interface IMyObject {
        label: string,
    }

    interface IMyObjectWithSize extends IMyObject{
        size?: number
    }


答:
```<code>current_result.loc[current_result['value1'] == 0, 'value2'] = 0
</code>```

Title: Values in one column based on condition in another column


答:
You can multiple by boolean mask - True are processes like 1,False like 0 so compare for not equal 0 by Series.ne:

```<code>current_result['value2'] *= current_result['value1'].ne(0)
print (current_result)
   group  value1  value2
0      a       2      25
1      b       0       0
2      c       0       0
3      d       5      11
4      e       5      36
5      f       5       3
6      g       6      65
7      h      31       6
8      i       7      89
9      j       5       8
10     k       0       0
11     l      99       5
</code>```

Body:
You can multiple by boolean mask - True are processes like 1,False like 0 so compare for not equal 0 by Series.ne:

current_result['value2'] *= current_result['value1'].ne(0)
print (current_result)
   group  value1  value2
0      a       2      25
1      b       0       0
2      c       0       0
3      d       5      11
4      e       5      36
5      f       5       3
6      g       6      65
7      h      31       6
8      i       7      89
9      j       5       8
10     k       0       0
11     l      99       5


问:
how return to top button works
I have looked around many places  return to top  button .when i click on that that takes me to top of the page.

some time some links taking me to particular place how does this works

is this html tack ticks or javascript..can i do this without page loading ?

答:
```<code><a name="top">Top of the page</a>
...
<a href="#top">return to top</a>
</code>```

Note: HTML5 recommends using id="top" rather than name="top"

Title: how return to top button works

Body:
<a name="top">Top of the page</a>
...
<a href="#top">return to top</a>

Note: HTML5 recommends using id="top" rather than name="top"


问:
How to filter out all Upsertable entities in successfactors using postman?
I am learning about SuccessFactors employee central API's. I want to upsert entities using postman. But I cannot find any resource about how to filter out all entities which can be upserted. Is there any way to do it using postman? </p>

答: You can call $metadata (e.g. https://apisalesdemo4.successfactors.com/$metadata) and search for "sap:upsertable=true" or "sap:upsertable=false". If yes, this entity is upsertable. </p>


问:
How to export non-exportable private key from store
I need to export private key from Windows store. What should I do if the key is marked as non-exportable? I know that it is possible, program jailbreak can export this key.

To export key I use Org.BouncyCastle.Security.DotNetUtilities.GetKeyPair() that exports key from (RSACryptoServiceProvider)cryptoProv.ExportParameters(true). Exported key I use in Org.BouncyCastle.Cms.CmsSignedDataGenerator for CMS signature.

I need solution for .Net, but any solution will be useful. Thank you.

答:
There is code and binaries available here for a console app that can export private keys marked as non-exportable, and it won't trigger antivirus apps like mimikatz will.

The code is based on a paper by the NCC Group.
will need to run the tool with the local system account, as it works by writing directly to memory used by Windows' lsass process, in order to temporarily mark keys as exportable. This can be done using PsExec from SysInternals' PsTools:

Spawn a new command prompt running as the local system user:

PsExec64.exe -s -i cmd
```
</li>
<li><p>In the new command prompt, run the tool:</p>
<pre class="lang-bash prettyprint-override"><code>exportrsa.exe
</code>```

It will loop over every Local Computer store, searching for certificates with a private key. For each one, it will prompt you for a password - this is the password you want to secure the exported PFX file with, so can be whatever you want

Shortcuts to needed files:

Executable that you will need to download and run: https://github.com/luipir/ExportNotExportablePrivateKey/raw/eb2e2eeb49f424b89805c56ca7278c6d498af23d/exportrsa/Release/exportrsa.exe

You will also need the 32-bit, 2010 version of the "Microsoft Visual C++ Redistributable Packages", available here: https://www.microsoft.com/en-us/download/details.aspx?id=26999

Body:
There is code and binaries available here for a console app that can export private keys marked as non-exportable, and it won't trigger antivirus apps like mimikatz will.

The code is based on a paper by the NCC Group.
will need to run the tool with the local system account, as it works by writing directly to memory used by Windows' lsass process, in order to temporarily mark keys as exportable. This can be done using PsExec from SysInternals' PsTools:

Spawn a new command prompt running as the local system user:

PsExec64.exe -s -i cmd

In the new command prompt, run the tool:

exportrsa.exe

It will loop over every Local Computer store, searching for certificates with a private key. For each one, it will prompt you for a password - this is the password you want to secure the exported PFX file with, so can be whatever you want

Shortcuts to needed files:

Executable that you will need to download and run: https://github.com/luipir/ExportNotExportablePrivateKey/raw/eb2e2eeb49f424b89805c56ca7278c6d498af23d/exportrsa/Release/exportrsa.exe

You will also need the 32-bit, 2010 version of the "Microsoft Visual C++ Redistributable Packages", available here: https://www.microsoft.com/en-us/download/details.aspx?id=26999


问:
SweetAlert2 form validation does not return
Trying to use SweetAlert2 with a form sending confirmation. But no matter what I try, I can't get it to work.

```<code>Swal.fire({
  title: err_msg,
  //html: strCEmail,
  text: 'hello',
  type: 'question',
  showCancelButton: true,
  confirmButtonColor: '#3085d6',
  cancelButtonColor: '#d33',
  confirmButtonText: 'Yes, send it!'
}).then((result) => {
  if (result.value) {
    // xxxxxxxxxxxxxxxxxxxx
  }
});
</code>```

The code reachs the xxxxxxxxxxxxx fine, but whatever I put there doesn't trigger the form to submit.

I've tried the obvious

```<code>return true;
</code>```

But that didn't work. Then after some digging I found a suggestion to submit the form like this:

```<code>document.forms["myform"].submit();
</code>```

or
    form.submit();

Which didn't work.

So... what can I use to submit the form once the user has selected submit in SweetAlert2?

答:
Give id to your form

```<code><form action="your-action" method="post" id="my_form">
</code>```

In js:

```<code>Swal.fire({
  title: err_msg,
  text: 'hello',
  type: 'question',
  showCancelButton: true,
  confirmButtonColor: '#3085d6',
  cancelButtonColor: '#d33',
  confirmButtonText: 'Yes, send it!'
}).then((result) => {
  if (result.value) {
      $(document).find('#my_form').submit();
  }
});
</code>```

Body:
Trying to use SweetAlert2 with a form sending confirmation. But no matter what I try, I can't get it to work.

Swal.fire({
  title: err_msg,
  //html: strCEmail,
  text: 'hello',
  type: 'question',
  showCancelButton: true,
  confirmButtonColor: '#3085d6',
  cancelButtonColor: '#d33',
  confirmButtonText: 'Yes, send it!'
}).then((result) => {
  if (result.value) {
    // xxxxxxxxxxxxxxxxxxxx
  }
});

The code reachs the xxxxxxxxxxxxx fine, but whatever I put there doesn't trigger the form to submit.

I've tried the obvious

return true;

But that didn't work. Then after some digging I found a suggestion to submit the form like this:

document.forms["myform"].submit();

or
    form.submit();

Which didn't work.

So... what can I use to submit the form once the user has selected submit in SweetAlert2?

Body:
Give id to your form

<form action="your-action" method="post" id="my_form">

In js:

Swal.fire({
  title: err_msg,
  text: 'hello',
  type: 'question',
  showCancelButton: true,
  confirmButtonColor: '#3085d6',
  cancelButtonColor: '#d33',
  confirmButtonText: 'Yes, send it!'
}).then((result) => {
  if (result.value) {
      $(document).find('#my_form').submit();
  }
});


问:
$.ajax not working in IE, it is fine in Firefox
```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script language="javascript">

    function funcSendSMS(numbers, smsmessage)
    {
    alert(numbers);
      var num = numbers;
      var msg = smsmessage;
  $.ajax({
    type: "GET",
    url: "http://sms.vrksolutions.com/messageapi.asp",
    data: "username=xxxxxx&password=xxxxxx&sender=xxxxxx&mobile="+num+"&message="+msg,
    async: false,
    cache: false,
    success: function(resp){
      // we have the response
      alert("Server said:\n '" + resp + "'");
    },
    error: function(e){
      alert('Error: ' + e);
    }
  });
}
</script>
<script  language="javascript">
funcSendSMS('<?php echo $phnos ?>', '<?php echo $smsmsg;?>');
</script>
</code>```

I got below error in IE

Webpage error details

User Agent: Mozilla/4.0 (compatible;
  MSIE 7.0; Windows NT 6.1; Trident/4.0;
  GTB6.6; SLCC2; .NET CLR 2.0.50727;
  .NET CLR 3.5.30729; .NET CLR
  3.0.30729; Media Center PC 6.0; InfoPath.2) Timestamp: Tue, 12 Apr
  2011 13:22:58 UTC

Message: Access is denied.

Line: 138
Char: 355
Code: 0
URI: https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js

at this lane i found

below code in min.js file

```<code>A.src=b.url;if(!d){var C=false;A.onload=A.onreadystatechange=function(){
if(!C&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete"))
{C=true;c.handleSuccess(b,w,e,f);c.handleComplete(b,w,e,f);
A.onload=A.onreadystatechange=null;r&&A.parentNode&&r.removeChild(A)}}}
r.insertBefore(A,r.firstChild);return B}var J=false,w=b.xhr();
if(w){b.username?w.open(h,b.url,b.async,b.username,b.password)
:w.open(h,b.url,b.async);try{if(b.data!=null&&!l||a&&
a.contentType)w.setRequestHeader("Content-Type",
</code>```

答:
```<code>http://sms.vrksolutions.com/messageapi.asp
</code>```

I'm going to guess that it's a cross domain scripting issue. You can't do a regular AJAX call from one domain to another for security reasons. This article should set you straight on the security issues and how to get started with JSONP.

Body:
I got below error in IE

Webpage error details

User Agent: Mozilla/4.0 (compatible;
  MSIE 7.0; Windows NT 6.1; Trident/4.0;
  GTB6.6; SLCC2; .NET CLR 2.0.50727;
  .NET CLR 3.5.30729; .NET CLR
  3.0.30729; Media Center PC 6.0; InfoPath.2) Timestamp: Tue, 12 Apr
  2011 13:22:58 UTC

Message: Access is denied.

Line: 138
Char: 355
Code: 0
URI: https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js

at this lane i found

below code in min.js file

A.src=b.url;if(!d){var C=false;A.onload=A.onreadystatechange=function(){
if(!C&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete"))
{C=true;c.handleSuccess(b,w,e,f);c.handleComplete(b,w,e,f);
A.onload=A.onreadystatechange=null;r&&A.parentNode&&r.removeChild(A)}}}
r.insertBefore(A,r.firstChild);return B}var J=false,w=b.xhr();
if(w){b.username?w.open(h,b.url,b.async,b.username,b.password)
:w.open(h,b.url,b.async);try{if(b.data!=null&&!l||a&&
a.contentType)w.setRequestHeader("Content-Type",

Body:
http://sms.vrksolutions.com/messageapi.asp

I'm going to guess that it's a cross domain scripting issue. You can't do a regular AJAX call from one domain to another for security reasons. This article should set you straight on the security issues and how to get started with JSONP.


问:
'Invalid URI: The format of the URI could not be determined.' when calling aspx page from web api
I want to call a aspx page from my method so I use Redirect() method as bellow:

```<code>pubic calsss mainController:ApiController
{
    [HttpPost]
    public void postReport()
    {
         Redirect("/WebForm1.aspx");
    }
}
</code>```

but when I use it it shows this Exception :
'Invalid URI: The format of the URI could not be determined.'

my WebForm1.aspx is an internal page.
can some one help me to solve this problem?

Upadate:

my web config:

```<code>public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        config.Routes.MapHttpRoute(
            name: "withAction",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        config.Routes.MapHttpRoute(
            name: "noApi",
            routeTemplate: "{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}
</code>```

My project structure :

答:
Can you replace your code like this:</p>

```<code>return Redirect("~/Webform1.aspx");
</code>```

Body:
I want to call a aspx page from my method so I use Redirect() method as bellow:

pubic calsss mainController:ApiController
{
    [HttpPost]
    public void postReport()
    {
         Redirect("/WebForm1.aspx");
    }
}

but when I use it it shows this Exception :
'Invalid URI: The format of the URI could not be determined.'

my WebForm1.aspx is an internal page.
can some one help me to solve this problem?

Upadate:

my web config:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        config.Routes.MapHttpRoute(
            name: "withAction",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        config.Routes.MapHttpRoute(
            name: "noApi",
            routeTemplate: "{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

My project structure :

Body:
Can you replace your code like this:

return Redirect("~/Webform1.aspx");


问:
How to execute command for go group character in codemirror?
I am trying to execute the command goGroupLeftCtrl in codemirror and it is not working,

Other commands like goLineUp is working.

```<code>editor.execCommand('goGroupLeftCtrl');
</code>```

The cursor should move to left of the word. Do I need any special addons?
Thank you

答: I finally managed to solve the problem by using a different technique. Instead of using execCommand, I used keydown functionality with ctrlKey</p>

Body:
I am trying to execute the command goGroupLeftCtrl in codemirror and it is not working,

Other commands like goLineUp is working.

editor.execCommand('goGroupLeftCtrl');

The cursor should move to left of the word. Do I need any special addons?
Thank you


答:
Don't mutate this.state, directly. Bring it into a new variable and then add it back into state.

Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

from: https://reactjs.org/docs/react-component.html

Instead, you should try:

```<code>  updatePositions() {
    const page_contents = [...this.state.page.page_contents]
    // re order page_contents
    this.setState({ page: { page_contents });
  }
</code>```

Title: React not reordering array of components on render

Body:
Don't mutate this.state, directly. Bring it into a new variable and then add it back into state.

Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

from: https://reactjs.org/docs/react-component.html

Instead, you should try:

  updatePositions() {
    const page_contents = [...this.state.page.page_contents]
    // re order page_contents
    this.setState({ page: { page_contents });
  }


问:
Consuming HTTPS web service using WCF
I'm trying to consuming a client's web service using WCF. The client's web service is done over HTTPS, and I can consume it fine with the following Binding:

```<code><bindings>
  <basicHttpBinding>
    <binding name="PurchaseOrderSoap" closeTimeout="00:01:00" openTimeout="00:01:00"
        receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false"
        bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
        maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
        messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
        useDefaultWebProxy="true">
      <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
          maxBytesPerRead="4096" maxNameTableCharCount="16384" />
      <security mode="Transport" />
    </binding>
  </basicHttpBinding>
</bindings>
</code>```

However, our security team have told me I need to use Message or TransportWithMessageCredential security, because Fortify 360 complains that Transport security is too weak.

When I try Meesage I get this error:

```<code>System.InvalidOperationException: BasicHttp binding requires that
BasicHttpBinding.Security.Message.ClientCredentialType be equivalent to the
BasicHttpMessageCredentialType.Certificate credential type for secure messages. Select
Transport or TransportWithMessageCredential security for UserName credentials.
</code>```

And with TransportWithMessageCredential I get the following error:

```<code>System.InvalidOperationException: The username is not provided. Specify username in
ClientCredentials.
</code>```

I've not got a username/password (I can connect to it fine in my browser), so my question is:

Can I use Message or TransportWithMessageCredentials when consuming an existing HTTPS web service (without the publisher  making any changes)? If so, what changes do I need to make to my configuration?

Edited to clarify question.

答:
If you cannot get the third party vendor to add an endpoint to their service that supports message security then you are stuck. It seems they currently only support basicHttpBinding with transport level security.

Transport security is not "less" secure than message level security. Message level security means the contents of the soap message are encrypted. This allows you to either store or relay a message in a clear text way and still be assured no one can peek at the message. If all you are doing is communicating between your system and the vendor over the internet then transport and message level security are equally secure.

Title: Consuming HTTPS web service using WCF

Body:
I'm trying to consuming a client's web service using WCF. The client's web service is done over HTTPS, and I can consume it fine with the following Binding:

<bindings>
  <basicHttpBinding>
    <binding name="PurchaseOrderSoap" closeTimeout="00:01:00" openTimeout="00:01:00"
        receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false"
        bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
        maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
        messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
        useDefaultWebProxy="true">
      <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
          maxBytesPerRead="4096" maxNameTableCharCount="16384" />
      <security mode="Transport" />
    </binding>
  </basicHttpBinding>
</bindings>

However, our security team have told me I need to use Message or TransportWithMessageCredential security, because Fortify 360 complains that Transport security is too weak.

When I try Meesage I get this error:

System.InvalidOperationException: BasicHttp binding requires that
BasicHttpBinding.Security.Message.ClientCredentialType be equivalent to the
BasicHttpMessageCredentialType.Certificate credential type for secure messages. Select
Transport or TransportWithMessageCredential security for UserName credentials.

And with TransportWithMessageCredential I get the following error:

System.InvalidOperationException: The username is not provided. Specify username in
ClientCredentials.

I've not got a username/password (I can connect to it fine in my browser), so my question is:

Can I use Message or TransportWithMessageCredentials when consuming an existing HTTPS web service (without the publisher  making any changes)? If so, what changes do I need to make to my configuration?

Edited to clarify question.


问:
What does this error mean 'IndexError: index 0 is out of bounds for axis 0 with size 0'?
I'm following a tutorial to train a chatbot. However, I keep getting this error and I don't know what it means,
line 16, in
    last_unix = df.tail(1)['unix'].values[0]
IndexError: index 0 is out of bounds for axis 0 with size 0

Below is my code. line 16 is last_unix = df.tail(1)['unix'].values[0]

```<code>import sqlite3
import pandas as pd

timeframes = ['2015-01']

for timeframe in timeframes:
    connection = sqlite3.connect('/Users/danieldossantos/Desktop/Faisnet/RC_{}.db'.format(timeframe))
    c = connection.cursor()
    limit = 5000
    last_unix = 0
    cur_length = limit
    counter = 0
    test_done = False
    while cur_length == limit:
        df = pd.read_sql("SELECT * FROM parent_reply WHERE unix > {} AND parent NOT NULL AND score > 0 ORDER BY unix ASC LIMIT {}".format(last_unix, limit), connection)
        last_unix = df.tail(1)['unix'].values[0]
        cur_length = len(df)
        if not test_done:
            with open("test.from", 'a', encoding='utf8') as f:
                for content in df['parent'].values:
                    f.write(content+'\n')
            with open("test.to", 'a', encoding='utf8') as f:
                for content in df['comment'].values:
                    f.write(content+'\n')
            test_done = True

        else:
            with open("train.from", 'a', encoding='utf8') as f:
                for content in df['parent'].values:
                    f.write(content+'\n')
            with open("train.to", 'a', encoding='utf8') as f:
                for content in df['comment'].values:
                    f.write(content+'\n')

        counter += 1
        if counter % 20 == 0:
            print(counter*limit, 'rows completed so far')
</code>```

I tried adding

```<code>df = pd.read_sql(
            "SELECT * FROM parent_reply WHERE unix > {} AND parent NOT NULL AND parent != 'False' AND score > 0 ORDER BY unix ASC LIMIT {}".format( last_unix, limit), connection)
</code>```

But that did nothing

I'm supposed to be getting the number of rows completed.

答:
It simply means that there is no data returned when you run this df.tail(1)['unix'].values[0].

It gives an empty numpy array, so there is nothing at first position or 0th index.

What you can do after the pd.read_sql line is -

print(df.shape) to see the number of rows and columns returned by the query.

print(df.tail(1)['unix']) to see the unix column of the last row of the dataframe and check whether it has any value or not.

Body:
I'm following a tutorial to train a chatbot. However, I keep getting this error and I don't know what it means,
line 16, in
    last_unix = df.tail(1)['unix'].values[0]
IndexError: index 0 is out of bounds for axis 0 with size 0

Below is my code. line 16 is last_unix = df.tail(1)['unix'].values[0]

import sqlite3
import pandas as pd

timeframes = ['2015-01']

for timeframe in timeframes:
    connection = sqlite3.connect('/Users/danieldossantos/Desktop/Faisnet/RC_{}.db'.format(timeframe))
    c = connection.cursor()
    limit = 5000
    last_unix = 0
    cur_length = limit
    counter = 0
    test_done = False
    while cur_length == limit:
        df = pd.read_sql("SELECT * FROM parent_reply WHERE unix > {} AND parent NOT NULL AND score > 0 ORDER BY unix ASC LIMIT {}".format(last_unix, limit), connection)
        last_unix = df.tail(1)['unix'].values[0]
        cur_length = len(df)
        if not test_done:
            with open("test.from", 'a', encoding='utf8') as f:
                for content in df['parent'].values:
                    f.write(content+'\n')
            with open("test.to", 'a', encoding='utf8') as f:
                for content in df['comment'].values:
                    f.write(content+'\n')
            test_done = True

        else:
            with open("train.from", 'a', encoding='utf8') as f:
                for content in df['parent'].values:
                    f.write(content+'\n')
            with open("train.to", 'a', encoding='utf8') as f:
                for content in df['comment'].values:
                    f.write(content+'\n')

        counter += 1
        if counter % 20 == 0:
            print(counter*limit, 'rows completed so far')

I tried adding

df = pd.read_sql(
            "SELECT * FROM parent_reply WHERE unix > {} AND parent NOT NULL AND parent != 'False' AND score > 0 ORDER BY unix ASC LIMIT {}".format( last_unix, limit), connection)

But that did nothing

I'm supposed to be getting the number of rows completed.


问:
Oracle Query is not executing for Large volume without Stat Gathering even if the plan is good
Im processing a large volume using batch process ,Batch got stuck at particular query which involve a table (table is permanent but using for holding data temporary, table data will clear after processing ).Query plan was good and cost is very less .  If i gathered the table and index stat with the data and lock it  , query executes in seconds . But Query will again stuck when different nature of data comes. Is there any option available other than stat gathering to work this out .</p>

答: maybe you could try to use dynamic sampling (or dynamic statistics as the feature is labeled since Version 12): https://blogs.oracle.com/optimizer/dynamic-sampling-and-its-impact-on-the-optimizer. This would allow you to gather the statistics for every execution using a dynamic_sampling hint in your call.</p>


问:
AWS step function - Calls REST API
Is it possible to call the REST API from AWS step function?. I want to call the REST APIs that is available in Kubernetes container and thrid party API.</p>

答:
You would have to call your REST API from a Lambda function: a task state with a lambda function specified as a resource.

See Task - Lambda Functions.

Title: AWS step function - Calls REST API


问:
Is it possible to set view on the left side of ImageView using LinearLayouts?
Is it possible to place the views like that using nested LinearLayout's? The black rectangle will be an icon which will inform user about current weather (it can be sunny, rainy, cloudy etc)

答:
Solved, if someone is curious about code

```<code><LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".hourly_menu"
android:orientation="horizontal">

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="20°C"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1111 HPA"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="11%"/>
</LinearLayout>

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="57dp"
    android:src="@drawable/day_clear_sky"/>
</code>```

Body:
Solved, if someone is curious about code

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".hourly_menu"
android:orientation="horizontal">

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="20°C"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1111 HPA"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="11%"/>
</LinearLayout>

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="57dp"
    android:src="@drawable/day_clear_sky"/>


问:
Where is index.g.cshtml
I am trying to work through this tutorial, ASP.Net Core Razor Pages, but (often) when I build the solution, I get a CS0234 error stating that a namespace is missing from file Index.g.cshtml.cd, but where does this file exist?

I have tried

All the build/clean/rebuild solution options.

I have restarted Visual Studio

I have deleted the DEBUG files and restarted VS and FINALLY

I have restarted my PC.
The ONLY solution that seems to work, is to delete the entire solution/project and start again.

Surely there must be a fix for this?
Can you assist?

答:
If an error says a using directive or namespace is missing from xxx.g.cshtml.cs, that usually means, that there is a directive directly in the view (.cshtml or .vbhtml), that the compiler cannot resolve.

In my case I had  the following statement in a partial view:

```<code>@inject UserManager<AppUser> UserManager
</code>```

I then went along and refactored the AppUser class from the web application Namespace.Web.AppUser into Namespace.Entities.AppUser, which then was causing that error.

There are different ways to resolve this.
The easiest way is to use a fully qualified type namespace:

```<code>@inject UserManager<Namespace.Entities.AppUser> UserManager
</code>```

And do not forget to add a reference to the other project, if it is in another project.
Or: add a using statement:

```<code>@using Namespace.Entities;
</code>```

Or: Add the using statement above to your ~\Views\_ViewStart.cshtml. This will make that class available in all views.

Title: Where is index.g.cshtml

Body:
If an error says a using directive or namespace is missing from xxx.g.cshtml.cs, that usually means, that there is a directive directly in the view (.cshtml or .vbhtml), that the compiler cannot resolve.

In my case I had  the following statement in a partial view:

@inject UserManager<AppUser> UserManager

I then went along and refactored the AppUser class from the web application Namespace.Web.AppUser into Namespace.Entities.AppUser, which then was causing that error.

There are different ways to resolve this.
The easiest way is to use a fully qualified type namespace:

@inject UserManager<Namespace.Entities.AppUser> UserManager

And do not forget to add a reference to the other project, if it is in another project.
Or: add a using statement:

@using Namespace.Entities;

Or: Add the using statement above to your ~\Views\_ViewStart.cshtml. This will make that class available in all views.


问:
How can I combine the Properties of two arrays?
I have made a for loop that makes dots. Now I want to color them in a specific way. Like the first 200 are black and the next 326 are blue. I already managed that, but now I have so many rows of code and I wonder if there is a cleaner way to do it. For example make an array for the colors and then make an array for the values? </p>

```<code>let circleColor = 'Lavender ';
const secondColor = 'burlyWood ';
const numberFirstColor = 493;
const numberSecondColor = numberFirstColor+578;
for (let i = 0; i < circleCount; i++) {
if (i > numberFirstColor) circleColor = secondColor;
if ( i > numberSecondColor) circleColor= thirdColor;
</code>```

答:
Another, bit more functional way would be to generate an array and then populate it with colors:

```<code>Array(circleCount)
  .fill()
  .map((_, idx) => idx < numberFirstColor ? circleColor : secondColor);

</code>```

Then you can iterate over you array and get the color for your item.

Body:
I have made a for loop that makes dots. Now I want to color them in a specific way. Like the first 200 are black and the next 326 are blue. I already managed that, but now I have so many rows of code and I wonder if there is a cleaner way to do it. For example make an array for the colors and then make an array for the values?

let circleColor = 'Lavender ';
const secondColor = 'burlyWood ';
const numberFirstColor = 493;
const numberSecondColor = numberFirstColor+578;
for (let i = 0; i < circleCount; i++) {
if (i > numberFirstColor) circleColor = secondColor;
if ( i > numberSecondColor) circleColor= thirdColor;

Body:
Another, bit more functional way would be to generate an array and then populate it with colors:

Array(circleCount)
  .fill()
  .map((_, idx) => idx < numberFirstColor ? circleColor : secondColor);

Then you can iterate over you array and get the color for your item.