问:
Xamarin Android PCL Web Request Hangs
I am trying to make a PCL that can make web requests for a Xamarin Android project.

My AndoridManifest.xml looks like as follows

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="JJJ.Mobile.Android" android:installLocation="auto">
    <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="23" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <application android:allowBackup="true" android:label="@string/app_name" android:theme="@style/MyTheme"></application>
</manifest>
</code>```

The code in the Android main activity button click just calls this PCL Create method directly.

I have breakpoints on the lines where it does SendAsync and where returns null, the SendAsync breakpoint gets hit and when you step over it VS hangs for a second then the Emulator is displayed and the app is hanging - Android displays soon after a message about not responding to wait or not - the exception breakpoint never gets hit. No exception is shown in the console

```<code>public async Task<HttpResponseMessage> Create()
        {
            try
            {
                var uri = new Uri("http://rxnav.nlm.nih.gov/REST/RxTerms/rxcui/198440/allinfo");

                var httpClient = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri);

                var response = await httpClient.SendAsync(request);
                return response;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
</code>```

The console output after button clicked, not sure if it's helpful or not

```<code>Thread started:  #6
03-30 19:31:17.669 D/Mono    ( 2556): Assembly Ref addref System.Net.Http[0x9d63d4e0] -> System.Core[0x9e0abbe0]: 10
Thread started: <Thread Pool> #7
03-30 19:31:18.392 D/Mono    ( 2556): [0x9d7bf930] hill climbing, change max number of threads 3
Thread started: <Thread Pool> #8
03-30 19:31:18.490 D/Mono    ( 2556): [0x9adbf930] worker starting
03-30 19:31:18.538 D/Mono    ( 2556): Unloading image System.dll [0x9ae04f00].
03-30 19:31:18.539 D/Mono    ( 2556): Image addref System[0xaed95740] -> System.dll[0xaadd4900]: 5
03-30 19:31:18.539 D/Mono    ( 2556): Config attempting to parse: 'System.dll.config'.
03-30 19:31:18.539 D/Mono    ( 2556): Config attempting to parse: '/Users/builder/data/lanes/4009/3a62f1ea/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System/System.config'.
03-30 19:31:18.540 D/Mono    ( 2556): Unloading image System.dll [0x9ae04f00].
03-30 19:31:18.540 D/Mono    ( 2556): Image addref System[0xaed95920] -> System.dll[0xaadd4900]: 6
03-30 19:31:18.541 D/Mono    ( 2556): Config attempting to parse: 'System.dll.config'.
03-30 19:31:18.541 D/Mono    ( 2556): Config attempting to parse: '/Users/builder/data/lanes/4009/3a62f1ea/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System/System.config'.
03-30 19:31:18.543 D/Mono    ( 2556): Unloading image System.dll [0x9ae04f00].
03-30 19:31:18.543 D/Mono    ( 2556): Image addref System[0xaed95920] -> System.dll[0xaadd4900]: 7
03-30 19:31:18.543 D/Mono    ( 2556): Config attempting to parse: 'System.dll.config'.
03-30 19:31:18.543 D/Mono    ( 2556): Config attempting to parse: '/Users/builder/data/lanes/4009/3a62f1ea/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System/System.config'.
03-30 19:31:18.545 D/Mono    ( 2556): Unloading image System.dll [0x9ae04f00].
03-30 19:31:18.545 D/Mono    ( 2556): Image addref System[0xaed95920] -> System.dll[0xaadd4900]: 8
03-30 19:31:18.545 D/Mono    ( 2556): Config attempting to parse: 'System.dll.config'.
03-30 19:31:18.545 D/Mono    ( 2556): Config attempting to parse: '/Users/builder/data/lanes/4009/3a62f1ea/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System/System.config'.
03-30 19:31:18.573 D/Mono    ( 2556): DllImport searching in: '__Internal' ('(null)').
03-30 19:31:18.573 D/Mono    ( 2556): Searching for 'java_interop_jnienv_is_assignable_from'.
03-30 19:31:18.573 D/Mono    ( 2556): Probing 'java_interop_jnienv_is_assignable_from'.
03-30 19:31:18.573 D/Mono    ( 2556): Found as 'java_interop_jnienv_is_assignable_from'.
03-30 19:31:18.574 D/Mono    ( 2556): DllImport searching in: '__Internal' ('(null)').
03-30 19:31:18.574 D/Mono    ( 2556): Searching for 'java_interop_jnienv_get_byte_array_region'.
03-30 19:31:18.574 D/Mono    ( 2556): Probing 'java_interop_jnienv_get_byte_array_region'.
03-30 19:31:18.574 D/Mono    ( 2556): Found as 'java_interop_jnienv_get_byte_array_region'.
03-30 19:31:18.575 D/Mono    ( 2556): DllImport searching in: '__Internal' ('(null)').
03-30 19:31:18.575 D/Mono    ( 2556): Searching for 'java_interop_jnienv_set_byte_array_region'.
03-30 19:31:18.575 D/Mono    ( 2556): Probing 'java_interop_jnienv_set_byte_array_region'.
03-30 19:31:18.575 D/Mono    ( 2556): Found as 'java_interop_jnienv_set_byte_array_region'.
03-30 19:31:18.632 W/Mono    ( 2556): The request to load the assembly System.Core v4.0.0.0 was remapped to v2.0.5.0
03-30 19:31:18.632 D/Mono    ( 2556): Unloading image System.Core.dll [0x9ae06d00].
03-30 19:31:18.632 D/Mono    ( 2556): Image addref System.Core[0xaed96460] -> System.Core.dll[0xaadd6700]: 5
03-30 19:31:18.632 D/Mono    ( 2556): Config attempting to parse: 'System.Core.dll.config'.
03-30 19:31:18.632 D/Mono    ( 2556): Config attempting to parse: '/Users/builder/data/lanes/4009/3a62f1ea/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System.Core/System.Core.config'.
03-30 19:31:18.640 W/Mono    ( 2556): The request to load the assembly System.Core v4.0.0.0 was remapped to v2.0.5.0
03-30 19:31:18.641 D/Mono    ( 2556): Unloading image System.Core.dll [0x9ae05e00].
03-30 19:31:18.641 D/Mono    ( 2556): Image addref System.Core[0xaed96460] -> System.Core.dll[0xaadd6700]: 6
03-30 19:31:18.641 D/Mono    ( 2556): Config attempting to parse: 'System.Core.dll.config'.
03-30 19:31:18.641 D/Mono    ( 2556): Config attempting to parse: '/Users/builder/data/lanes/4009/3a62f1ea/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System.Core/System.Core.config'.
03-30 19:31:18.895 D/Mono    ( 2556): [0x9d7bf930] hill climbing, change max number of threads 2
03-30 19:31:24.114 D/Mono    ( 2556): [0x9adbf930] worker finishing
Thread finished: <Thread Pool> #8
The thread 'Unknown' (0x8) has exited with code 0 (0x0).
</code>```

The emulator is running Android 6, I've checked the internet by using the built in browser and it works. I am really confused about this, any help would be greatly appreciated!

答:
I assume that you're running out of memory which is forcing your task to terminate. I used the code below and all is working as expected. I setup the project as a Xamarin.Android project with a Xamarin.PCL for the request portion. I also created a mock model for getting the response in a cleaner fashion. I don't really know what you're doing with the XML so you could omit that part if it is not relevant.

Project Setup

Nuget Packages Installed in the PCL

ModernHttpClient

Newtonsoft.Json

Main Activity

Below is the Android Main Activity

```<code>using Android.App;
using Android.OS;
using XamPCL;

namespace App1
{
    [Activity(Label = "App1", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        protected override async void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

                var n = new XamPCLa();
                //you want to await this function.
                Model response = await n.Test();
        }
    }
}
</code>```

Xamarin.Portable (XamPCL)

```<code>using ModernHttpClient;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace XamPCL
{
    public class Model
    {
        /// <summary>
        /// this will resolve your xml into the model
        /// </summary>
        [JsonProperty(PropertyName = "rxtermsProperties")]
        public DrugSpec Container {get;set;}
    }

    public class DrugSpec
    {
        /// <summary>
        ///
        /// </summary>
        [JsonProperty(PropertyName = "displayName")]
        public string DisplayName { get; set; }
    }

    public class XamPCLa
    {
        public XamPCLa()
        {

        }

        public async Task<Model> Test()
        {
            var httpClient = GetHttpClient();
            try
            {
                var response = await httpClient.GetAsync(@"https://rxnav.nlm.nih.gov/REST/RxTerms/rxcui/198440/allinfo").ConfigureAwait(false);
                response.EnsureSuccessStatusCode();

                if (response.IsSuccessStatusCode)
                {
                    var content = response.Content;

                    string jsonString = await content.ReadAsStringAsync().ConfigureAwait(false);

                    return JsonConvert.DeserializeObject<Model>(jsonString);
                }
            }
            catch (Exception e)
            {

            }
            return new Model();
        }

        private HttpClient GetHttpClient()
        {
            var httpClient = new HttpClient(new NativeMessageHandler());

            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            return httpClient;
        }
    }
}
</code>```

Result in MainActivity

Title: Xamarin Android PCL Web Request Hangs

Body:
I am trying to make a PCL that can make web requests for a Xamarin Android project.

My AndoridManifest.xml looks like as follows

<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="JJJ.Mobile.Android" android:installLocation="auto">
    <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="23" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <application android:allowBackup="true" android:label="@string/app_name" android:theme="@style/MyTheme"></application>
</manifest>

The code in the Android main activity button click just calls this PCL Create method directly.

I have breakpoints on the lines where it does SendAsync and where returns null, the SendAsync breakpoint gets hit and when you step over it VS hangs for a second then the Emulator is displayed and the app is hanging - Android displays soon after a message about not responding to wait or not - the exception breakpoint never gets hit. No exception is shown in the console

public async Task<HttpResponseMessage> Create()
        {
            try
            {
                var uri = new Uri("http://rxnav.nlm.nih.gov/REST/RxTerms/rxcui/198440/allinfo");

                var httpClient = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri);

                var response = await httpClient.SendAsync(request);
                return response;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

The console output after button clicked, not sure if it's helpful or not

Thread started:  #6
03-30 19:31:17.669 D/Mono    ( 2556): Assembly Ref addref System.Net.Http[0x9d63d4e0] -> System.Core[0x9e0abbe0]: 10
Thread started: <Thread Pool> #7
03-30 19:31:18.392 D/Mono    ( 2556): [0x9d7bf930] hill climbing, change max number of threads 3
Thread started: <Thread Pool> #8
03-30 19:31:18.490 D/Mono    ( 2556): [0x9adbf930] worker starting
03-30 19:31:18.538 D/Mono    ( 2556): Unloading image System.dll [0x9ae04f00].
03-30 19:31:18.539 D/Mono    ( 2556): Image addref System[0xaed95740] -> System.dll[0xaadd4900]: 5
03-30 19:31:18.539 D/Mono    ( 2556): Config attempting to parse: 'System.dll.config'.
03-30 19:31:18.539 D/Mono    ( 2556): Config attempting to parse: '/Users/builder/data/lanes/4009/3a62f1ea/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System/System.config'.
03-30 19:31:18.540 D/Mono    ( 2556): Unloading image System.dll [0x9ae04f00].
03-30 19:31:18.540 D/Mono    ( 2556): Image addref System[0xaed95920] -> System.dll[0xaadd4900]: 6
03-30 19:31:18.541 D/Mono    ( 2556): Config attempting to parse: 'System.dll.config'.
03-30 19:31:18.541 D/Mono    ( 2556): Config attempting to parse: '/Users/builder/data/lanes/4009/3a62f1ea/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System/System.config'.
03-30 19:31:18.543 D/Mono    ( 2556): Unloading image System.dll [0x9ae04f00].
03-30 19:31:18.543 D/Mono    ( 2556): Image addref System[0xaed95920] -> System.dll[0xaadd4900]: 7
03-30 19:31:18.543 D/Mono    ( 2556): Config attempting to parse: 'System.dll.config'.
03-30 19:31:18.543 D/Mono    ( 2556): Config attempting to parse: '/Users/builder/data/lanes/4009/3a62f1ea/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System/System.config'.
03-30 19:31:18.545 D/Mono    ( 2556): Unloading image System.dll [0x9ae04f00].
03-30 19:31:18.545 D/Mono    ( 2556): Image addref System[0xaed95920] -> System.dll[0xaadd4900]: 8
03-30 19:31:18.545 D/Mono    ( 2556): Config attempting to parse: 'System.dll.config'.
03-30 19:31:18.545 D/Mono    ( 2556): Config attempting to parse: '/Users/builder/data/lanes/4009/3a62f1ea/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System/System.config'.
03-30 19:31:18.573 D/Mono    ( 2556): DllImport searching in: '__Internal' ('(null)').
03-30 19:31:18.573 D/Mono    ( 2556): Searching for 'java_interop_jnienv_is_assignable_from'.
03-30 19:31:18.573 D/Mono    ( 2556): Probing 'java_interop_jnienv_is_assignable_from'.
03-30 19:31:18.573 D/Mono    ( 2556): Found as 'java_interop_jnienv_is_assignable_from'.
03-30 19:31:18.574 D/Mono    ( 2556): DllImport searching in: '__Internal' ('(null)').
03-30 19:31:18.574 D/Mono    ( 2556): Searching for 'java_interop_jnienv_get_byte_array_region'.
03-30 19:31:18.574 D/Mono    ( 2556): Probing 'java_interop_jnienv_get_byte_array_region'.
03-30 19:31:18.574 D/Mono    ( 2556): Found as 'java_interop_jnienv_get_byte_array_region'.
03-30 19:31:18.575 D/Mono    ( 2556): DllImport searching in: '__Internal' ('(null)').
03-30 19:31:18.575 D/Mono    ( 2556): Searching for 'java_interop_jnienv_set_byte_array_region'.
03-30 19:31:18.575 D/Mono    ( 2556): Probing 'java_interop_jnienv_set_byte_array_region'.
03-30 19:31:18.575 D/Mono    ( 2556): Found as 'java_interop_jnienv_set_byte_array_region'.
03-30 19:31:18.632 W/Mono    ( 2556): The request to load the assembly System.Core v4.0.0.0 was remapped to v2.0.5.0
03-30 19:31:18.632 D/Mono    ( 2556): Unloading image System.Core.dll [0x9ae06d00].
03-30 19:31:18.632 D/Mono    ( 2556): Image addref System.Core[0xaed96460] -> System.Core.dll[0xaadd6700]: 5
03-30 19:31:18.632 D/Mono    ( 2556): Config attempting to parse: 'System.Core.dll.config'.
03-30 19:31:18.632 D/Mono    ( 2556): Config attempting to parse: '/Users/builder/data/lanes/4009/3a62f1ea/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System.Core/System.Core.config'.
03-30 19:31:18.640 W/Mono    ( 2556): The request to load the assembly System.Core v4.0.0.0 was remapped to v2.0.5.0
03-30 19:31:18.641 D/Mono    ( 2556): Unloading image System.Core.dll [0x9ae05e00].
03-30 19:31:18.641 D/Mono    ( 2556): Image addref System.Core[0xaed96460] -> System.Core.dll[0xaadd6700]: 6
03-30 19:31:18.641 D/Mono    ( 2556): Config attempting to parse: 'System.Core.dll.config'.
03-30 19:31:18.641 D/Mono    ( 2556): Config attempting to parse: '/Users/builder/data/lanes/4009/3a62f1ea/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System.Core/System.Core.config'.
03-30 19:31:18.895 D/Mono    ( 2556): [0x9d7bf930] hill climbing, change max number of threads 2
03-30 19:31:24.114 D/Mono    ( 2556): [0x9adbf930] worker finishing
Thread finished: <Thread Pool> #8
The thread 'Unknown' (0x8) has exited with code 0 (0x0).

The emulator is running Android 6, I've checked the internet by using the built in browser and it works. I am really confused about this, any help would be greatly appreciated!

Body:
I assume that you're running out of memory which is forcing your task to terminate. I used the code below and all is working as expected. I setup the project as a Xamarin.Android project with a Xamarin.PCL for the request portion. I also created a mock model for getting the response in a cleaner fashion. I don't really know what you're doing with the XML so you could omit that part if it is not relevant.

Project Setup

Nuget Packages Installed in the PCL

ModernHttpClient

Newtonsoft.Json

Main Activity

Below is the Android Main Activity

using Android.App;
using Android.OS;
using XamPCL;

namespace App1
{
    [Activity(Label = "App1", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        protected override async void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

                var n = new XamPCLa();
                //you want to await this function.
                Model response = await n.Test();
        }
    }
}

Xamarin.Portable (XamPCL)

using ModernHttpClient;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace XamPCL
{
    public class Model
    {
        /// <summary>
        /// this will resolve your xml into the model
        /// </summary>
        [JsonProperty(PropertyName = "rxtermsProperties")]
        public DrugSpec Container {get;set;}
    }

    public class DrugSpec
    {
        /// <summary>
        ///
        /// </summary>
        [JsonProperty(PropertyName = "displayName")]
        public string DisplayName { get; set; }
    }

    public class XamPCLa
    {
        public XamPCLa()
        {

        }

        public async Task<Model> Test()
        {
            var httpClient = GetHttpClient();
            try
            {
                var response = await httpClient.GetAsync(@"https://rxnav.nlm.nih.gov/REST/RxTerms/rxcui/198440/allinfo").ConfigureAwait(false);
                response.EnsureSuccessStatusCode();

                if (response.IsSuccessStatusCode)
                {
                    var content = response.Content;

                    string jsonString = await content.ReadAsStringAsync().ConfigureAwait(false);

                    return JsonConvert.DeserializeObject<Model>(jsonString);
                }
            }
            catch (Exception e)
            {

            }
            return new Model();
        }

        private HttpClient GetHttpClient()
        {
            var httpClient = new HttpClient(new NativeMessageHandler());

            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            return httpClient;
        }
    }
}

Result in MainActivity


来源: stackexchange

问:
How to reformat the date WITHIN a text file C#
I'm writing a piece of code that takes in an access log and cleans it. Removes all data that i don't need and gives me out a clean version. I've cleaned it from redunadant data but i need to re-format the date which is one of the fields inside of the text file. (Below is the cleaned text file thus far)

I had initially planned on splitting it by '/' and then putting the 3 elements of the date into an array (day, month, year) and re-arranging so that the date was in american format - however this then breaks the file path by '/' and i don't want that.

Below is my code so far, any help or ideas would be much appreciated!

enter code here

```<code>  StreamReader reader = new StreamReader(fileName);
        StreamWriter writer = new StreamWriter(newFileName);
        string line;

        string personalIdentifier = new string(fileName.Take(4).ToArray());
        string gender = fileName.Substring(fileName.Length - 5, 1);
        string classification = fileName.Substring(fileName.Length - 8, 2);
        string text = string.Empty;

        while ((line = reader.ReadLine()) != null)
        {
            string[] cleanArray;
            cleanArray = new string[7];

            var result = line.Split('"')
                 .Select((element, index) => index % 2 == 0
                  ? element.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                  : new string[] { element })
                 .SelectMany(element => element).ToList();

            cleanArray[0] = personalIdentifier;
            cleanArray[1] = gender;
            cleanArray[2] = classification;
            cleanArray[3] = result[0];
            cleanArray[4] = result[3];
            cleanArray[5] = result[5];
            cleanArray[6] = result[6];

            //removing the [ at the start of the date
            cleanArray[4] = cleanArray[4].Substring(1);

            //re-formatting the date so that it can be accepted by machine learning
            var dateString = cleanArray[4];
            var date = DateTime.ParseExact(dateString, "dd/MMM/yyyy:HH:mm:ss", CultureInfo.InvariantCulture);
            var newDateString = date.ToString("yyyy-MM-dd HH:mm:ss");

            //push each clean array onto the file that has been automatically created at the top
            writer.WriteLine(string.Join(", ", cleanArray.Select(v => v.ToString())));
            writer.WriteLine();
        }
        reader.DiscardBufferedData();
        writer.Close();
        reader.Close();
        }
</code>```

答:
Storing data in string fromat (or retrieving it from that) is tricky. You need the following things:

the encoding used to store the string in bytes

the culture format used to store the DateTime

the timezone the DateTime is applied to.

My first advice is to never store or Transmit DateTimes as strings. Failing that:

You propably do know the encoding of the file. And as this is a log, it will propably keep to the old ASCII settings. Encodings become a lot less relevant under char 127. XML tends to take care of this part for you.

Culture Format is a Problem. By default ToString() and Parse() and all thier variants retrieve the culture format from Windows. And just because they have the same language, does not mean they have the same formats for anything. For example UK and US date formats are totally different.
So always pick a fixed one and hardcode it. The Automatic Culture Format only works for direct user input, nothing else.

For the timezone, my advice is to always store and retreive as UTC. Otherwise you have to adapt for the Timezone used by the original writer (wich you might not know and might not be consistent) and your own (wich DateTime.ToString() will do for you).

ContentLicense: CC BY-SA 3.0

Body:
I'm writing a piece of code that takes in an access log and cleans it. Removes all data that i don't need and gives me out a clean version. I've cleaned it from redunadant data but i need to re-format the date which is one of the fields inside of the text file. (Below is the cleaned text file thus far)

I had initially planned on splitting it by '/' and then putting the 3 elements of the date into an array (day, month, year) and re-arranging so that the date was in american format - however this then breaks the file path by '/' and i don't want that.

Below is my code so far, any help or ideas would be much appreciated!

enter code here

  StreamReader reader = new StreamReader(fileName);
        StreamWriter writer = new StreamWriter(newFileName);
        string line;

        string personalIdentifier = new string(fileName.Take(4).ToArray());
        string gender = fileName.Substring(fileName.Length - 5, 1);
        string classification = fileName.Substring(fileName.Length - 8, 2);
        string text = string.Empty;

        while ((line = reader.ReadLine()) != null)
        {
            string[] cleanArray;
            cleanArray = new string[7];

            var result = line.Split('"')
                 .Select((element, index) => index % 2 == 0
                  ? element.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                  : new string[] { element })
                 .SelectMany(element => element).ToList();

            cleanArray[0] = personalIdentifier;
            cleanArray[1] = gender;
            cleanArray[2] = classification;
            cleanArray[3] = result[0];
            cleanArray[4] = result[3];
            cleanArray[5] = result[5];
            cleanArray[6] = result[6];

            //removing the [ at the start of the date
            cleanArray[4] = cleanArray[4].Substring(1);

            //re-formatting the date so that it can be accepted by machine learning
            var dateString = cleanArray[4];
            var date = DateTime.ParseExact(dateString, "dd/MMM/yyyy:HH:mm:ss", CultureInfo.InvariantCulture);
            var newDateString = date.ToString("yyyy-MM-dd HH:mm:ss");

            //push each clean array onto the file that has been automatically created at the top
            writer.WriteLine(string.Join(", ", cleanArray.Select(v => v.ToString())));
            writer.WriteLine();
        }
        reader.DiscardBufferedData();
        writer.Close();
        reader.Close();
        }


问:
Test the behavior of a java web service for multiple concurrent requests
How do I test the behavior of a java restful web service in case of multiple concurrent requests? Is there any 3rd party tool that can be leveraged?

The service accepts POST method. It expects a couple of parameters in it's request body and produces the response in the form of JSON.

The functionality of the service is to perform database read operations using the request body parameters and populate the fetched data in the JSON.

答:
One of the bests tools to test web services is SOAPUI.

You can use it for what you want.

Link to SOAPUI

You can check this link to see how to use SOAPUI and concurrent tests.


问:
how to zoom image
hai my images are gallery all image display in same view but i expect the selected image only zoom for my gallery that type how to create any one help how to create give me your idea.....now i am post my screenshot.....help me....

答:
maybe you can find what you need here:

http://www.zdnet.com/blog/burnette/how-to-use-multi-touch-in-android-2-part-6-implementing-the-pinch-zoom-gesture/1847

Or take a look at this post:
how can i get zoom functionality for images

ContentLicense: CC BY-SA 2.5

Title: how to zoom image


问:
Can't install IPA with AdHoc distribution certificate
Here is the senario where i am facing problem...

I have an App on Appstore i have removed it from appstore as a result all of my provisioning certificate and certificate gone invalid and just now i made then active again ,and while installing those application,I am using the same provisioning certificate its active now but i am not able to install the app on my device any idea why? Is there something i am doing wrong i am new to IOS.

答:
Make sure to add your device UDID to the your account.
Or confirm that your device is added to ADHoc certificate.</p>


问:
Recurring variadic template class parameters
I would like a variadic template class (with, say N template parameters) to define N member functions, each one taking a single parameter of type from the parameters list. I tried this :

```<code>template<class Derived, class... DerivedOthers>
class VtfVisitor : public VtfVisitor<DerivedOthers...>
{
public:
    virtual void visit(Derived& derived) = 0;
};

template<class Derived>
class VtfVisitor
{
public:
    virtual void visit(Derived& derived) = 0;
};
</code>```

Which does not work as I cannot redefine a template class. Then I tried solution proposed by Bo :

```<code>template<class Derived, class... DerivedOthers>
class VtfVisitor : public VtfVisitor<DerivedOthers...>
{
public:
    virtual void visit(Derived& derived) VISITOR_CVQ = 0;
};

template<class Derived>
class VtfVisitor<Derived>
{
public:
    virtual void visit(Derived& derived) VISITOR_CVQ = 0;
};
</code>```

Which still does not work: when trying this with VtfVisitor<D1,D2>, member function visit(D2&) is not defined in the instanciated template class (while visit(D1&) is well defined).

How could I get this to work as expected ?

Thanks for help.

答:
You need to put the ellipsis outside the template argument list:

```<code>template<class Derived, class... DerivedOthers>
class VtfVisitor : public VtfVisitor<DerivedOthers>...
{
public:
    virtual void visit(Derived& derived) = 0;
};
</code>```

As an example, if DerivedOthers... is {int, char, float}, you will get the following expansion:

```<code>class VtfVisitor : public VtfVisitor<char>, VtfVisitor<float>
{
public:
    virtual void visit(int& derived) = 0;
};
</code>```

Body:
I would like a variadic template class (with, say N template parameters) to define N member functions, each one taking a single parameter of type from the parameters list. I tried this :

template<class Derived, class... DerivedOthers>
class VtfVisitor : public VtfVisitor<DerivedOthers...>
{
public:
    virtual void visit(Derived& derived) = 0;
};

template<class Derived>
class VtfVisitor
{
public:
    virtual void visit(Derived& derived) = 0;
};

Which does not work as I cannot redefine a template class. Then I tried solution proposed by Bo :

template<class Derived, class... DerivedOthers>
class VtfVisitor : public VtfVisitor<DerivedOthers...>
{
public:
    virtual void visit(Derived& derived) VISITOR_CVQ = 0;
};

template<class Derived>
class VtfVisitor<Derived>
{
public:
    virtual void visit(Derived& derived) VISITOR_CVQ = 0;
};

Which still does not work: when trying this with VtfVisitor<D1,D2>, member function visit(D2&) is not defined in the instanciated template class (while visit(D1&) is well defined).

How could I get this to work as expected ?

Thanks for help.

Body:
You need to put the ellipsis outside the template argument list:

template<class Derived, class... DerivedOthers>
class VtfVisitor : public VtfVisitor<DerivedOthers>...
{
public:
    virtual void visit(Derived& derived) = 0;
};

As an example, if DerivedOthers... is {int, char, float}, you will get the following expansion:

class VtfVisitor : public VtfVisitor<char>, VtfVisitor<float>
{
public:
    virtual void visit(int& derived) = 0;
};


问:
Get the first word and char on the name of png file
l have a set of png images which are named as follow

```<code>slash_67_45.png
A_91_14.png
a_38_10.png
%_34_45.png
é_67_78.png
è_67_56.png
e_67_10.png
B_56_54.png
b_45_45.png
@_34_45.png
À_34_5.png
à_23_6.png
7_23_6.png
'_254.png
"_23.png
\_67.png
[_45.png
</code>```

l want to retrieve only the words or character before the first '_' and store that in a column in csv file as follow

```<code>charachter_column         its-image               imag-without-character

    slash                 slash_67_45.png         _67_45.png
    A                     A_91_14.png             _91_14.png
    a                     a_38_10.png             _38_10.png
    %                     %_34_45.png             _34_45.png
    é                     è_67_78.png             _67_78.png
    è                     é_67_56.png             _67_56.png
    e                     e_67_10.png             _67_10.png
    B                    B_56_54.png              _56_54.png
    b                     b_45_45.png             _45_45.png
    @                     @_34_45.png             _34_45.png
    À                      A_34_5.png             _34_5.png
    à                      à_23_6.png             _23_6.png
    7                      7_23_6.png             _23_6.png
    '                       '_254.png             _254.png
    "                        "_23.png             _23.png
    \                        \_67.png             _67.png
    [                        [_45.png             _45.png
</code>```

Here is the code l tried :

```<code>import os
import pandas as pd
charachter_column= []
its_image=[]
image_without_character=[]

temp_df = pd.DataFrame({'charachter_column ': charachter_column , 'its_image ': its-image,
'image_without_character' : image_without_character})
temp_df.to_csv('/home/images_charac.csv')

DATA_DIR = "/home/images/"
png_files=sorted(os.listdir(DATA_DIR))
for png in png_files:
    print(os.path.join(DATA_DIR,file))
    file_name=file
    character_column= file_name[:file_name.find("_")]
    image_without_character=file_name[file_name.find("_")+1:]

    temp_df = pd.DataFrame({'charachter_column ': charachter_column , 'its_image ': file_name,
'image_without_character' : image_without_character})
temp_df.to_csv('/home/images_charac.csv')
</code>```

the problem here it's that l have 3 '_' l want to consider only the first '_' encountered from the left

答:
There appear to be some other issues with your code, but this example should address the root issue you're facing:

```<code>files = ['slash_67_45.png',
'A_91_14.png',
'a_38_10.png',
'%_34_45.png',
'é_67_78.png',
'è_67_56.png',
'e_67_10.png',
'B_56_54.png',
'b_45_45.png']

for png_file in files:
    character, everything_else = png_file.split('_',maxsplit=1)
    print(character)
</code>```

out

```<code>A --- 91_14.png
a --- 38_10.png
% --- 34_45.png
é --- 67_78.png
è --- 67_56.png
e --- 67_10.png
B --- 56_54.png
b --- 45_45.png
</code>```

EDIT

It looks like you want to keep the '_'. In that case, you could do this:

```<code>for png_file in files:
    character, sep, everything_else = png_file.partition('_')
    print(character,'---', sep + everything_else)
</code>```

out

```<code>slash --- _67_45.png
A --- _91_14.png
a --- _38_10.png
% --- _34_45.png
é --- _67_78.png
è --- _67_56.png
e --- _67_10.png
B --- _56_54.png
b --- _45_45.png
</code>```

Body:
l have a set of png images which are named as follow

slash_67_45.png
A_91_14.png
a_38_10.png
%_34_45.png
é_67_78.png
è_67_56.png
e_67_10.png
B_56_54.png
b_45_45.png
@_34_45.png
À_34_5.png
à_23_6.png
7_23_6.png
'_254.png
"_23.png
\_67.png
[_45.png

l want to retrieve only the words or character before the first '_' and store that in a column in csv file as follow

charachter_column         its-image               imag-without-character

    slash                 slash_67_45.png         _67_45.png
    A                     A_91_14.png             _91_14.png
    a                     a_38_10.png             _38_10.png
    %                     %_34_45.png             _34_45.png
    é                     è_67_78.png             _67_78.png
    è                     é_67_56.png             _67_56.png
    e                     e_67_10.png             _67_10.png
    B                    B_56_54.png              _56_54.png
    b                     b_45_45.png             _45_45.png
    @                     @_34_45.png             _34_45.png
    À                      A_34_5.png             _34_5.png
    à                      à_23_6.png             _23_6.png
    7                      7_23_6.png             _23_6.png
    '                       '_254.png             _254.png
    "                        "_23.png             _23.png
    \                        \_67.png             _67.png
    [                        [_45.png             _45.png

Here is the code l tried :

import os
import pandas as pd
charachter_column= []
its_image=[]
image_without_character=[]

temp_df = pd.DataFrame({'charachter_column ': charachter_column , 'its_image ': its-image,
'image_without_character' : image_without_character})
temp_df.to_csv('/home/images_charac.csv')

DATA_DIR = "/home/images/"
png_files=sorted(os.listdir(DATA_DIR))
for png in png_files:
    print(os.path.join(DATA_DIR,file))
    file_name=file
    character_column= file_name[:file_name.find("_")]
    image_without_character=file_name[file_name.find("_")+1:]

    temp_df = pd.DataFrame({'charachter_column ': charachter_column , 'its_image ': file_name,
'image_without_character' : image_without_character})
temp_df.to_csv('/home/images_charac.csv')

the problem here it's that l have 3 '_' l want to consider only the first '_' encountered from the left

Body:
There appear to be some other issues with your code, but this example should address the root issue you're facing:

files = ['slash_67_45.png',
'A_91_14.png',
'a_38_10.png',
'%_34_45.png',
'é_67_78.png',
'è_67_56.png',
'e_67_10.png',
'B_56_54.png',
'b_45_45.png']

for png_file in files:
    character, everything_else = png_file.split('_',maxsplit=1)
    print(character)

out

A --- 91_14.png
a --- 38_10.png
% --- 34_45.png
é --- 67_78.png
è --- 67_56.png
e --- 67_10.png
B --- 56_54.png
b --- 45_45.png

EDIT

It looks like you want to keep the '_'. In that case, you could do this:

for png_file in files:
    character, sep, everything_else = png_file.partition('_')
    print(character,'---', sep + everything_else)

out

slash --- _67_45.png
A --- _91_14.png
a --- _38_10.png
% --- _34_45.png
é --- _67_78.png
è --- _67_56.png
e --- _67_10.png
B --- _56_54.png
b --- _45_45.png


问:
Javascript swaps to mm/dd date but the input field is dd/mm
I have an html form with bootstrap with this date fields:

```<code><input type="date" class="form-control" id="from" name="from" placeholder="dd/mm/yyyy">
<input type="date" class="form-control" id="to" name="to" placeholder="dd/mm/yyyy">
</code>```

I need to compare the two to check "to" is a date after "from", but when I compare using this code:

```<code>if(new Date($("#from").val() > new Date($("#to").val()) ....
</code>```

the calculation goes wrong because under the hood it swaps month numbers with the day numbers. How do I force it to take the dd/mm/yyyy format (or convert the input as mm/dd/yyyy) to get the proper calculation?
Thank you.

答:
In Javascript, you can generate date as new Date(year,month,day) you need to construct your date this way then try this,

```<code>var date = new Date(2010,10,10)
(new Date().getTime() - date.getTime())/ (24 * 60 * 60 * 1000)
</code>```

In this code, I am subtracting the date from current date, with little modification you can get it worked for your code.

Body:
I have an html form with bootstrap with this date fields:

<input type="date" class="form-control" id="from" name="from" placeholder="dd/mm/yyyy">
<input type="date" class="form-control" id="to" name="to" placeholder="dd/mm/yyyy">

I need to compare the two to check "to" is a date after "from", but when I compare using this code:

if(new Date($("#from").val() > new Date($("#to").val()) ....

the calculation goes wrong because under the hood it swaps month numbers with the day numbers. How do I force it to take the dd/mm/yyyy format (or convert the input as mm/dd/yyyy) to get the proper calculation?
Thank you.

Body:
In Javascript, you can generate date as new Date(year,month,day) you need to construct your date this way then try this,

var date = new Date(2010,10,10)
(new Date().getTime() - date.getTime())/ (24 * 60 * 60 * 1000)

In this code, I am subtracting the date from current date, with little modification you can get it worked for your code.


问:
Reset database field values when active page is unloaded
In my app, I have a record locking mechanism that prevents two people from being in the Edit view of a record at the same time. Here is the function that locks the record when it is called up in the Edit view:

```<code>public function lockRecord($id = null) {
$this->loadModel('User');
$this->Model->id = $id;
$current = $this->Model->read(null, $id);

//Get the current logged-in user's ID
$userid = $current['Model']['requester_id'];

//Get the current lock expiry time
$lock_time = $this->Model->find('first', array(
  'fields'=>array('Model.lock_expiry_time'),
  'conditions'=>array('Model.id'=>$id)
  )
);

//Get the ID of the user who has the record lock (if any)
$logged_user = $this->Model->find('first', array(
  'fields'=>array('Model.lock_key'),
  'conditions'=>array('Model.id'=>$id)
  )
);

//Get that same user's full name
$full_name = $this->User->find('first', array(
  'joins' => array(
    array(
      'table' => 'recordtable',
      'alias' => 'Model',
      'type' => 'INNER',
      'conditions' => array('Model.lock_key = User.id')
      )
    )
  )
);
$this->set('lock_time', $lock_time);
$this->set(compact($current));
$this->set(compact($logged_user));
$this->set(compact($full_name));
if(AuthComponent::user('id') != $logged_user['Msr']['lock_key'] && date("Y-m-d H:i:s") < $lock_time['Msr']['lock_expiry_time']) {
  $this->Session->setFlash(__('This MSR is locked for editing by ' . $full_name['User']['full_name'] . '. Please try again in a few minutes or wait for this user to close the document.<br/>
    (Lock expires at '. $lock_time['Msr']['lock_expiry_time'] . ')'));
  $this->redirect(array('action' => 'view', $id));
} else {
  //Set a new lock key and expiry time if the record is free for editing
  $locksession = $this->Msr->query("UPDATE msrs SET lock_key = {$userid}, lock_expiry_time = ADDTIME(NOW(), '00:05:00') WHERE id = {$id}");
  $this->set('locksession', $locksession);
  }
}
</code>```

When the user saves their changes, the unlockRecord function is called to release the key, reset the lock_expiry_time, and redirect the user to the "View" view:

```<code>public function unlockRecord($id = null) {
//Get a list of security groups
$groups = $this->Session->read('groups');
$this->Msr->id = $id;
//Reset the lock_key and the lock_expiry_time
$locksession = $this->Msr->query("UPDATE msrs SET lock_key = '', lock_expiry_time = '' WHERE id = {$id} ");
//If the module admin manually releases the lock, display a message
if(in_array('msr_module_admin', $groups)) {
  $this->Session->setFlash(__('The MSR has been unlocked and is available for editing.'));
}
$this->redirect(array('action'=>'view', $id));
}
</code>```

There are three other conditions where the lock can be released:

--An administrator manually releases the lock by clicking a link.

--The user logs out of the system entirely.

--The lock expires five minutes after it is set.

I need the lock to be released any time the record in the Edit view is no longer active. For instance, if the user clicks off to another site or clicks a different link in my own site; anything that takes them away from the record they have open in the Edit view. lock_key should be set to '' and lock_expiry_time set to ''. How might I accomplish this?

答:
Recognizing that a page on your site has been abandoned by the user is not possible to do reliably in web programming.

What happens to your web site if she switches off her computer/device or disconnects her network? Nothing. What happens if she clicks a link in her bookmarks bar in the middle of editing your page? Nothing. You never hear from her again.  That's why your lock has an expiry time.

So, to address your problem you need to think about ways to shorten the expiry time and/or reduce the chance of page abandonment.

One choice:  put some Javascript in your edit page that uses an ajax-style request once every so often to hit your web site with a keepalive request.  You can rig this up to hit your site every minute. Every time you get the keepalive request, you can extend the expiry time by 90 seconds.

Another choice: You may have noticed that StackOverflow pages throw a browser dialog box saying "Do you want to leave this site?" if you press the BACK button while editing a post. SO actually throws the dialog box whenever you abandon a page.  They use the onbeforeunload event in the browser for this. You can do the same, enabling a dialog box when the edit page is activated, and disabling it when the user saves it.

Browsers don't allow web pages to force any sort of action other than a dialog box upon page unload. Such a feature would be very easy for cybercreeps to use to propagate malware.

Body:
In my app, I have a record locking mechanism that prevents two people from being in the Edit view of a record at the same time. Here is the function that locks the record when it is called up in the Edit view:

public function lockRecord($id = null) {
$this->loadModel('User');
$this->Model->id = $id;
$current = $this->Model->read(null, $id);

//Get the current logged-in user's ID
$userid = $current['Model']['requester_id'];

//Get the current lock expiry time
$lock_time = $this->Model->find('first', array(
  'fields'=>array('Model.lock_expiry_time'),
  'conditions'=>array('Model.id'=>$id)
  )
);

//Get the ID of the user who has the record lock (if any)
$logged_user = $this->Model->find('first', array(
  'fields'=>array('Model.lock_key'),
  'conditions'=>array('Model.id'=>$id)
  )
);

//Get that same user's full name
$full_name = $this->User->find('first', array(
  'joins' => array(
    array(
      'table' => 'recordtable',
      'alias' => 'Model',
      'type' => 'INNER',
      'conditions' => array('Model.lock_key = User.id')
      )
    )
  )
);
$this->set('lock_time', $lock_time);
$this->set(compact($current));
$this->set(compact($logged_user));
$this->set(compact($full_name));
if(AuthComponent::user('id') != $logged_user['Msr']['lock_key'] && date("Y-m-d H:i:s") < $lock_time['Msr']['lock_expiry_time']) {
  $this->Session->setFlash(__('This MSR is locked for editing by ' . $full_name['User']['full_name'] . '. Please try again in a few minutes or wait for this user to close the document.

    (Lock expires at '. $lock_time['Msr']['lock_expiry_time'] . ')'));
  $this->redirect(array('action' => 'view', $id));
} else {
  //Set a new lock key and expiry time if the record is free for editing
  $locksession = $this->Msr->query("UPDATE msrs SET lock_key = {$userid}, lock_expiry_time = ADDTIME(NOW(), '00:05:00') WHERE id = {$id}");
  $this->set('locksession', $locksession);
  }
}

When the user saves their changes, the unlockRecord function is called to release the key, reset the lock_expiry_time, and redirect the user to the "View" view:

public function unlockRecord($id = null) {
//Get a list of security groups
$groups = $this->Session->read('groups');
$this->Msr->id = $id;
//Reset the lock_key and the lock_expiry_time
$locksession = $this->Msr->query("UPDATE msrs SET lock_key = '', lock_expiry_time = '' WHERE id = {$id} ");
//If the module admin manually releases the lock, display a message
if(in_array('msr_module_admin', $groups)) {
  $this->Session->setFlash(__('The MSR has been unlocked and is available for editing.'));
}
$this->redirect(array('action'=>'view', $id));
}

There are three other conditions where the lock can be released:

--An administrator manually releases the lock by clicking a link.

--The user logs out of the system entirely.

--The lock expires five minutes after it is set.

I need the lock to be released any time the record in the Edit view is no longer active. For instance, if the user clicks off to another site or clicks a different link in my own site; anything that takes them away from the record they have open in the Edit view. lock_key should be set to '' and lock_expiry_time set to ''. How might I accomplish this?


问:
Jquery not running even after including it in my html
So i'm trying to put my jquery in a js folder saved as script.js and then just call the file in my html. So i tried to call it before my css, after my css and even just right above where my  ends yet my jquery is not running. Can anyone identify my issue? Here's how i tried to call my script.js in my index.php

```<code><!DOCTYPE HTML>
<html>
<head>
<?php include '/php/db.php'; ?>
<link rel="stylesheet" href="style.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

<script type = "text/javascript" src="js/script.js"></script>

<link href="https://fonts.googleapis.com/css?family=Josefin+Sans" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Paprika" rel="stylesheet">

<title>YFC</title>
</head>

<body>

    <div id = "container" method="post">
        <div class="signup">
            <h1>Sign up</h1>
            <form action="/action_page.php">
              <input class="pop" type="text" name="Sname" placeholder="Fill in your name!"><br><br><br>

              <input class="pop" type="password" name="Slastname" placeholder="Fill in your last name!"><br><br><br>

              <input class="pop" type="text" name="Susername" placeholder="Fill in your username!"><br><br><br>

              <input class="pop" type="password" name="Spassword" placeholder="Fill in your password!"><br><br><br>

              <input class="pop" type="password" name="SRpassword" placeholder="Repeat your password!"><br><br><br>
              <input class="sbutton" type="submit" value="Submit">
            </form>
        </div>

        <div class="signin">
            <h1>Log in</h1>
            <form action="/action_page.php" method="post">
              <input class="pop" type="text" name="Lusername" placeholder="Fill in your username!"> <br><br><br>
              <input class="pop" type="password" name="Lpassword" placeholder="Fill in your username!"> <br><br><br>
              <input class="lbutton" type="submit" value="Log in">

            </form>
        </div>

    </div>

</body>
</html>
</code>```

And here is my jquery code

```<code>$('.pop').mouseenter(function(){
    $(this).css('width',300);
});

$('.pop').mouseleave(fucntion(){
     $(this).css('width',280)

});
</code>```

答:
You need to run your JS code when the DOM is available for use. Right now you're trying to use the .pop elements before they exist.

To do this in jQuery you can use a document.ready event handler:

```<code>$(function() {
  $('.pop').mouseenter(function() {
    $(this).css('width', 300);
  }).mouseleave(function() {
     $(this).css('width', 280)
  });
});
</code>```

However there's a couple of things to note here which can improve the quality of your code. Firstly you shouldn't put CSS rules in your JS code. Instead create classes and then use any of the jQuery class amendment methods (addClass(), removeClass(), toggleClass()) to add/remove it as needed.

Also you can use hover() to run code under both the mouseenter and mouseleave events. If you couple that with toggleClass() you only ever need to provide a single handler function:

```<code>$(function() {
  $('.pop').hover(function() {
    $(this).toggleClass('hover');
  });
});
</code>```

.pop { width: 280px; }
.pop.hover { width: 300px; }
```

<p>Taking that a stage further still, then you don't even need to use JS code at all. You can use CSS's <code>:hover</code> selector to amend the element when the mouse is over it, like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.pop {
  width: 280px;
  border: 1px solid #C00;
  margin: 2px;
}
.pop:hover { width: 300px; }</code>```

Pop

Pop

Pop
```

Body:
So i'm trying to put my jquery in a js folder saved as script.js and then just call the file in my html. So i tried to call it before my css, after my css and even just right above where my  ends yet my jquery is not running. Can anyone identify my issue? Here's how i tried to call my script.js in my index.php

<!DOCTYPE HTML>

<?php include '/php/db.php'; ?>
<link rel="stylesheet" href="style.css">

<link href="https://fonts.googleapis.com/css?family=Josefin+Sans" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Paprika" rel="stylesheet">

<title>YFC</title>

Sign up

            <form action="/action_page.php">
              <input class="pop" type="text" name="Sname" placeholder="Fill in your name!">

              <input class="pop" type="password" name="Slastname" placeholder="Fill in your last name!">

              <input class="pop" type="text" name="Susername" placeholder="Fill in your username!">

              <input class="pop" type="password" name="Spassword" placeholder="Fill in your password!">

              <input class="pop" type="password" name="SRpassword" placeholder="Repeat your password!">

              <input class="sbutton" type="submit" value="Submit">
            </form>

Log in

            <form action="/action_page.php" method="post">
              <input class="pop" type="text" name="Lusername" placeholder="Fill in your username!">

              <input class="pop" type="password" name="Lpassword" placeholder="Fill in your username!">

              <input class="lbutton" type="submit" value="Log in">

            </form>

And here is my jquery code

$('.pop').mouseenter(function(){
    $(this).css('width',300);
});

$('.pop').mouseleave(fucntion(){
     $(this).css('width',280)

});

Body:
You need to run your JS code when the DOM is available for use. Right now you're trying to use the .pop elements before they exist.

To do this in jQuery you can use a document.ready event handler:

$(function() {
  $('.pop').mouseenter(function() {
    $(this).css('width', 300);
  }).mouseleave(function() {
     $(this).css('width', 280)
  });
});

However there's a couple of things to note here which can improve the quality of your code. Firstly you shouldn't put CSS rules in your JS code. Instead create classes and then use any of the jQuery class amendment methods (addClass(), removeClass(), toggleClass()) to add/remove it as needed.

Also you can use hover() to run code under both the mouseenter and mouseleave events. If you couple that with toggleClass() you only ever need to provide a single handler function:

$(function() {
  $('.pop').hover(function() {
    $(this).toggleClass('hover');
  });
});

.pop { width: 280px; }
.pop.hover { width: 300px; }

Taking that a stage further still, then you don't even need to use JS code at all. You can use CSS's :hover selector to amend the element when the mouse is over it, like this:

.pop {
  width: 280px;
  border: 1px solid #C00;
  margin: 2px;
}
.pop:hover { width: 300px; }

<div class="pop">Pop</div>
<div class="pop">Pop</div>
<div class="pop">Pop</div>


问:
PHP - Content Shopping Api - item not found
I am using Google's Content Shopping API, Everything is going good with this code.

But when I am trying to delete the product from Merchant Center by following method, the product deleted from list successfully but still returning "item not found" error.

This is the code :

```<code>public function deleteProduct($offerId) {
    $productId = $this->buildProductId($offerId);
    // The response for a successful delete is empty
    $this->service->products->delete($this->merchantId, $productId);
}
</code>```

And this is the error it returning.

```<code>Google_Service_Exception
{
"error": {
"errors": [
{
"domain": "global",
"reason": "notFound",
"message": "item not found"
}
],
"code": 404,
"message": "item not found"
}
}
</code>```

答:
Well, I want to handle two scenarios in my project.

1) If the product is live on Google Merchant Center then request to delete it, otherwise not.

2) If the product is already live on the Google Merchant Center then do not try to upload it again.

Content Shopping API having no such thing to check the product is already present or not. They directly throw the Exception.

Answer for scenario 1 :

Actually I am using Yii2 framework which uses Pjax in GridView. When I am clicking a button, it first call Pjax and then redirect to the URL. Hence it is trying to delete same product again. And hence the Exception.

Answer for scenario 2 :

You can upload the same product again to the Google Merchant Center. If the product is already there then it will update all values for that productId(itemId or offerId). I don't think its good for me. Hence I am keeping the status of uploaded products in my database. And if same product came, I just setting the flag of 'uploaded' and not really uploading the product.

Body:
I am using Google's Content Shopping API, Everything is going good with this code.

But when I am trying to delete the product from Merchant Center by following method, the product deleted from list successfully but still returning "item not found" error.

This is the code :

public function deleteProduct($offerId) {
    $productId = $this->buildProductId($offerId);
    // The response for a successful delete is empty
    $this->service->products->delete($this->merchantId, $productId);
}

And this is the error it returning.

Google_Service_Exception
{
"error": {
"errors": [
{
"domain": "global",
"reason": "notFound",
"message": "item not found"
}
],
"code": 404,
"message": "item not found"
}
}


问:
Bootstrap tooltips and popovers: To Destroy, or NOT To Destroy?
if I create tooltips and popovers via BS' tooltip() and popover() methods, is there a need to do any explicit destroying of said creations if the DOM changes and the affected elements are no longer present? Am I creating JS dust bunnies by NOT explicitly destroying?</p>

答:
to put toolips on dynamic content you should use a delegate as such:$('body').toolip({selector: '.has-tooltip'}); and in this case, destroying is not needed.

https://github.com/twbs/bootstrap/issues/4215

http://jsbin.com/zopod/1/edit?html,css,js,output


问:
Why was function overloading added to C++?
I have a C background. I was just wondering why was function overloading added to C++? C doesn't have function overloading but C++ does, what was the need for it?

What went across the mind of the language designer at that time?

答:
One good reason, in addition to what DeadMG said, is that if you're writing a template function which e.g. calls sqrt, then you need a generic way of calling sqrt -- it would be very difficult if you had to try and somehow vary the name to sqrtf, sqrtd, etc., depending on the type of the template parameter. Overloading solves this problem, because then you just write sqrt and let the compiler figure out which overload it should be using:

```<code>template <typename T>
T sqrt_plus_one(T t) // contrived example
{
  return sqrt(t) + 1;
}
</code>```

Body:
One good reason, in addition to what DeadMG said, is that if you're writing a template function which e.g. calls sqrt, then you need a generic way of calling sqrt -- it would be very difficult if you had to try and somehow vary the name to sqrtf, sqrtd, etc., depending on the type of the template parameter. Overloading solves this problem, because then you just write sqrt and let the compiler figure out which overload it should be using:

template <typename T>
T sqrt_plus_one(T t) // contrived example
{
  return sqrt(t) + 1;
}


问:
how to vlookup Multiple sheets and delete set of ID's from all sheets
i have 12 sheets in workbook in that sheet8 is the sheet where all the sheets vlookup with, in sheet8 i have only one column with list of Customer name.

now i want what all 11 sheets should vlookup with sheet8 and what ever the names matches with sheet8 should be there which are not matching should be deleted.in these sheets 3 are empty.

code is below

```<code>Sub VLdelete()

    Dim arr(), msg As String
    Dim ws_lrow, ws8_lrow, i As Integer
    Dim ws As Worksheet

    ws8_lrow = Sheets("Sheet8").Cells(Rows.Count, 1).End(xlUp).Row

    ReDim arr(ws8_lrow)

    For i = 2 To ws8_lrow
        arr(i - 2) = Sheets("Sheet8").Cells(i, 1).value
    Next i

    For Each ws In ActiveWorkbook.Sheets
        ws_lrow = ws.Cells(Rows.Count, 2).End(xlUp).Row

        For i = ws_lrow To 2 Step -1
            If IsInArray(ws.Cells(i, 2), arr()) = 0 Then
                msg = msg & "User """ & ws.Cells(i, 2) & """ from: " & ws.Name & vbCrLf
                ws.Cells(i, 2).EntireRow.Delete xlShiftUp
            End If
        Next i
    Next ws

    If Len(msg) > 0 Then
        MsgBox "The following users have been deleted:" & vbCrLf & msg
    End If

End Sub

Private Function IsInArray(valToBeFound As Variant, arr As Variant) As Boolean

    Dim element As Variant
    On Error GoTo IsInArrayError: 'array is empty
     For Each element In arr
            If element = valToBeFound Then
                IsInArray = True
                Exit Function
            End If
        Next element
    Exit Function

IsInArrayError:
    On Error GoTo 0
    IsInArray = False

End Function
</code>```

but i am getting delete method of range class failed error ...at line no 24

```<code>ws.Cells(i, 2).EntireRow.Delete xlShiftUp
</code>```

can anyone help

答:
Try the shorter code version below.

You can replace your Function IsInArray with Application.Match.

If Not IsError(Application.Match(.Cells(i, 2), arr, 0)) Then checks if there is a match of current .Cells(i, 2) value with one of the array elements arr >> If there is it will pass this If criteria.

Code

```<code>Option Explicit

Sub VLdelete()

    Dim arr As Variant
    Dim msg As String
    Dim ws_lrow As Long, ws8_lrow As Long, i As Long
    Dim ws As Worksheet

    Application.ScreenUpdating = False

    With Sheets("Sheet8")
        ws8_lrow = .Cells(.Rows.Count, 1).End(xlUp).Row
        ' populate array without loop
        ' use Transpose to get 1-D array (and not 2-D)
        arr = Application.Transpose(.Range("A2:A" & ws8_lrow))
    End With

    For Each ws In ActiveWorkbook.Sheets
        If ws.Name <> "Summary" Then ' skip "Summary" sheet
            With ws
                ws_lrow = .Cells(.Rows.Count, 2).End(xlUp).Row

                For i = ws_lrow To 2 Step -1
                    ' check that no match was found >> delete user
                    If IsError(Application.Match(.Cells(i, 2), arr, 0)) Then
                        msg = msg & .Cells(i, 2) & vbCrLf
                        .Cells(i, 2).EntireRow.Delete xlShiftUp
                    End If
                Next i
            End With
        End If
    Next ws
    Application.ScreenUpdating = True

    If Len(msg) > 0 Then
        MsgBox "The following users have been deleted:" & vbCrLf & msg
    End If

End Sub
</code>```

Body:
i have 12 sheets in workbook in that sheet8 is the sheet where all the sheets vlookup with, in sheet8 i have only one column with list of Customer name.

now i want what all 11 sheets should vlookup with sheet8 and what ever the names matches with sheet8 should be there which are not matching should be deleted.in these sheets 3 are empty.

code is below

Sub VLdelete()

    Dim arr(), msg As String
    Dim ws_lrow, ws8_lrow, i As Integer
    Dim ws As Worksheet

    ws8_lrow = Sheets("Sheet8").Cells(Rows.Count, 1).End(xlUp).Row

    ReDim arr(ws8_lrow)

    For i = 2 To ws8_lrow
        arr(i - 2) = Sheets("Sheet8").Cells(i, 1).value
    Next i

    For Each ws In ActiveWorkbook.Sheets
        ws_lrow = ws.Cells(Rows.Count, 2).End(xlUp).Row

        For i = ws_lrow To 2 Step -1
            If IsInArray(ws.Cells(i, 2), arr()) = 0 Then
                msg = msg & "User """ & ws.Cells(i, 2) & """ from: " & ws.Name & vbCrLf
                ws.Cells(i, 2).EntireRow.Delete xlShiftUp
            End If
        Next i
    Next ws

    If Len(msg) > 0 Then
        MsgBox "The following users have been deleted:" & vbCrLf & msg
    End If

End Sub

Private Function IsInArray(valToBeFound As Variant, arr As Variant) As Boolean

    Dim element As Variant
    On Error GoTo IsInArrayError: 'array is empty
     For Each element In arr
            If element = valToBeFound Then
                IsInArray = True
                Exit Function
            End If
        Next element
    Exit Function

IsInArrayError:
    On Error GoTo 0
    IsInArray = False

End Function

but i am getting delete method of range class failed error ...at line no 24

ws.Cells(i, 2).EntireRow.Delete xlShiftUp

can anyone help

Body:
Try the shorter code version below.

You can replace your Function IsInArray with Application.Match.

If Not IsError(Application.Match(.Cells(i, 2), arr, 0)) Then checks if there is a match of current .Cells(i, 2) value with one of the array elements arr >> If there is it will pass this If criteria.

Code

Option Explicit

Sub VLdelete()

    Dim arr As Variant
    Dim msg As String
    Dim ws_lrow As Long, ws8_lrow As Long, i As Long
    Dim ws As Worksheet

    Application.ScreenUpdating = False

    With Sheets("Sheet8")
        ws8_lrow = .Cells(.Rows.Count, 1).End(xlUp).Row
        ' populate array without loop
        ' use Transpose to get 1-D array (and not 2-D)
        arr = Application.Transpose(.Range("A2:A" & ws8_lrow))
    End With

    For Each ws In ActiveWorkbook.Sheets
        If ws.Name <> "Summary" Then ' skip "Summary" sheet
            With ws
                ws_lrow = .Cells(.Rows.Count, 2).End(xlUp).Row

                For i = ws_lrow To 2 Step -1
                    ' check that no match was found >> delete user
                    If IsError(Application.Match(.Cells(i, 2), arr, 0)) Then
                        msg = msg & .Cells(i, 2) & vbCrLf
                        .Cells(i, 2).EntireRow.Delete xlShiftUp
                    End If
                Next i
            End With
        End If
    Next ws
    Application.ScreenUpdating = True

    If Len(msg) > 0 Then
        MsgBox "The following users have been deleted:" & vbCrLf & msg
    End If

End Sub


问:
Searching from File title as well as file content in media library
I managed to Search the contents of text files using custom search as described in the link below: https://docs.kentico.com/k8/custom-development/miscellaneous-custom-development-tasks/smart-search-api/creating-custom-smart-search-indexes

But it is not able to search in the filename. For example, if my search text is "Roman", the file "RomanRaj.txt" should show up in the results. Please help.

答: I'd suggest NOT creating a custom smart search index but look at using attachments and searching those.  Out of the box, Kentico will allow you to search attachments and their contents without writing any code.</p>


问:
SQL Calculate a Total Time in a specific State
I have these datas in a Table

```<code>_____DateTime____|Variable__|Value
2017/03/29 23:00:00 | Variable1   | 1
2017/03/31 01:00:00 | Variable1   | 0
2017/03/31 02:00:00 | Variable1   | 1
2017/03/31 03:00:00 | Variable1   | 0
2017/03/31 04:00:00 | Variable2   | 1
2017/03/31 23:00:00 | Variable1   | 1
2017/04/01 01:00:00 | Variable1   | 0
</code>```

And I would like to calculate the total duration where each variable was in state 1 between two date

For example between for Var1 2017/03/31 00:00:00 and 2017/04/01 00:00:00
The result is :

```<code>1 hour between 2017/03/31 00:00:00 and 2017/03/31 01:00:00
1 hour between 2017/03/31 02:00:00 and 2017/03/31 03:00:00
1 hour between 2017/03/31 23:00:00 and 2017/04/01 00:00:00
</code>```

So the result I want for Var1 should be 3 hours

For example between for Var2 2017/03/31 00:00:00 and 2017/04/01 00:00:00
The result is :
1 hour between 2017/03/31 04:00:00 and 2017/04/01 00:00:00 (no value before but because it change to 1 I suppose that it was 0 before)

So the result I want for Var2 should be 20 hours

Variable|__Time in Value (second)

Variable1   | 180

Variable2   | 1200

If someone can help me.

Thanks in advance

答:
For SQL Server 2012+ (because of lead() and concat())

Using a stacked cte to generate an hours table to inner join a subquery that uses the lead() window function to get the next date for status change partitioned by Variable.

To adapt for prior versions, use an outer apply() to get the next dt for each variable instead of lead(); and regular string concatenation with proper conversions instead of concat().

```<code>declare @fromdate datetime = '20170331 00:00:00';
declare @thrudate datetime = '20170401 00:00:00';
;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n))
, hours as (
  select top ((datediff(hour, @fromdate, @thrudate)+1))
      [DateHour]=dateadd(hour,(row_number() over (order by (select 1)) -1),@fromdate)
  from n as deka cross join n as hecto cross join n as kilo
                cross join n as tenK cross join n as hundredK
   order by 1
)
select variable, value
  , hours = count(h.datehour)
  , start_dt = convert(varchar(20),min(h.datehour),120)
  , end_dt   = convert(varchar(20),end_dt,120)
  , txt = concat(
            count(h.datehour),' '
          , case when count(h.datehour) < 2 then 'hour' else 'hours' end
          , ' between '
          , convert(varchar(20),min(h.datehour),120)
          , ' and '
          , convert(varchar(20),end_dt,120)
    )
from hours h
  inner join (
  select
      variable
    , value
    , start_dt = dt
    , end_dt   = case when coalesce(lead(dt) over (partition by variable order by dt),@thrudate) > @thrudate
                        then @thrudate
                      else coalesce(lead(dt) over (partition by variable order by dt),@thrudate)
                      end
  from t
    ) s
    on h.datehour >= s.start_dt
   and h.datehour <  s.end_dt
  where h.datehour >= @fromdate
    and h.datehour <  @thrudate
    and s.value = 1
group by variable, value, start_dt, end_dt
</code>```

rextester demo: http://rextester.com/ZBWP22523

returns:

```<code>+-----------+-------+-------+---------------------+---------------------+--------------------------------------------------------------+
| variable  | value | hours |      start_dt       |       end_dt        |                             txt                              |
+-----------+-------+-------+---------------------+---------------------+--------------------------------------------------------------+
| Variable1 |     1 |     1 | 2017-03-31 00:00:00 | 2017-03-31 01:00:00 | 1 hour between 2017-03-31 00:00:00 and 2017-03-31 01:00:00   |
| Variable1 |     1 |     1 | 2017-03-31 02:00:00 | 2017-03-31 03:00:00 | 1 hour between 2017-03-31 02:00:00 and 2017-03-31 03:00:00   |
| Variable1 |     1 |     1 | 2017-03-31 23:00:00 | 2017-04-01 01:00:00 | 1 hour between 2017-03-31 23:00:00 and 2017-04-01 01:00:00   |
| Variable2 |     1 |    20 | 2017-03-31 04:00:00 | 2017-04-01 00:00:00 | 20 hours between 2017-03-31 04:00:00 and 2017-04-01 00:00:00 |
+-----------+-------+-------+---------------------+---------------------+--------------------------------------------------------------+
</code>```

If you need to do this often, you might consider creating an actual table for hours. Otherwise, using the stacked cte is as fast as most other options, and is much faster than a recursive cte as the number of values generated increases.

Number and Calendar table reference:

Generate a set or sequence without loops - 1 - Aaron Bertrand

Generate a set or sequence without loops - 2 - Aaron Bertrand

Generate a set or sequence without loops - 3 - Aaron Bertrand

The "Numbers" or "Tally" Table: What it is and how it replaces a loop - Jeff Moden

Creating a Date Table/Dimension in SQL Server 2008 - David Stein

Calendar Tables - Why You Need One - David Stein

Creating a date dimension or calendar table in SQL Server - Aaron Bertrand

TSQL Function to Determine Holidays in SQL Server - Tim Cullen

F_TABLE_DATE - Michael Valentine Jones

Body:
I have these datas in a Table

_____DateTime____|Variable__|Value
2017/03/29 23:00:00 | Variable1   | 1
2017/03/31 01:00:00 | Variable1   | 0
2017/03/31 02:00:00 | Variable1   | 1
2017/03/31 03:00:00 | Variable1   | 0
2017/03/31 04:00:00 | Variable2   | 1
2017/03/31 23:00:00 | Variable1   | 1
2017/04/01 01:00:00 | Variable1   | 0

And I would like to calculate the total duration where each variable was in state 1 between two date

For example between for Var1 2017/03/31 00:00:00 and 2017/04/01 00:00:00
The result is :

1 hour between 2017/03/31 00:00:00 and 2017/03/31 01:00:00
1 hour between 2017/03/31 02:00:00 and 2017/03/31 03:00:00
1 hour between 2017/03/31 23:00:00 and 2017/04/01 00:00:00

So the result I want for Var1 should be 3 hours

For example between for Var2 2017/03/31 00:00:00 and 2017/04/01 00:00:00
The result is :
1 hour between 2017/03/31 04:00:00 and 2017/04/01 00:00:00 (no value before but because it change to 1 I suppose that it was 0 before)

So the result I want for Var2 should be 20 hours

Variable|__Time in Value (second)

Variable1   | 180

Variable2   | 1200

If someone can help me.

Thanks in advance

Body:
For SQL Server 2012+ (because of lead() and concat())

Using a stacked cte to generate an hours table to inner join a subquery that uses the lead() window function to get the next date for status change partitioned by Variable.

To adapt for prior versions, use an outer apply() to get the next dt for each variable instead of lead(); and regular string concatenation with proper conversions instead of concat().

declare @fromdate datetime = '20170331 00:00:00';
declare @thrudate datetime = '20170401 00:00:00';
;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n))
, hours as (
  select top ((datediff(hour, @fromdate, @thrudate)+1))
      [DateHour]=dateadd(hour,(row_number() over (order by (select 1)) -1),@fromdate)
  from n as deka cross join n as hecto cross join n as kilo
                cross join n as tenK cross join n as hundredK
   order by 1
)
select variable, value
  , hours = count(h.datehour)
  , start_dt = convert(varchar(20),min(h.datehour),120)
  , end_dt   = convert(varchar(20),end_dt,120)
  , txt = concat(
            count(h.datehour),' '
          , case when count(h.datehour) < 2 then 'hour' else 'hours' end
          , ' between '
          , convert(varchar(20),min(h.datehour),120)
          , ' and '
          , convert(varchar(20),end_dt,120)
    )
from hours h
  inner join (
  select
      variable
    , value
    , start_dt = dt
    , end_dt   = case when coalesce(lead(dt) over (partition by variable order by dt),@thrudate) > @thrudate
                        then @thrudate
                      else coalesce(lead(dt) over (partition by variable order by dt),@thrudate)
                      end
  from t
    ) s
    on h.datehour >= s.start_dt
   and h.datehour <  s.end_dt
  where h.datehour >= @fromdate
    and h.datehour <  @thrudate
    and s.value = 1
group by variable, value, start_dt, end_dt

rextester demo: http://rextester.com/ZBWP22523

returns:

+-----------+-------+-------+---------------------+---------------------+--------------------------------------------------------------+
| variable  | value | hours |      start_dt       |       end_dt        |                             txt                              |
+-----------+-------+-------+---------------------+---------------------+--------------------------------------------------------------+
| Variable1 |     1 |     1 | 2017-03-31 00:00:00 | 2017-03-31 01:00:00 | 1 hour between 2017-03-31 00:00:00 and 2017-03-31 01:00:00   |
| Variable1 |     1 |     1 | 2017-03-31 02:00:00 | 2017-03-31 03:00:00 | 1 hour between 2017-03-31 02:00:00 and 2017-03-31 03:00:00   |
| Variable1 |     1 |     1 | 2017-03-31 23:00:00 | 2017-04-01 01:00:00 | 1 hour between 2017-03-31 23:00:00 and 2017-04-01 01:00:00   |
| Variable2 |     1 |    20 | 2017-03-31 04:00:00 | 2017-04-01 00:00:00 | 20 hours between 2017-03-31 04:00:00 and 2017-04-01 00:00:00 |
+-----------+-------+-------+---------------------+---------------------+--------------------------------------------------------------+

If you need to do this often, you might consider creating an actual table for hours. Otherwise, using the stacked cte is as fast as most other options, and is much faster than a recursive cte as the number of values generated increases.

Number and Calendar table reference:

Generate a set or sequence without loops - 1 - Aaron Bertrand

Generate a set or sequence without loops - 2 - Aaron Bertrand

Generate a set or sequence without loops - 3 - Aaron Bertrand

The "Numbers" or "Tally" Table: What it is and how it replaces a loop - Jeff Moden

Creating a Date Table/Dimension in SQL Server 2008 - David Stein

Calendar Tables - Why You Need One - David Stein

Creating a date dimension or calendar table in SQL Server - Aaron Bertrand

TSQL Function to Determine Holidays in SQL Server - Tim Cullen

F_TABLE_DATE - Michael Valentine Jones


问:
Unity 5 unityscript returns errors when trying to write to a file
I have successfully made a level with a Terrain, a Rigidbody FPS Controller from Standard Assets -> Characters and some other GameObjects. I now need to save my system so I have started to google file IO for UnityScript. I have found some examples but they return compiler errors (details below).

OS is Windows 10 64-bit. Unity version is 5.5.1f1 64-bit. Code editor is Visual Studio 2015, line endings corrected to Windows line endings. Language is UnityScript. Code I have used:

```<code>#pragma strict

import System;
import System.IO;

var Filename : String = "save.ini";
private var rwfile : StreamWriter;
var x;
var y;
var z;
var Player : GameObject;

private var startTime : int;
private var timer1 : int;

function TimerSet() {startTime = Time.time;}

function TimerUpdate() {
    timer1 = Time.time;
    if(timer1 > 60) {
        Debug.Log("Saving");
        Write();
        TimerSet();}}

function WriterSetup() {
    Debug.Log("File Writer setup...");
    if (!File.Exists(Filename)) {
        rwfile = File.CreateText(Filename);}
    Debug.Log("File Writer configured sucsessfully");}

function Write() {
    rwfile = File.CreateText(Filename);
    x = Player.transform.position.x;
    y = Player.transform.position.y;
    z = Player.transform.position.z;
    rwfile.WriteLine(x);
    rwfile.WriteLine(y);
    rwfile.WriteLine(z);
    rwfile.Close();}

function Start() {Debug.Log("Saver Script Setup");
    WriterSetup();
    TimerSet();}

function Update() {TimerUpdate();}
</code>```

My error:

答:
Your error is telling you that it dosen't know what OpenText is. I don't see in your code anything about a function called OpenText, so i guess you were trying to use the File.OpenText function so you should change this line

```<code>rwfile = OpenText(Filename);
</code>```

To this

```<code>rwfile = File.OpenText(Filename);
</code>```

Also for the other errors you need to assigne your rwfile to a StreamWriter

```<code>private var rwfile : StreamWriter;
</code>```

You should also change your Write function for this:

```<code>function Write() {
    x = Player.transform.position.x;
    y = Player.transform.position.y;
    z = Player.transform.position.z;

    using (rwfile = File.CreateText(Filename))
    {
        rwfile.WriteLine(x);
        rwfile.WriteLine(y);
        rwfile.WriteLine(z);
        rwfile.Close();
    }
}
</code>```

Body:
I have successfully made a level with a Terrain, a Rigidbody FPS Controller from Standard Assets -> Characters and some other GameObjects. I now need to save my system so I have started to google file IO for UnityScript. I have found some examples but they return compiler errors (details below).

OS is Windows 10 64-bit. Unity version is 5.5.1f1 64-bit. Code editor is Visual Studio 2015, line endings corrected to Windows line endings. Language is UnityScript. Code I have used:

#pragma strict

import System;
import System.IO;

var Filename : String = "save.ini";
private var rwfile : StreamWriter;
var x;
var y;
var z;
var Player : GameObject;

private var startTime : int;
private var timer1 : int;

function TimerSet() {startTime = Time.time;}

function TimerUpdate() {
    timer1 = Time.time;
    if(timer1 > 60) {
        Debug.Log("Saving");
        Write();
        TimerSet();}}

function WriterSetup() {
    Debug.Log("File Writer setup...");
    if (!File.Exists(Filename)) {
        rwfile = File.CreateText(Filename);}
    Debug.Log("File Writer configured sucsessfully");}

function Write() {
    rwfile = File.CreateText(Filename);
    x = Player.transform.position.x;
    y = Player.transform.position.y;
    z = Player.transform.position.z;
    rwfile.WriteLine(x);
    rwfile.WriteLine(y);
    rwfile.WriteLine(z);
    rwfile.Close();}

function Start() {Debug.Log("Saver Script Setup");
    WriterSetup();
    TimerSet();}

function Update() {TimerUpdate();}

My error:

Body:
Your error is telling you that it dosen't know what OpenText is. I don't see in your code anything about a function called OpenText, so i guess you were trying to use the File.OpenText function so you should change this line

rwfile = OpenText(Filename);

To this

rwfile = File.OpenText(Filename);

Also for the other errors you need to assigne your rwfile to a StreamWriter

private var rwfile : StreamWriter;

You should also change your Write function for this:

function Write() {
    x = Player.transform.position.x;
    y = Player.transform.position.y;
    z = Player.transform.position.z;

    using (rwfile = File.CreateText(Filename))
    {
        rwfile.WriteLine(x);
        rwfile.WriteLine(y);
        rwfile.WriteLine(z);
        rwfile.Close();
    }
}


问:
UWP XAMARIN crashes in RELEASE mode (but good working in debug)
I use Xamarin Forms, UWP Project. In my Project I have file embedded as resources. In debug mode it compile and working good, but in release mode it crashes. What can I do?
I tried many tips, but nothing helped.

My errors:

```<code>Вызвано исключение: "System.IO.FileNotFoundException" в System.Private.Reflection.Core.dll
Вызвано исключение: "System.IO.FileNotFoundException" в System.Private.Reflection.Core.dll
"project.UWP.exe" (Win32). Загружено "C:\Windows\SysWOW64\Windows.Storage.ApplicationData.dll". Загрузка символов пропущена. Модуль состоит из машинного кода, а отладка машинного кода в данный момент отключена.
"project.UWP.exe" (Win32). Загружено "C:\Windows\SysWOW64\DWrite.dll". Загрузка символов пропущена. Модуль состоит из машинного кода, а отладка машинного кода в данный момент отключена.
"project.UWP.exe" (Win32). Загружено "C:\Windows\SysWOW64\Windows.Globalization.dll". Загрузка символов пропущена. Модуль состоит из машинного кода, а отладка машинного кода в данный момент отключена.
Вызвано исключение: "System.AggregateException" в System.Private.Threading.dll
Вызвано исключение: "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException" в Microsoft.CSharp.dll
Вызвано исключение: "System.Reflection.MissingMetadataException" в System.Private.CoreLib.dll
Дополнительные сведения: Reflection_InsufficientMetadata_NoHelpAvailable: EETypeRva:0x0001e930. For more information, visit http://go.microsoft.com/fwlink/?LinkId=623485

Вызвано исключение: "System.Reflection.TargetInvocationException" в System.Private.CoreLib.dll
Вызвано исключение: "System.Reflection.MissingMetadataException" в System.Linq.Expressions.dll
Дополнительные сведения: Reflection_InsufficientMetadata_NoHelpAvailable: EETypeRva:0x0001e930. For more information, visit http://go.microsoft.com/fwlink/?LinkId=623485

Вызвано исключение: "System.Reflection.MissingMetadataException" в Newtonsoft.Json.dll
Дополнительные сведения: Reflection_InsufficientMetadata_NoHelpAvailable: EETypeRva:0x0001e930. For more information, visit http://go.microsoft.com/fwlink/?LinkId=623485

Вызвано исключение: "System.Reflection.MissingMetadataException" в Newtonsoft.Json.dll
Дополнительные сведения: Reflection_InsufficientMetadata_NoHelpAvailable: EETypeRva:0x0001e930. For more information, visit http://go.microsoft.com/fwlink/?LinkId=623485

Исключение типа "System.Reflection.MissingMetadataException" возникло в Newtonsoft.Json.dll, но не было обработано в коде пользователя
Дополнительные сведения: Reflection_InsufficientMetadata_NoHelpAvailable: EETypeRva:0x0001e930. For more information, visit http://go.microsoft.com/fwlink/?LinkId=623485

Вызвано исключение: "System.Reflection.MissingMetadataException" в project.UWP.McgInterop.dll
Дополнительные сведения: Reflection_InsufficientMetadata_NoHelpAvailable: EETypeRva:0x0001e930. For more information, visit http://go.microsoft.com/fwlink/?LinkId=623485

Исключение типа "System.Reflection.MissingMetadataException" возникло в project.UWP.McgInterop.dll, но не было обработано в коде пользователя
Дополнительные сведения: Reflection_InsufficientMetadata_NoHelpAvailable: EETypeRva:0x0001e930. For more information, visit http://go.microsoft.com/fwlink/?LinkId=623485
</code>```

答: In release mode UWP apps are compiled with .NET Native tool chain. If you want using Reflection then you should add types in Default.rd.xml file DOC</p>

Body:
I use Xamarin Forms, UWP Project. In my Project I have file embedded as resources. In debug mode it compile and working good, but in release mode it crashes. What can I do?
I tried many tips, but nothing helped.

My errors:

Вызвано исключение: "System.IO.FileNotFoundException" в System.Private.Reflection.Core.dll
Вызвано исключение: "System.IO.FileNotFoundException" в System.Private.Reflection.Core.dll
"project.UWP.exe" (Win32). Загружено "C:\Windows\SysWOW64\Windows.Storage.ApplicationData.dll". Загрузка символов пропущена. Модуль состоит из машинного кода, а отладка машинного кода в данный момент отключена.
"project.UWP.exe" (Win32). Загружено "C:\Windows\SysWOW64\DWrite.dll". Загрузка символов пропущена. Модуль состоит из машинного кода, а отладка машинного кода в данный момент отключена.
"project.UWP.exe" (Win32). Загружено "C:\Windows\SysWOW64\Windows.Globalization.dll". Загрузка символов пропущена. Модуль состоит из машинного кода, а отладка машинного кода в данный момент отключена.
Вызвано исключение: "System.AggregateException" в System.Private.Threading.dll
Вызвано исключение: "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException" в Microsoft.CSharp.dll
Вызвано исключение: "System.Reflection.MissingMetadataException" в System.Private.CoreLib.dll
Дополнительные сведения: Reflection_InsufficientMetadata_NoHelpAvailable: EETypeRva:0x0001e930. For more information, visit http://go.microsoft.com/fwlink/?LinkId=623485

Вызвано исключение: "System.Reflection.TargetInvocationException" в System.Private.CoreLib.dll
Вызвано исключение: "System.Reflection.MissingMetadataException" в System.Linq.Expressions.dll
Дополнительные сведения: Reflection_InsufficientMetadata_NoHelpAvailable: EETypeRva:0x0001e930. For more information, visit http://go.microsoft.com/fwlink/?LinkId=623485

Вызвано исключение: "System.Reflection.MissingMetadataException" в Newtonsoft.Json.dll
Дополнительные сведения: Reflection_InsufficientMetadata_NoHelpAvailable: EETypeRva:0x0001e930. For more information, visit http://go.microsoft.com/fwlink/?LinkId=623485

Вызвано исключение: "System.Reflection.MissingMetadataException" в Newtonsoft.Json.dll
Дополнительные сведения: Reflection_InsufficientMetadata_NoHelpAvailable: EETypeRva:0x0001e930. For more information, visit http://go.microsoft.com/fwlink/?LinkId=623485

Исключение типа "System.Reflection.MissingMetadataException" возникло в Newtonsoft.Json.dll, но не было обработано в коде пользователя
Дополнительные сведения: Reflection_InsufficientMetadata_NoHelpAvailable: EETypeRva:0x0001e930. For more information, visit http://go.microsoft.com/fwlink/?LinkId=623485

Вызвано исключение: "System.Reflection.MissingMetadataException" в project.UWP.McgInterop.dll
Дополнительные сведения: Reflection_InsufficientMetadata_NoHelpAvailable: EETypeRva:0x0001e930. For more information, visit http://go.microsoft.com/fwlink/?LinkId=623485

Исключение типа "System.Reflection.MissingMetadataException" возникло в project.UWP.McgInterop.dll, но не было обработано в коде пользователя
Дополнительные сведения: Reflection_InsufficientMetadata_NoHelpAvailable: EETypeRva:0x0001e930. For more information, visit http://go.microsoft.com/fwlink/?LinkId=623485


问:
TestBench license and Jenkins on AWS
I've setup several headless UI tests using Vaadin TestBench but Jenkins fails due to licensing when running:

```<code>License for Vaadin TestBench 4 not found. Go to vaadin.com/pro for more details.
</code>```

The Vaadin documentation states to put the license file in the home directory, specifically stating /Users/<home> but that isn't a valid location for a RHEL EC2 instance.

I have tried placing my license file in /home/<user> and /home/<user>/ and even tried creating the /Users/ directory in case it is hardcoded to only check that location.

I've tried modifying the Jenkins Maven job to add the following into MAVEN_OPTS:

```<code>-Dvaadin.testbench.developer.license=<LICENSE>
</code>```

So far it always fails to find my license when running the test jobs.

What is the correct way to add licenses that Jenkins can access running on an AWS EC2 instance?

答:
Build settings in the Goals and options field
-Dvaadin.testbench.developer.license=<LICENSE>

Title: TestBench license and Jenkins on AWS

Body:
I've setup several headless UI tests using Vaadin TestBench but Jenkins fails due to licensing when running:

License for Vaadin TestBench 4 not found. Go to vaadin.com/pro for more details.

The Vaadin documentation states to put the license file in the home directory, specifically stating /Users/<home> but that isn't a valid location for a RHEL EC2 instance.

I have tried placing my license file in /home/<user> and /home/<user>/ and even tried creating the /Users/ directory in case it is hardcoded to only check that location.

I've tried modifying the Jenkins Maven job to add the following into MAVEN_OPTS:

-Dvaadin.testbench.developer.license=<LICENSE>

So far it always fails to find my license when running the test jobs.

What is the correct way to add licenses that Jenkins can access running on an AWS EC2 instance?


问:
Why can we not return a structure to a function?
Why can we not return a structure as a return value? I would also like to print it as well? I want to print the variables of the structure returned.

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

struct distance
{
    int feet;
    float inch;
};

distance add(struct distance d1,struct distance d2);

distance d3;
int main()
{
    struct distance dist1, dist2,dist3;
    printf("first distance\n");
    scanf("%d",&dist1.feet);
    scanf("%f",&dist1.inch);
    printf("second distance\n");
    scanf("%d",&dist2.feet);
    scanf("%f",&dist2.inch);
    dist3 = add(dist1,dist2);
    printf("sum of distances= %d\'-%.1f\"",dist3.feet,dist3.inch);
    return dist3;
}

 distance add(struct distance d1,struct distance d2){
    //Adding distances d1 and d2 and storing it in d3
    d3.feet = d2.feet+d1.feet;
    d3.inch = d2.inch+d1.inch;
    if(d3.inch>12){
        d3.inch-=12;
        ++d3.feet;
    }
}
</code>```

The following error message is displayed
prog.c:7:1: error: unknown type name ‘distance’
 distance add(struct distance d1,struct distance d2);

答:
Yes, of course you can return a structure, but you have to actually return it using the return statement:

```<code>struct distance add(struct distance d1, struct distance d2)
{
  d1.feet += d2.feet;
  d1.inches += d2.inches;
  while(d1.inches > 12)
  {
    ++d1.feet;
    d1.inches -= 12;
  }
  return d1;  /* Return the result. */
}
</code>```

Also no point in creating a d3 (and certainly not globally!), just use one of the arguments as the new value, and return that.

Using a loop to adjust for overflow is better, so I did that too.

Finally, you don't typedef the struct distance so you can't just say distance as the return type, it has to be struct distance like the arguments.

Body:
Why can we not return a structure as a return value? I would also like to print it as well? I want to print the variables of the structure returned.

#include <stdio.h>

struct distance
{
    int feet;
    float inch;
};

distance add(struct distance d1,struct distance d2);

distance d3;
int main()
{
    struct distance dist1, dist2,dist3;
    printf("first distance\n");
    scanf("%d",&dist1.feet);
    scanf("%f",&dist1.inch);
    printf("second distance\n");
    scanf("%d",&dist2.feet);
    scanf("%f",&dist2.inch);
    dist3 = add(dist1,dist2);
    printf("sum of distances= %d\'-%.1f\"",dist3.feet,dist3.inch);
    return dist3;
}

 distance add(struct distance d1,struct distance d2){
    //Adding distances d1 and d2 and storing it in d3
    d3.feet = d2.feet+d1.feet;
    d3.inch = d2.inch+d1.inch;
    if(d3.inch>12){
        d3.inch-=12;
        ++d3.feet;
    }
}

The following error message is displayed
prog.c:7:1: error: unknown type name ‘distance’
 distance add(struct distance d1,struct distance d2);

Body:
Yes, of course you can return a structure, but you have to actually return it using the return statement:

struct distance add(struct distance d1, struct distance d2)
{
  d1.feet += d2.feet;
  d1.inches += d2.inches;
  while(d1.inches > 12)
  {
    ++d1.feet;
    d1.inches -= 12;
  }
  return d1;  /* Return the result. */
}

Also no point in creating a d3 (and certainly not globally!), just use one of the arguments as the new value, and return that.

Using a loop to adjust for overflow is better, so I did that too.

Finally, you don't typedef the struct distance so you can't just say distance as the return type, it has to be struct distance like the arguments.


问:
is there a function in lodash to replace matched item
I wonder if there is a simpler method in lodash to replace an item in a JavaScript collection? (Possible duplicate but I did not understand the answer there:)

I looked at their documentation but could not find anything

My code is:

```<code>var arr = [{id: 1, name: "Person 1"}, {id:2, name:"Person 2"}];
// Can following code be reduced to something like _.XX(arr, {id:1}, {id:1, name: "New Name"});
_.each(arr, function(a, idx){
  if(a.id === 1){
    arr[idx] = {id:1, name: "Person New Name"};
    return false;
  }
});

_.each(arr, function(a){
  document.write(a.name);
});
</code>```

Update:
The object I'm trying to replace with has many properties like

{id: 1, Prop1: ..., Prop2:..., and so on}

Solution:

Thanks to dfsq but I found a proper solution within lodash that seems to work fine and is pretty neat and I put it in a mixin as well since I've this requirement at many places. JSBin

```<code>var update = function(arr, key, newval) {
  var match = _.find(arr, key);
  if(match)
    _.merge(match, newval);
  else
    arr.push(newval);
};

_.mixin({ '$update': update });

var arr = [{id: 1, name: "Person 1"}, {id:2, name:"Person 2"}];

_.$update(arr, {id:1}, {id:1, name: "New Val"});

document.write(JSON.stringify(arr));
</code>```

Faster Solution
As pointed out by @dfsq, following is way faster

```<code>var upsert = function (arr, key, newval) {
    var match = _.find(arr, key);
    if(match){
        var index = _.indexOf(arr, _.find(arr, key));
        arr.splice(index, 1, newval);
    } else {
        arr.push(newval);
    }
};
</code>```

答:
If the insertion point of the new object does not need to match the previous object's index then the simplest way to do this with lodash is by using _.reject and then pushing new values in to the array:

```<code>var arr = [
  { id: 1, name: "Person 1" },
  { id: 2, name: "Person 2" }
];

arr = _.reject(arr, { id: 1 });
arr.push({ id: 1, name: "New Val" });

// result will be: [{ id: 2, name: "Person 2" }, { id: 1, name: "New Val" }]
</code>```

If you have multiple values that you want to replace in one pass, you can do the following (written in non-ES6 format):

```<code>var arr = [
  { id: 1, name: "Person 1" },
  { id: 2, name: "Person 2" },
  { id: 3, name: "Person 3" }
];

idsToReplace = [2, 3];
arr = _.reject(arr, function(o) { return idsToReplace.indexOf(o.id) > -1; });
arr.push({ id: 3, name: "New Person 3" });
arr.push({ id: 2, name: "New Person 2" });

// result will be: [{ id: 1, name: "Person 1" }, { id: 3, name: "New Person 3" }, { id: 2, name: "New Person 2" }]
</code>```

Body:
I wonder if there is a simpler method in lodash to replace an item in a JavaScript collection? (Possible duplicate but I did not understand the answer there:)

I looked at their documentation but could not find anything

My code is:

var arr = [{id: 1, name: "Person 1"}, {id:2, name:"Person 2"}];
// Can following code be reduced to something like _.XX(arr, {id:1}, {id:1, name: "New Name"});
_.each(arr, function(a, idx){
  if(a.id === 1){
    arr[idx] = {id:1, name: "Person New Name"};
    return false;
  }
});

_.each(arr, function(a){
  document.write(a.name);
});

Update:
The object I'm trying to replace with has many properties like

{id: 1, Prop1: ..., Prop2:..., and so on}

Solution:

Thanks to dfsq but I found a proper solution within lodash that seems to work fine and is pretty neat and I put it in a mixin as well since I've this requirement at many places. JSBin

var update = function(arr, key, newval) {
  var match = _.find(arr, key);
  if(match)
    _.merge(match, newval);
  else
    arr.push(newval);
};

_.mixin({ '$update': update });

var arr = [{id: 1, name: "Person 1"}, {id:2, name:"Person 2"}];

_.$update(arr, {id:1}, {id:1, name: "New Val"});

document.write(JSON.stringify(arr));

Faster Solution
As pointed out by @dfsq, following is way faster

var upsert = function (arr, key, newval) {
    var match = _.find(arr, key);
    if(match){
        var index = _.indexOf(arr, _.find(arr, key));
        arr.splice(index, 1, newval);
    } else {
        arr.push(newval);
    }
};

Body:
If the insertion point of the new object does not need to match the previous object's index then the simplest way to do this with lodash is by using _.reject and then pushing new values in to the array:

var arr = [
  { id: 1, name: "Person 1" },
  { id: 2, name: "Person 2" }
];

arr = _.reject(arr, { id: 1 });
arr.push({ id: 1, name: "New Val" });

// result will be: [{ id: 2, name: "Person 2" }, { id: 1, name: "New Val" }]

If you have multiple values that you want to replace in one pass, you can do the following (written in non-ES6 format):

var arr = [
  { id: 1, name: "Person 1" },
  { id: 2, name: "Person 2" },
  { id: 3, name: "Person 3" }
];

idsToReplace = [2, 3];
arr = _.reject(arr, function(o) { return idsToReplace.indexOf(o.id) > -1; });
arr.push({ id: 3, name: "New Person 3" });
arr.push({ id: 2, name: "New Person 2" });

// result will be: [{ id: 1, name: "Person 1" }, { id: 3, name: "New Person 3" }, { id: 2, name: "New Person 2" }]